C Introduction
This is a step-by-step method to solve a particular problem.
This is a pictorial representation for flow of information.
This is a series of meaningful instructions written in a particular order to do a specific task.
Computer is a machine, it cannot think and act by it's own as the human being does. So we need to tell it what to do and how to do it. The series of meaningful instructions written in a particular order to carry out a specific task which is known as a program. Thus the programs are written in some languages and such languages are known as programming languages.
Basically there are different categories of programming languages.
The program written using the binary digits specified for a particular processor is known as the machine language of the computer. It consists of series of binary digits i.e. 1's and 0's and this is the language the processor understands without any interfaces.
This language uses the mnemonics or abbreviations, symbols etc. to represent an instruction to a specific processor. The programs written in this language is converted into it's machine level language equivalent by a software (program) known as an Assembler.
These languages are machine independent languages.
This is a program which translates the program written in assembly level language into it's machine level language equivalent.
This is a program which translates a program written in higher level language into machine level language equivalent, one statement at a time and executes it immediately.
This is a program which translates the entire program into it's machine level language equivalent and then executes it.
Because of the outgrowth of two earlier languages called BCPL (Basic Combined Programming Language) and B the language C emerged. In 1970, this language was developed by Dennis Ritchie at Bell Telephone Laboratory Inc., now known as AT&T Bell Laboratories Inc. Brian Kernighan and Ritchie published a definite description about C in 1978.
C is often called as miple level language. Since it is designed to have relatively faster program execution as compared to Assembly and Machine level language which are known as low level language. It also has relatively faster program development feature as compared to higher-level language.
Every language has a grammer and meaning. Thus C Programming language also has its grammer and meaning. The grammer of C is called as syntax and meaning of the language is called as semantic. So to learn C language we have to learn the grammer of C then using this language useful programs can be writtern.
The smallest individual units of a C program are called as C tokens.
Following are the six C tokens
C language has its characters categorized into following groups.
a to z, A to Z
0 to 9
~ ' ! @ # % ^ & * ( ) -_ + / = \ | { } [ ] : ; " ' < > , .?
Blank spaces, Horizontal tab, Carriage return, Form Feed, Newlines
These are the words whose meaning is already been explained to C compiler. Keywords cannot be used as variable names and if we try to do so that means we are trying to assign new meaning to the key word and it is not allowed.
auto | break | case | char | const | continue |
default | do | double | else | enum | extern |
float | far | for | goto | if | int |
long | near | register | return | short | signed |
static | struct | switch | typedef | union | unsigned |
void | while |
These refer to the names of variables, arrays and functions. These are the user given names. It can consist of digits, characters and special symbols. Both lowercase and uppercase characters can be used.
This is a quantity that will not change. This quantity can be stored in a memory location and a name can be given to it.
These are the group of characters enclosed within the double quotation marks. The characters may be letters, digits, special symbols and space.
These are symbols used in a C statement. For example underscore symbol can be used to join two words which make a function name or variable name.
These are used in mathematical and logical operations.
The alphabets, number and special symbols when properly combined will form variables. This is a name given to a location in memory where some value can be stored which can be altered also in the program.
area, radius1, si_int
When the value is required to be stored in a variable, we must first of all
identify the kind of data we are going to store in that variable and memory required
by that data type.
Following is the table, which gives different basic (premitive) data
types, their description, memory required by them. (Detailed table is given in the
Annexure.)
Data type |
Description |
Memory requirements |
Range of values |
---|---|---|---|
char |
Single character |
1 byte |
-128 to 127 |
int |
Integer quantity |
2 bytes |
-32768 to 32767 |
float |
Real quantity |
4 bytes |
3.4e-38 to 3.4e+38 |
double |
Real quantity |
8 bytes |
1.7e-308 to 1.7e+308 |
This section is used to give details about
the program, name of the program, name of the author of the program.
These are all used as comment lines. The comment lines are not processed.
This section provides instructions to the compiler to include files so as to link functions from the C library.
All symbolic constants are defined in this section.
If a variable is required to be used in different functions of a program then it is declared in this section so that it is available to all the different functions of an entire program.
Every C program must have this function. This function tells the beginning of the program. main( ) contains two parts one is the declaration part and the other is the executable part. In the declaration part all the variables used by the statements appearing in the executable part are declared and the executable part contains all the executable statements. The declaration part and executable part must appear in between the opening and closing brace. The program execution begins at the opening brace and ends at the closing brace. All the statements that appear in declaration part and executable part must end with a semicolon ( ; ).
This section contains all the user defined functions that are called by the statements in the main( ) function or the other user defined functions. Although these user defined functions can be placed anywhere in the program, they are generally placed immediately after the main( ) function.
The lines beginning with /* and ending with */ are known as comment lines. These lines can be used any where in the program to enhance the readability and understanding of the program. Comment lines are not executable statements and therefore anything between /* and */ is ignored by the compiler.
This defines certain functions and the programmer can make use
of these to write efficient programs. These library functions are defined in different
header files. These files have the extension as 'h'. Instead of programmer
The second line is used to include the header file stdio.h, because the function printf() which is used in this program is defined in the header file stdio.h.
The third line indicates the beginning of the program with the function name main().
The fourth line is the open brace after which you can have executable statements.
The fifth line has a statement to print the message. Here the built in C library function printf() is used.
The sixth line, which has a brace, indicates the end of the program.
There are different methods to invoke TC editor. I will discuss one method. Let us
assume TC shortcut is present on your desktop. Double click on TC shortcut, you will get
TC editor which is shown in the figure 1.
writing instructions to do a specific task he can use already existing code written and
placed in the form of functions in the C library.
Now let us write our first C program using a library function printf() to display a message
on the monitor.
/* This is the First C program */
#include
main()
{
printf(" Welcome to the wonder world of C\n");
}
In the above program the first line is the comment line.
1) Invoke TC editor
:
Procedure to write and execute the program using Turbo C:
Figure 1
Type the above given program. To save the program Press Alt key and f key simultaneously you will get a drop down menu as shown in Figure 2. Then select the save option and then save it with a name given to it and extension as c,
for example T3.C.
Figure 2
The program written is required to be compiled so press Alt and c key simultaneously, you will get a drop down menu as shown in Figure 3. From the resulting menu press c key. If there are any errors it is shown in the menu and correct the errors, otherwise you will get a screen which shows the compilation is successful and press any key
In the program, Operators are used to manipulate data and variables using which mathematical and logical expressions can be written. C operators can be classified into different categories as shown below.
1) Arithmetic operators:
+, -, *, /, % (modulo division).
> (greater than), < (less than), >= (greater than or equal to), <= (less than or equal to), = = (equal to), != (Not equal to).
These operators are used to form the relational expressions.
Example: a >= b, c < d
&& (Logical AND), || (Logical OR), ! (Logical NOT)
This operator is used to assign some value to some variable.
A ternary operator pair ?: is available in C to construct conditional expression of the form
In the above program a, b and x are the integer variables because they
are declared with the key word int. Because of this declaration two bytes are reserved
for each of the variables in memory.
Figure showing the allocation of memory to variables
The value 5 is stored in memory location identified as a and value 10 is stored in memory location identified as b. After the evaluation of the expression value 10 is stored in the variable x. The expression is evaluated from left to right. If the value of a is greater than value of b, value of a is stored in x otherwise value of b is stored in x. In our case since value of a is not greater than b value of b that is 10 is stored in variable x, which is shown in the figure given below.
Figure showing storage of values in memory locations These operators are used for manipulation of data at bit level. Following is the list of bitwise manipulation operators.
In all cases Operand1 and Operand2 specifies the values. The following example demonstrates the usage of all bitwise operators.
/* Program to test different bitwise operators*/ #include
Expression 1 ? Expression 2 : Expression 3;
The operator pair works as given below:
The entire expression is evaluated from left to right.
Expression 1 is evaluated first, if it is non zero (true) then Expression 2 is evaluated and becomes the value of the expression. If Expression 1 is false (not true) Expression 3 is evaluated and its value becomes the value of the expression. So only one of the Expressions either Expression 2 or Expression 3 is evaluated and not the both during a given evaluation.
Now let us write a program, which will use the ternary operator pair.
/* Program to test ternary operator pair */
#include
main()
{
int a, b, x;
a=5;
b=10;
x=(a>b) ? a:b;
printf(" Value of x is %d\n",x);
}
Syntax: operand1 >> operand2;
Shift right operator shifts bits of operand1 right by distance operand2.
Syntax: operand1 << operand2;
Shift left operator shifts bits of operand1 left by distance operand2.
Syntax: operand1 >>> operand2;
Shift right operator unsigned shifts bits of operand1 right by distance operand2 (unsigned).
Syntax: operand1 & operand2;
AND operation is performed on operand1 and operand2 bitwise.
Syntax: operand1 | operand2;
OR operation is performed on operand1 and operand2 bitwise.
Syntax: operand1 ^ operand2;
OR operation is performed on operand1 and operand2 bitwise.
Syntax: ~operand1;
Bitwise compliment operation is performed on operand1.
Note:
#include
void main()
{
int operand1,operand2,result;
printf("Enter Values for Shift operations\n");
printf("\nEnter the value for operand1:");
scanf("%d",&operand1);
printf("Enter the value for operand2:");
scanf("%d",&operand2);
result=operand1>>operand2;
printf("\nResult of bitwise Shift right operation is: %d\n",result);
result=operand1<<operand2;
printf("Result of bitwise Shift left operation is: %d\n",result);
printf("\nEnter Values for Logical operations\n");
printf("\nEnter the value for operand1:");
scanf("%d",&operand1);
printf("Enter the value for operand2:");
scanf("%d",&operand2);
result=operand1 & operand2;
printf("\nResult of bitwise AND operation is: %d\n",result);
result=operand1 | operand2;
printf("Result of bitwise OR operation is: %d\n",result);
result=operand1 ^ operand2;
printf("Result of bitwise XOR operation is: %d\n",result);
result=~operand1;
printf("Result of bitwise Compliment operation on operand1: %d\n",result);
}
Output:
Comma operator, sizeof operator, pointer operator ( *, &) and member selection operator (. , ->).
Comma operator:
The comma operator can be used to link the related expression together. A comma linked lists of expression are evaluated left to right and the value of right most expression is the value of the combined expression.
Example:
a=(x=10, y=15, x+y);
In the above example value 10 is assigned to x then the value 15 is assigned to y and the apition of two values 10 and 15 is assigned to a. Since comma operator has the lowest precedence of all operators the parenthesis is required.
The Sizeof operator: The sizeof is a compile time operator. When it is used with an operand it returns the number of bytes the operand occupies. The operand may be a data type qualifier, variable, or a constant.
Example:
n=sizeof(b);
n=sizeof(float);
In the above example sizeof operator will return the number of bytes allocated to the variable b. So if b is an integer variable n will have the value 2 and if b is a float variable n will have the value as 4. Similarly in the second example the argument used with the sizeof operator is float so now n will have the value as 4.
Note:
Pointer operator and member selection operator are explained in chapters Pointers and Structures and Unions respectively.
When the operands in a single arithmetic expression are integers, then the expression is called integer arithmetic. Integer values are yielded by integer arithmetic.
Example:
a= 14 , b=4
x = a + b; x will have the value as 18
x = a - b; x will have the value 10
x = a * b; x will have the value 56
x = a / b; x will have the value 3. The decimal part is truncated
x = a % b; x will have the value 2. This operation yields the remainder after division.
An arithmetic operation involving real operands is called real arithmetic.
Example:
x = 3.0 / 2.0 = 1.5
Y = 5.0 / 2.0 = 2.5
When one of the operands is integer and other is real the expression is called as mixed mode arithmetic expression. If either operand is of real type then only the real operation is performed and the result is always a real value.
x = 15/10.0 = 1.5 y = 15.0 / 10 = 1.5
The variable x and y should be of real data type.
An arithmetic expression without parenthesis will be evaluated from left to right using the rules of precedence of operators.
Assignment |
=, +=, -=, *=, /=, %= |
---|---|
Conditional |
? : |
Relational |
<, >, <=, >=
= = , ! = |
Arithmetic |
*, /, %
+, - |
Unary |
! , ++, -- |
Parenthesis |
( ) |
Logical |
&&, || |
Example 1.
2 + 3 * 2 / 2-1
2 + 6 / 2 - 1
2 + 3 - 1
5 - 1
4
3 * 2 + 3 - 1 * 2/3 + 3 % 2
The expression is evaluated from left to right according to the rules of precedence.
6 + 3 -1 * 2/ 3 + 3 % 2
6 + 3 - 1 * 0 + 3 % 2
6 + 3 - 0 + 3 % 2
6 + 3 - 0 + 1
9 - 0 + 1
9 + 1
10
(2 + 3) * 2/ 2 -1
The expression is evaluated from left to right according to the rules of precedence.
5 * 2 / 2 -1
10 / 2 - 1
5 - 1
4
When a program is written, you may need to give some input to the program at the time of execution and the result generated by the program may be required to be displayed on the computer screen. So C provides certain library functions, which are used for input and out operations.
Reading a single character can be done by using a function getchar().
The syntax is:
Variable name= getchar();
Variable name is a valid C name that has been declared as char data type. When this statement is encountered the computer waits until a key and Enter key is pressed and then assigns the inputted value to the getchar() function and since getchar() function is used at the right hand side of the assignment statement the inputted value in turn is assigned to the variable name which is at the left hand side of the assignment statement..
Example:
#include
void main()
{
char c;
printf("Enter a character\n");
c=getchar();
printf("Entered character is %c\n",c);
}
In the above program the variable name c is declared as character data type. The printf() function is used to display the message. When the computer encounters c=getchar(); statement, it waits for the user to input a value and press an Enter key. When you do so, the value is assigned to the function and it is assigned in turn to the variable name c and using the printf() function present in the next line, the value present in the variable c is displayed on the screen.
To read the characters contained in a line of text the getchar() function can be called successively. This function accepts any characters that is keyed in including new line and tab.
When we enter a character and press Enter key, along with the character the new line character will also be present in the input buffer after getchar() returns. So this may cause problems when we use getchar() function repeatedly. So to take care of new line character present in the input buffer, flushall() function or an extra getchar() function can be used.
We can use a function named as putchar() to display a character on the computer monitor.
putchar(Variable name);
Where variable name is a valid C name that has been declared as char data type of which the value will be displayed.
Example:
#include<stdio.h>
void main()
{
char c;
printf("Enter a character\n");
c=getchar();
putchar(c);
}
The above program displays the message, accepts the entered character and displays that character on the computer monitor.
C provides other functions like getch() and putch() to accept and display the character from the standard input and standard output unit respectively.
When getch() function is used it will not display the entered character on the computer monitor and it will not wait for the user to press an Enter key. So one can use getch() function at the end of the program so as to stay on the output screen after the execution of the program and when any key is pressed, the program screen is shown. So the pressed key is not displayed.
Similarly putch() function is available to display the value of a character variable.
This refers to an input data that has been arranged in a particular format. For example if three data elements, say 13, 13.37, 'z' has to be read in according to the format of its appearance, that is 13 to be read into variable of data type int, 13.37 to be read into variable of data type float and 'z' to be read into variable of data type char. This type of inputting is possible with the help of function scanf().
scanf("control string",arg1,arg2....argn);
The control string specifies the field format in which the data is to be entered and the arguments arg1, arg2…..argn specifies the apresses of locations where the data is to be stored. Comma separates control string and arguments.
Field specifications which is specified in control string, directs the computer to the interpretation of input data. It may include following things:
Format (field) specifications consisting of conversion character %, a data type character and an optional number specifying the field width.
Blanks, tabs or new lines are ignored.
The data type character indicates the type of data that is to be assigned to the variable associated with the corresponding argument.
There should be one to one correspondence between the order of field specification appeared within the control string and the order of arguments arg1, arg2,....argn. This means within the control string if %d has appeared first, then %f and then %c then, after the control string first you should have arg1 as an integer variable, arg2 as real variable and arg3 as character variable.
#include <stdio.h>
void main()
{
int m;
float n;
char c;
printf( "Input an integer, real and an alphabet\n");
scanf("%d%f%c",&m,&n,&c);
printf("inputted values are %d%f%c\n",m,n,c );
}
In the above example % sign in both scanf() and printf() function is used and the % sign indicates that conversion specification follows. In the above example %d means integer, %f means real and %c means character.
Similar to Formatted Input we have Formatted Output. In this the results, messages can be displayed the way in which we want. Here also we have the control string which is followed by arguments.
Syntax:
printf("control string",arg1,arg2....argn);
Characters, special symbols that you want to be displayed on the computer
Field specifications that tell you the type of data you want to display and the way in which you want to display. This also specifies the number of arguments that follows the control string.
Format (field) specifications consisting of conversion character %, a data type character and an optional number specifying the field width. The data type character indicates the type of data that is to be assigned to the variable associated with the corresponding argument.
Escape sequence characters such as new line (\n), tab (\t) etc.
The arguments arg1, arg2....argn specifies the apresses of locations from where the data is to be retrieved. Comma separates control string and arguments.
There should be one to one correspondence between the order of field specification appeared within the control string and the order of arguments arg1, arg2,....argn. This means within the control string if %d has appeared first, then %f and then %c then, after the control string first you should have arg1 as an integer variable, arg2 as real variable and arg3 as character variable.
#include<stdio.h>
void main()
{
int m=51;
float n=13.7;
char c='a';
printf("Values are m=%d n=%f c=%c\n",m,n,c );
}
For printing an integer number %wd can be used as format specification where w specifies the minimum number of columns used for the output. However if a number is greater than the specified number of columns, it will be printed in full, overwriting the minimum specification. d specifies that the value to be printed is an integer. The number is written right justified in the given field width. Leading blanks will appear as necessary. The leading blanks can be filled with zeros by placing 0 before the field width specifier. By placing a minus (-) sign directly after % character, it is possible to force the printing to be left justified. By specifying ld in the place of d in the format specification long integer may be printed.
Example showing different format specifications for integer:
void main()
{
int a;
a = 1234;
printf("%d\n",a);
printf("%6d\n",a);
printf("%-6d\n",a);
printf("%06d\n",a);
printf("%2d\n",a);
}
A real number may be displayed in decimal notation using the format %w.pf. The integer w indicates the minimum number of columns that are to be used for the display of the value and integer p indicates the number of digits to be displayed after the decimal point. The value is rounded to p decimal places and printed right justified in the field of w columns. Leading blanks and trailing zeroes will appear as necessary. The default precision is 6 decimal places. The negative numbers will be printed with the minus (-) sign. We can also display a real number in exponential notation by using specification % w.pe
In the exponential notation the display takes the form [ - ]m.nnne [ ] xx where the length of the string n is specified by precision 'p'. The default precision is 6. The field width w should satisfy the condition w p + 7. The value will be rounded off and printed right justified in the field of w columns.
Paping the leading blanks with zeroes and printing with left justification is also possible by introducing 0 or '-' before field width specification specifier w.#include
void main ()
{
float a;
a=33.456;
printf("%f\n",a);
printf("%6.2f\n",a);
printf("%-6.2f\n",a);
printf("%9.2e\n",a);
printf("%-9.2e\n",a);
printf("%9.2e\n",-a);
}
A single character can be displayed using the format %wc. The character will be displayed right justified in the field of w columns. By placing a minus (-) sign before the integer w the display can be made left justified. 1 is the default value of w.
#include
void main()
{
char a = 'x';
printf("%c\n",a);
printf("%4c\n",a);
printf("%-4c\n",a);
}
For this the format specification is %w.ps, where w specifies the number of columns for display and p specifies that only the first p characters of the string are to be displayed and the display is right justified in the field of 'w' columns.
#include
void main()
{
char a[50];
printf("Enter the Input String\n");
scanf("%[^\n]",&a);
printf("\nDifferent types of Outputs are\n\n");
printf("%s\n",a);
printf("%25s\n",a);
printf("%25.15s\n",a);
printf("%.9s\n",a);
printf("%10s\n",a);
printf("%-25.15s\n",a);
}
While reading character string using scanf() function if we give the format specification as %[characters] it means that only the characters specified within the brackets are allowed to be inputted and inputting of any other character other than those given inside the brackets will terminate the reading.
scanf("%[a-n]", &a);
The above statement will allow you to input any characters from a to n and if any other characters other than these characters are entered from the keyboard then the reading is terminated immediately.
Whereas in the format specification %[^character] the character specified are not permitted to be inputted. Upon encountering the character specied within the bracket, the inputting is terminated.
scanf("%[^a-n]",&a);
The above statement will not allow you to input any characters from a to n and any other characters other than these characters are accepted and if any characters specifed in the bracket are entered from the keyboard, immediately the reading is terminated.
The format specification %s will terminate the reading at the encounter of the space. So it is used to read the string without any space.
scanf("%s",&a);
To read the string till the end of line use the format specification character as %[^\n]. It means allow all the characters including space till the end of line character is pressed.
scanf("%[^\n]",&a);
When the instructions of a program are executed one after another from the beginning to the end, it is called as Sequential Flow of instructions.
/*C Program to calculate sum of two numbers*/
#include
void main() /*C Program to find Area of a Cirle*/ #include
{
int a,b,c;
a=55;
b=65;
c=a+b;
printf("A is %d, B is %d, Result is %d",a,b,c);
}
Output:
Example 2:
#include
void main()
{
int r;
float area;
r=6;
area=3.14*r*r;
printf("The Area of the Circle is %f",area);
getch();
}
Output:
/*C Program to calculate Area of a Triangle*/
#include
#include
void main()
{
int b, h;
float area;
printf("Enter the Base of Triangle\n");
scanf("%d",&b);
printf("Enter the Height of the Triangle\n");
scanf("%d",&h);
area=(b*h)/2;
printf("\nThe Area of the Triangle is %f",area);
getch();
}
Our aim is to provide information to the knowledge seekers.
Support us generously