Introduction to C Programming Basics
Introduction to C Programming Basics
1. History
C is a programming language developed at AT& T’s (American Telephone & Telegraph)
Bell Laboratories of USA in 1972. It was designed and written by a man named Dennis
Ritchie. It is developed to overcome the problems of previous languages such as B, BCPL,
etc.
C as a language was in use by 1973, although extra functionality such as new types was
introduced up until 1980. In 1978 the publication of The C ProgrammingLanguage by
Kernighan & Ritchie caused a revolution in the computing world.
In 1983, the American National Standards Institute (ANSI) established a committee to
provide a modern, comprehensive definition of C. The resulting definition, the ANSI
standard, or "ANSI C", was completed late 1988.
Compilers: It is a program which is used to convert the high level language programs
into machinelanguage. The code in a source file stored on the disk must be translated
into machine language. This is the job of the compiler. The Compiler is a computer
program that translates the source code written in a high-level language into the
corresponding object code of the low-level language. This translation process is called
compilation. The entire high level program is converted into the executable machine
code file. The Compiler which executes C programs is called as C Compiler. Example
Turbo C, Borland C, GC etc.,
Algorithm is a finite sequence of instructions, each of which has a clear meaning and
can be performed with a finite amount of effort in a finite length of time. No matter
what the input values may be, an algorithm terminates after executing a finite number
of [Link] represent an algorithm using a pseudo language that is a
combination of the constructs of a programming language together with informal
English [Link] ordered set of instructions required to solve a problem is known
as an algorithm.
The characteristics of a good algorithm are:
Precision – the steps are precisely stated(defined).
Uniqueness – results of each step are uniquely defined and only depend on
theinput and the result of the precedingsteps.
Finiteness – the algorithm stops after a finite number of instructions areexecuted.
Example
Different symbols are used for different states in flowchart, For example: Input/Output
and decision making has different symbols. The table below describes all the symbols
that are used in making flowchart
Source Code
Documentation Section
Header Files:
#include
Manifest Constants:
#defines
Int main(void)
--body of program—
int main(){
//printing information
printf("Hello C");
return 0;
Syntax:
/* code
to be commented */
Example:
#include<stdio.h>
int main(){
/*printing information
Multi-Line Comment*/
printf("Hello C");
return 0;
}
# defines:
ANSI C allows you to declare constants. The # define directive is used to tell the
preprocessor to perform a search-and-replace operation.
Example:
# define Pi 3.14159
# define Tax-rate 0.0735
In the example above, the preprocessor will search through the source file and replace
every instance of the token Pi with 3.14159
After performing the search and replace operation, the preprocessor removes the
# define line.
User supplied function prototypes:
Declares the user-written functions actually defined later in the source file. A function
prototype is a statement (rather than an entire function declaration) that is placed a
head of a calling function in the source code to define the function's label before it is
used. A function prototype is simply a reproduction of a function header (the first line of
a function declaration) that is terminated with a semi-colon.
User-written functions:
Divide the application into logical procedural units and factor out commonly used code to
eliminate repetition
6. C Tokens
C tokens are the basic buildings blocks in C language which are constructed together to
write a C [Link] and every smallest individual unit in a C program is known as C
tokens. C tokens are of six types.
They are
Keywords (eg: int,while),
Keywords
C keywords are the words that convey a special meaning to the c compiler. The
keywords cannot be used as variable names. In the C programming language,
keywords are special words with predefined meaning. Keywords are also known
as reserved words in C programming language. In the C programming language,
there are 32 keywords. All the 32 keywords have their meaning which is already
known to the compiler.
Properties of Keywords
1. All the keywords in C programming language are defined as lowercase letters so they must
be used only in lowercase letters
2. Every keyword has a specific meaning, users can not change that meaning.
3. Keywords can not be used as user-defined names like variable, functions, arrays, pointers,
etc...
4. Every keyword in C programming language represents something or specifies some kind of
action to be performed by the compiler.
volatile while
Variables
Variables in a c programming language are the named memory locations where the user can
store different values of the same datatype during the program execution. That means a
variable is a name given to a memory location in which we can store different values of the
same data type.
In other words, a variable can be defined as a storage container to hold values of the same
datatype during the program execution. The formal definition of a data type is as follows...
Every variable in c programming language must be declared in the declaration section before
it is used. Every variable must have a datatype that determines the range and type of values
be stored and the size of the memory to be allocated.
A variable name may contain letters, digits and underscore symbol. The following are the
rules to specify a variable name...
Declaration of Variable
Declaration of a variable tells the compiler to allocate the required amount of memory with
the specified variable name and allows only specified datatype values into that memory
location.
In C programming language, the declaration can be performed either before the function as
global variables or inside any block or function. But it must be at the beginning of block or
function.
Declaration Syntax:
Example:
int number;
The above declaration tells to the compiler that allocates 2 bytes of memory with the
name number and allows only integer values into that memory location.
Data types in the c programming language are used to specify what kind of value can be
stored in a variable. The memory size and type of the value of a variable are determined by
the variable data type.
The primary data types in the C programming language are the basic data types. All the
primary data types are already defined in the system. Primary data types are also called as
Built-In data types. The following are the primary data types in c programming language...
Type Description
The integer data type is a set of whole numbers. Every integer value does not have the
decimal value. We use the keyword "int" to represent integer data type in c. We use the
keyword int to declare the variables and to specify the return type of a function. The integer
data type is used with different type modifiers like short, long, signed and unsigned.
int will be 2 bytes or 16 bits in the case of an environment that is 16-bit. However, int will
be 4 bytes or 32 bits in case of an environment that is 32-bit.
Syntax:
int
int num1;
Floating-point data types are a set of numbers with the decimal value. Every floating-point
value must contain the decimal value. We use the keyword "float" to represent floating-point
data type. The float value contains 6 decimal places. The size of the float data type is
basically 32 bits or 4 bytes.
Syntax:
float ;
float num1;
Example: 9.125,
double data type are a set of numbers with the decimal value. double is same as float but
with longer precision and takes double space (8 bytes) than float. To extend the precision
further we can use long double which occupies 10 bytes of memory space. It is capable of
storing values that are comparatively double the size of the bytes that the float data type can
store. This is the reason why it is known as the double. This data type is capable of holding
about 15-17 digits, both after and before the decimal of the data type.
Syntax:
double num2;
Example: 3.1254.
Character type variable can hold a single character and are declared by using the keyword
char. The character data type is a set of characters enclosed in single quotations. The size of
the char data type is basically 8 bits or 1 byte.
Syntax:
char ;
char ch = ‘a’;
Example: a, b, g, S, j.
Void Type:
Void data type is a data type used to indicate nothing or null. Void doesn't have any
meaning. Void data type cannot hold any data type because it is an empty data type. Void
data type is not useful for declaring variables or identifiers but it is useful in the case of
functions while returning a value. You can find the importance of void data type in functions
in the next articles.
Operators
Arithmetic
[Link] Operators Operation Example
1 + Addition A+B
2 – Subtraction A-B
3 * multiplication A*B
4 / Division A/B
5 % Modulus A%B
Example:
#include <stdio.h>int
main()
{
int a=40,b=20,add,sub,mul,div,mod;
add =a+b;
sub = a-b;
mul = a*b;
div = a/b;
mod = a%b;
printf("Addition of a, b is : %d\n", add);
printf("Subtraction of a, b is : %d\n", sub);
printf("Multiplication of a, b is : %d\n",
mul); printf("Division of a, b is : %d\n",
div); printf("Modulus of a, b is : %d\n",
mod);
}
Output:
Addition of a, b is : 60
Subtraction of a, b is : 20
Multiplication of a, b is : 800
Division of a, b is : 2
Modulus of a, b is : 0
2. Assignmentoperators
In C programs, values for the variables are assigned using assignment operators.
Forexample,ifthevalue10istobeassigned forthevariable sum,itcanbe assignedas
sum= 10;
Other assignment operators in C language are given below.
Simple
= sum = 10
assignme
10 is assigned to variable sum
nt
operator
Example:
# include <stdio.h>
int main()
{
int Total=0,i;
for(i=0;i<10;i++)
{
Total+=i; // This is same as Total = Toatal+i
}
printf("Total = %d", Total);
}
Output:
Total = 45
3. Relationaloperators
Relational operators are used to find the relation between two variables. i.e. to compare the
values of two variables in a Cprogram.
x is greater than y
1 > x>y
5 == x == y x is equal to y
x is not equal to y
6 != x != y
Example:
#include<stdio.h>
int main()
{
int m=40,n=20;
if (m == n)
{
printf("m and n are equal");
}
else
{
printf("m and n are not equal");
}
}
Output:
4. Logicaloperators
These operators are used to perform logical operations on the given expressions.
There are 3 logical operators in C language. They are, logical AND (&&), logical OR (||)
and logical NOT (!).
If―((x>5)
&& (y<5))‖ is true, logical
NOT operator makes
itfalse
Example:
#include <stdio.h>
int main()
{
int m=40,n=20;
int o=20,p=30;
if (m>n &&m !=0)
{
printf("&& Operator : Both conditions are true\n");
}
if (o>p || p!=20)
{
printf("|| Operator : Only one condition is true\n");
}
if (!(m>n && m !=0))
{
printf("! Operator : Both conditions are true\n");
}
else
{
printf("! Operator : Both conditions are true.
" \ "But, status is inverted as false\n");
}
}
Output:
5. Bitwiseoperators
The bitwise operators are the operators used to perform the operations on the data at the
bit-level. When we perform the bitwise operations, then it is also known as bit-level
programming. It consists of two digits, either 0 or 1. It is mainly used in numerical
computations to make the calculations faster.
We have different types of bitwise operators in the C programming language.
The followingis the list of the bitwise operators:
Operator Meaning of operator
& Bitwise AND operator
| Bitwise OR operator
^ Bitwise exclusive ORoperator
~ One's complement operator(unary operator)
<< Left shift operator
1 1 1 1 1
Example :
#include <stdio.h>
int main()
{
int a=6, b=14; // variable declarations
printf("The output of the Bitwise AND operator a&b is %d",a&b);
return 0;
}
Output:
The output of Bitwise AND operator a&b is 6
Bitwise OR operator
The bitwise OR operator is represented by a single vertical sign (|). Two integer operands
are written on both sides of the (|) symbol. If the bit value of any of the operand is 1, then the
output would be 1, otherwise 0.
For example,
We consider two variables,
a = 23;
b = 10;
The binary representation of the above two variables would be:
a = 0001 0111
b = 0000 1010
When we apply the bitwise OR operator in the above two variables, i.e., a|b , then the output
would be:
Result = 0001 1111
Example:
#include <stdio.h>
int main()
{
int a=23,b=10; // variable declarations
printf("The output of the Bitwise OR operator a|b is %d",a|b);
return 0;
}
Output:
The output of the Bitwise OR operator a|b is 31
Bitwise exclusive OR operator
Bitwise exclusive OR operator is denoted by (^) symbol. Two operands are written on both
sides of the exclusive OR operator. If the corresponding bit of any of the operand is 1 then
the output would be 1, otherwise 0.
For example,
We consider two variables a and b,
a = 12;
b = 10;
The binary representation of the above two variables would be:
a = 0000 1100
b = 0000 1010
When we apply the bitwise exclusive OR operator in the above two variables (a^b), then the
result would be:
Result = 0000 1110
Example:
#include <stdio.h>
int main()
{
int a=12,b=10; // variable declarations
printf("The output of the Bitwise exclusive OR operator a^b is %d",a^b);
return 0;
}
Output:
The output of the Bitwise exclusive OR operator a^b is 6
Bitwise complement operator
The bitwise complement operator is also known as one's complement operator. It is
represented by the symbol tilde (~). It takes only one operand or variable and performs
complement operation on an operand. When we apply the complement operation on any
bits, then 0 becomes 1 and 1 becomes 0.
For example,
If we have a variable named 'a',
a = 8;
The binary representation of the above variable is given below:
a = 1000
When we apply the bitwise complement operator to the operand, then the output would be:
Result = 0111
Example:
#include <stdio.h>
int main()
{
int a=8; // variable declarations
printf("The output of the Bitwise complement operator ~a is %d",~a);
return 0;
}
Output
The output of the Bitwise complement operator ~a is 7
Bitwise shift operators
Two types of bitwise shift operators exist in C programming. The bitwise shift operators will
shift the bits either on the left-side or right-side. Therefore, we can say that the bitwise shift
operator is divided into two categories:
Left-shift operator
Right-shift operator
Left-shift operator
It is an operator that shifts the number of bits to the left-side.
Syntax of the left-shift operator is given below:
Operand << n
Where,Operand is an integer expression on which we apply the left-shift operation.
n is the number of bits to be shifted.
In the case of Left-shift operator, 'n' bits will be shifted on the left-side. The 'n' bits on the
left
side will be popped out, and 'n' bits on the right-side are filled with 0.
For example,
Suppose we have a statement:
int a = 5;
The binary representation of 'a' is given below:
a = 0101
If we want to left-shift the above representation by 2, then the statement would be:
a << 2;
0101<<2 = 00010100
Example :
#include <stdio.h>
int main()
{
int a=5; // variable initialization
printf("The value of a<<2 is : %d ", a<<2);
return 0;
}
Output
The value of a<<2 is : 20
Right-shift operator
It is an operator that shifts the number of bits to the right side.
Syntax of the right-shift operator is given below:
Operand >> n;
Where,Operand is an integer expression on which we apply the right-shift operation.
N is the number of bits to be shifted.
In the case of the right-shift operator, 'n' bits will be shifted on the right-side. The 'n' bits on
the right-side will be popped out, and 'n' bits on the left-side are filled with 0.
For example,
Suppose we have a statement, int a = 7;
The binary representation of the above variable would be: a = 0111
If we want to right-shift the above representation by 2, then the statement would be:
a>>2;
0000 0111 >> 2 = 0000 0001
Let's understand through a program.
#include <stdio.h>
int main()
{
int a=7; // variable initialization
printf("The value of a>>2 is : %d ", a>>2);
return 0;
}
Output : The value of a>>2 is : 1
Conditional operators return one value if condition is true and returns another value is
condition is false.
In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if
else conditional statements.
Example
#include <stdio.h>int
main()
{
int x=1, y;
y = ( x ==1 ? 2 : 0 ) ;
printf("x value is %d\n", x);
printf("y value is %d", y);
}
Output:
x value is 1
y value is 2
7. Increment/decrementoperators
Increment operators are used to increase the value of the variable by one and
decrement operators are used to decrease the value of the variable by one in
Cprograms.
Below table will explain the difference between pre/post increment and decrement operators
in C.
Syntax:
Increment operator: ++var_name ;( or) var_name++;
Decrement operator: – -var_name; (or) var_name – -;
Example:
#include <stdio.h>
int main()
{
int i=1;
while(i<10)
{
123456789
int i=20;
while(i>10)
{
20 19 18 17 16 15 14 13 12 11
8. Specialoperators
Below are some of special operators that C language offers.
Formatted Output
The function printf() is used for formatted output to standard output based on a format
specification. The format specification string, along with the data to be output, are the
parameters to the printf() function.
Syntax:
printf (format,data1,data2,…);
In this syntax format is the format specification string. This string contains, for each
variable to be output, a specification beginning with the symbol % followed by a
character called the conversion character.
Example:
printf(―%c‖, data1);
The character specified after % is called a conversion character because it allows one
data type to be converted to another type and printed.
See the following table conversion character and their meanings.
Conversion Meaning
Character
d The data is converted to decimal (integer)
C The data is taken as a character.
S The data is a string and character from the string , are printed
until a NULL,
character is reached.
F The data is output as float or double with a default Precision 6.
Symbols Meaning
\n For new line (linefeed return)
\t For tab space (equivalent of 8 spaces)
Example
printf(―%c\n‖,data1);
Example
The text "Character is:" is printed out along with the value of data1.
Main()
{
Char alphabh="A";
float number2=22.34;
printf(“char= %c\n”,&alphabh);
printf(“int= %d\n”,&number1);
printf(“float= f\n”,&number2);
getch();
clrscr();
retrun 0;
}
Output Here…
char =A
int= 55
flaot=22.340000
Formatted Input
The function scanf() is used for formatted input from standard input and provides
many of the conversion facilities of the function printf().
Syntax
The function scnaf() reads and converts characters from the standards input depending
on the format specification string and stores the input in memory locations represented
by the other arguments (num1, num2,….).
For Example:
scanf(―%c %d‖,&Name,&Roll No);
Unformatted I/O Statements
Unformatted I/O refers to operations that reads or writes data without any format.
Unformatted input and output functions read a single input sent by the user.
Unformatted Input and Output functions take the character, character array, and strings as
input. We can read-only character data types with these functions. These functions are
already defined in the libraries. It reads only a single input from the user and displays the
value on the console output screen.
1. getch()
2. getche()
3. getchar()
4. putchar()
5. gets()
6. puts()
7. putch()
1. getch():
getch() function is a built-in function declared in conio.h header file. It reads a single
character from the keyboard. The input character won't be displayed on the console Output
screen. getch() function immediately returns the input character without pressing the enter
key.
getch() is also used for hold the output screen.
Syntax:
getch() or variable name= getch();
Example:
#include <conio.h>
#include <stdio.h>
int main()
{
Char ch;
printf("Enter any character: ");
ch=getch(); // A character is entered, but it won't be displayed on the screen
printf(“character is %c”,ch);
return 0;
}
getche():
getche() function is a built-in function declared in conio.h header file. It reads a single
character from the keyboard. The input character will be displayed on the console Output
screen. getch() function immediately returns the input character without pressing the enter
key.
In this function, we won't pass any parameters
Syntax:
getche() or variable name= getche();
Example:
#include <conio.h>
#include <stdio.h>
int main()
Char ch;
printf("Enter any character: ");
printf(“character value:%c”,ch);
return 0;
getchar():
getchar() function is a built-in function declared in stdio.h header file. It reads a single
character from the keyboard if the user enters multiple characters or a single character.
In this function, we won't pass any parameters
Syntax
Example
#include <stdio.h>
int main()
printf(" \nThe entered character is: %c", ch); // printing the entered character
return 0;
}
In the output, we gave the input as "Hello", but in the output, it displayed only H. By this,
we can say only the first character is considered in the getchar() function.
gets():
gets() is a built-in function present stdio.h header file. By using gets() function, we can read
the collection of characters or a string. We should have to declare a character array to store
the string. This function allows spaces in the string.
This function takes a character or a string as a parameter
Syntax:
gets(str);
Example
#include <stdio.h>
int main()
return 0;
}
putchar():
putchar() is a built-in function present stdio.h header file. It displays a single character from
the keyboard if the user enters multiple characters or a single character.
We can pass the character into the function or by passing a variable which has stored a
[Link]() prints a single character.
It takes a single character or a variable as parameter. And return a character on the console
output screen.
Syntax:
putchar(variable_name);
It takes a single character or a variable as parameter. And return a character on the console
output screen.
Example
#include <stdio.h>
int main()
putchar(ch); // method 1
putchar('A'); // Method 2
return 0;
}
puts():
puts() is a built-in function present stdio.h header file. By using puts() function, we can print
the collection of characters or a string. We should have to declare a character array to store
the string. This function also prints spaces between the characters.
Syntax:
puts( character array);
This function takes a character array or a string as a parameter. And returns a string or a
character array on the console output screen.
Example:// program to implement the gets() function in C
#include <stdio.h>
int main()
printf(" \nThe Entered string is: %s",str); // printing the string using printf()
return 0;
}
Output:
7. putch():
putch() function is a built-in function in C present in conio.h header file. It is used to display
a single character on the console output screen.
Syntax:
putch( variable name );
This function takes a single character or a variable as a parameter. And it returns a single
character on the console output screen.
Example program:// program to implement the putch() function in C
#include <stdio.h>
int main()
Charch;
printf("\nTheEntered character is: "); // Displays that character on the console output screen
return 0;
}
Output: