Instructions in C Programming Language
Instructions in C Programming Language
Instructions in C Programming Language There are basically three types of instructions in C: a) Type Declaration Instruction b) Arithmetic Instruction c) Control Instruction The purpose of each of these instructions is given below:
Type Declaration instruction Type Declaration instruction is used to declare the type of variables used in C. Any variable we want to use in the program must be declared before using it. This declaration is done using Type declaration instruction. This declaration is done at the beginning of the main() function. E.g.: int pr, rt; float amt; Arithmetic instructions Arithmetic instructions are used to perform arithmetic operations on variables and constants. Here we will learn some new terms. These are operands and operators. The variables and constants on which arithmetic operation is done by arithmetic operators are called operands. Example 1:
int a = 5, b = 10, c; c = a + b;
Example 2:
int a; float b, c, d; a = 10; b = 0.05; c = 1.5; d = a +b * c;
Here, a is integer variable. b, c and d are real variables. = is the assignment operator. + and * are arithmetic operators. 10 is integer constant. 0.05 and 1.5 are real constants.
Page 1
Instructions in C
Control Instructions in C The Control Instructions enable us to specify the order in which instructions in a program are to be executed. or the control instructions determine the flow of control in a program. There are four types of control instructions in C. 1. Sequence Control Instruction The Sequence control instruction ensures that the instructions are executed in the same order in which they appear in the program. 2. Selection or Decision Control Instruction Decision instructions allow the computer to take a decision as to which instruction is to be executed next. 3. Repetition or Loop Control Instruction The Loop control instruction helps computer to execute a group of statements repeatedly. 4. Case Control Instruction Same as decision control instruction. By default the instructions in a program are executed sequentially. However, in serious programming situations, seldom do we want the instructions to be executed sequentially. Many a times, we want a set of instructions to be executed in one situation, and an entirely different set of instructions to be executed in another situation. This kind of situation is dealt in C programs using a decision control instruction. As mentioned earlier, a decision control instruction can be implemented in C using: a) The if statement b) The if-else statement c) The conditional operators The if Statement Like most languages, C uses the keyword if to implement the decision control instruction. The general form of if statement looks like this: if ( this condition is true ) execute this statement ; The keyword if tells the compiler that what follows is decision control statement. if (condition is true) execute the statement; The if condition tells the compiler that the condition is true, execute the statement. Condition of if is always within the pair of parentheses. If condition is true the statement
Page 2
Instructions in C
will execute and condition is false, the statement will not execute. For checking condition is true or false we use the relational operators. Relational Operators: Expression x==y x!=y x<y x>y x<=y x>=y Is True If x is equal to y x is not equal to y x is less than y x is greater than y x is less than or equal to y x is greater than or equal to y
Example:main( ) { int num ; printf ( "Enter a number less than 10 " ) ; scanf ( "%d", &num ) ; if ( num <= 10 ) printf ( "What an obedient servant you are !" ) ; }
Multiple statements within if: We can execute more than one statements for that if condition should be satisfied. The block of statements to be executed must be enclosed in opening and closing braces. If only one statement needs to be executed then braces need not be used. Let us understand if statement using an example.
int a = 10; if (a == 10) { printf(You are in if block\n); printf(The value of a is %d\n, a); } printf(You are out of if block);
In the above example we have assigned value 10 to a. In the next line, there is an if statement. It is read as If a is equal to 10 then perform the block of statements enclosed within the braces. After the execution of this block normal sequence flow of the program is executed. The output of the above example is: You are in if block The value of a is 10 You are out of if block
Page 3
Instructions in C
If-else Statement in C Programming Here, if and else are the keywords in C. Syntax:
if(expression) { Statement-1; Statement-2; } else { Statement-3; Statement-4; } next_statement; Flowchart : If Else Statement
If expression is True then Statement-1 and Statement-2 are executed Otherwise Statement-3 and Statement-4 are executed.
Example:
int a = 10; if (a == 10){ printf(You are in 1st printf(The value of a } else{ printf(You are in 2nd printf(The value of a }
In the above example we have assigned value 10 to a. In the next line, there is an if statement. It is read as If a is equal to 10 then perform the block of statements enclosed within the braces of if part else perform the block of statements enclosed within the braces of else part. After the execution of if-else statement normal sequence flow of the program is followed. The output of the above example is: You are in if block You are in 1st block The value of a is 10
Page 4
Instructions in C
Nested If else: We can use several If else condition within if block or else block. This is called nested if else condition. Example:/* program of nested if-else */
void main ( ) { int num = 10 ; if ( num > 0 ) printf ("\n Number is Positive"); else if ( num < 0 ) printf ("\n Number is Negative"); else printf ("\n Number is Zero"); }
Explanation : In the above program firstly condition is tested i.e number is checked with zero. If it is greater than zero then only first if statement will be executed and after the execution of if statement control will be outside the complete if-else statement.
else if ( num < 0 ) printf ("\n Number is Negative"); else printf ("\n Number is Zero");
and if number is neither positive nor negative then it will be considered as zero.
Suppose in first if condition is false then the second condition will be tested i.e if number is not positive then and then only it is tested for the negative.
Page 5
Instructions in C
Logical operators There are only three logical operator in C. 1) && AND 2) || OR 3) ! NOT The first two operator allows two or more conditions to be combined in an if statement. Example:main( ) { int m1, m2, m3, m4, m5, per ; printf ( "Enter marks in five subjects " ) ; scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ; per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ; if ( per >= 60 ) printf ( "First division" ) ; if ( ( per >= 50 ) && ( per < 60 ) ) printf ( "Second division" ) ; if ( ( per >= 40 ) && ( per < 50 ) ) printf ( "Third division" ) ; if ( per < 40 ) printf ( "Fail" ) ; }
The Conditional Operator in C The conditional operator is also known as ternary operator. It is called ternary operator because it takes three arguments. The conditional operator evaluates an expression returning a value if that expression is true and different one if the expression is evaluated as false. Syntax: condition ? result1 : result2 If the condition is true, result1 is returned else result2 is returned. Examples:
10==5 ? 11: 12 // returns 12, since 10 not equal to 5. 10!=5 ? 4 : 3 // returns 4, since 10 not equal to 5. 12>8 ? a : b // returns the value of a, since 12 is greater than 8. /*Conditional operator*/ #include<stdio.h> void main(){ int a = 10, b = 11; int c; c = (a < b)? a : b printf(%d, c); } Output: 10
Page 6
Instructions in C
Switch Case
One of the classic problem encountered in nested if-else/else-if ladder is called problem of Confusion. It occurs when no matching else is available for if. As the number of alternatives increases the Complexity of program increases drastically. To overcome this, C Provide a multi-way decision statement called Switch Statement. Structure of Switch Case Example
#include<stdio.h> void main() { int roll = 3 ; switch ( roll ) { case 1: printf "); break; case 2: printf "); break; case 3: printf break; default: printf found"); break; } }
switch(expression) { case value1 : body1 break; case value2 : body2 break; case value3 : body3 break; default : default-body break; } next-statement;
( " I am Pankaj
( " I am Nikhil
Switch case checks the value of expression/variable against the list of case values and when the match is found , the block of statement associated with that case is executed Expression should be Integer Expression / Character Break statement takes control out of the case. Break Statement is Optional.
Instructions in C
1. 3 is assigned to integer variable roll 2. Switch case decides We have to execute block of code specified in 3rd case. 3. Switch Case executes code from top to bottom. 4. It will now enter into first Case [i.e case 1:] 5. It will validate Case number with variable Roll. If no match found then it will jump to Next Case. 6. When it finds matching case it will execute block of code specified in that case. See how Switch Case works using Graphical Picture
Goto Statement
Page 8
Instructions in C
The goto statement is used for unconditional jump from one part of the program to another part of the program. It is always suggested not to use goto statement as this reduces the readability of the program. Using goto statement is considered as poor programming approach. The goto statement consists of two parts: label and goto keyword.
goto label; ------------label :
Whenever goto keyword encountered then it causes the program to continue on the line , so long as it is in the scope . Types of Goto : Forward Goto Backward Goto
Example:
/*use of goto statement*/ #include<stdio.h> #include<conio.h> void main(){ int a; goto label;
Output: 20
When goto label is encountered, control goes to the statement next to the label. Here, label is not the keyword. We can use any name for the label. Its user defined.
Page 9
Instructions in C
Loop Control Structure Loops are used to change the sequence or flow of the program. The basic behavior of the program is that it starts it from the beginning of the program, executes the particular statement only once and proceeds to the next statement. This behavior is continued till the end of the program is reached. But sometimes we need to execute a particular statement more than once. At this point Loops plays an important role. Following are the types of Loops we can use in the program: 1) while statement 2) do-while statement 3) for statement The While Loop Let us suppose you want to execute a block of statement 5 times. There is one approach using goto statement as shown below.
#include<stdio.h> #include<conio.h> void main(){ int i=0; clrscr(); label1: i=i+1; printf("%d This will be repeated 5 times\n", i); if(i!=5) goto label1; printf("End of the program"); getch(); }
Output: 1 This will be repeated 5 times 2 This will be repeated 5 times 3 This will be repeated 5 times 4 This will be repeated 5 times 5 This will be repeated 5 times End of the program
The above mentioned approach solves our purpose. But it is very tedious job to take care of labels. It also decreases the readability of the program. Hence there is another approach to perform the above task very effectively. We will use while loop. Syntax:
initialization; while(condition) { -------------/* Block of Statements*/ -------------incrementation; }
Page 10
Instructions in C
Here, while is the keyword which is know to the compiler, Condition can be any expression. Here, when while is encountered, condition is checked first by the compiler. If the condition is satisfied then the block of statement inside the while loop is executed. After the execution of block of statement, again condition is check. If the conditional expression returns true, the block of statement is executed again. This process is followed till the conditional expression returns false value. Let us write the above program using while loop.
#include<stdio.h> #include<conio.h> void main(){ int i=0; clrscr(); while(i!=5){ i=i+1; printf("%d This will be repeated 5 times\n", i); } printf("End of the program"); getch(); } Output: 1 This will be repeated 5 times 2 This will be repeated 5 times 3 This will be repeated 5 times 4 This will be repeated 5 times 5 This will be repeated 5 times End of the program
As you can see, the out of the above program is same as the one with goto statement in it. We can also see that the readability of the program increases. Using while loop is much easier than using goto statement as we dont have worry about positioning of labels.
Note :
For Single Line of Code Opening and Closing braces are not needed. while(1) is used for Infinite Loop Initialization , Incrimination and Condition steps are on different Line. While Loop is also Entry Controlled Loop.[i.e conditions are checked if found true then and then only code is executed ]
Page 11
Instructions in C
To Break Infinite While Loop : Whenever you decide to use infinite while loop while writing code , you must include terminating or ending condition in a while loop to ensure that your code will be terminated at some moment of time.
while(1) { ch = fgetc(fp); printf("%c",ch); fp++; if(ch == 'EOF') break; }
In the Above program we cannot decide, size of file while writing program so we decided to go with infinite while loop. Our main purpose is to read file so we have provided breaking condition inside loop which will takes control out of loop. Semicolon at the end of While
#include<stdio.h> void main() { int num=300; while(num>255); //Note it Carefully printf("Hello"); }
Output : It won't Print anything Explanation of Above Infinite Loop : 1. In the above program , Condition is specified in the While Loop 2. Semicolon at the end of while indicated while without body. 3. In the program variable num doesnt get incremented, condition remains true forever. 4. As Above program does not have Loop body , It wont print anything
Page 12
Instructions in C
The do while Loop
initialization; do { -------------/* Block of Statements*/ -------------incrementation; }while(condition);
Here, while and do are the keywords which is know to the compiler. Condition can be any expression. This is very similar to while loop. Here, the block of statement enclosed in the opening and closing braces after the keyword do is executed at least once. After the execution of the block of statement for the first time, the condition in the while is executed. If the condition is satisfied then the block of statement inside the do block is executed. After the execution of block of statement, again condition is check. If the conditional expression returns true, the block of statement is executed again. This process is followed till the conditional expression returns false value. Note: It is necessary to write semicolon (;) after the while (condition) as shown in the syntax else you will get an error. The above example for while loop can re-written as follows:
#include<stdio.h> #include<conio.h> void main(){ int i=0; clrscr(); do{ i=i+1; printf("%d This will be repeated 5 times\n", i); }while(i!=5); printf("End of the program"); getch(); } Output: This will be repeated 5 times 2 This will be repeated 5 times 3 This will be repeated 5 times 4 This will be repeated 5 times 5 This will be repeated 5 times End of the program
Note :
It is Exit Controlled Loop. Initialization , Incrementation and Condition steps are on different Line. It is also called Bottom Tested [i.e Condition is tested at bottom and Body has to execute at least once ].
Page 13
Instructions in C
The For Loop In while and do while statement we need to write logic to repeatedly execute a block of statement by initializing a counter and incrementing it after a particular steps. This sometime looks tedious and decreases the readability of the program. The readability of the program can be improved by using for statement. Using for statement we can merge all the three parts i.e. assignment, condition checking and increment/decrementing. Syntax: for(initialization ; conditional ; increment) { --------------//body --------------}
Initialization: setting up a loop counter to initial value test condition: Testing the loop counter to determine whether the loop needs to be executed or not. increment/decrement: Increment or decrement the loop counter value Explanation: The for loop is executed as follows: 1) The initial counter value is initialized. This initialization is done only once for the entire for loop. 2) After the initialization, test condition is checked. Test condition can be any relational or logical expression. If the test condition is satisfied i.e. the condition evaluates to true then the block of statement inside the for loop is executed. 3) After the execution of the block of statement, increment/decrement of the counter is done. After performing this, the test condition is again evaluated. The step 2 and 3 are repeated till the test condition returns false. The above example for while loop can re-written as follows:
#include<stdio.h> #include<conio.h> void main(){ int i; clrscr(); for(i=1; i<=5;i++) { Er. Pankaj Kapoor Page 14
Instructions in C
printf("%d This will be repeated 5 times\n", i); } printf("End of the program"); getch(); } Output: 1 This will be repeated 5 times 2 This will be repeated 5 times 3 This will be repeated 5 times 4 This will be repeated 5 times 5 This will be repeated 5 times End of the program
In the above program, value 1 is assigned to i. The for loop would be executed till the value of i is less than or equal to 5. Note :
For Single Line of Code Opening and Closing braces are not needed. There can Exist For Loop without body. Initialization , Incrementation and Condition steps are on same Line. Like While loop , For Loop is Entry Controlled Loop.[i.e conditions are checked if found true then and then only code is executed ]
Different Ways of Using For Loop in C Programming In order to do certain actions multiple times , we use loop control statements. For loop can be implemented in different verities of using for loop
Form for ( i=0 ; i < 10 ; i++ ) Statement1; for ( i=0 ;i <10; i++) { Statement1; Statement2; Statement3; } for ( i=0 ; i < 10;i++) ; for (i=0,j=0;i<100;i++,j++) Statement1; for ( ; i<10 ; i++) for ( ; i<10 ; ) for ( ; ; ) Comment Single Statement
For Loop with no Body ( Carefully Look at the Semicolon ) Multiple initialization & Multiple Update Statements Separated by Comma Initialization not used Initialization & Update not used Infinite Loop,Never Terminates
Page 15
Instructions in C
The Break Statement Here, break is the keyword known to the compiler. The break statement is used to break from any kind of loop. Let us understand the use of break statement using an example. Example:
for(i=0;i<10;i++){ /*block of statement*/ }
Let us suppose that we want to come out of for loop when the value of I equals to 5. The solution to this is using break statement. The problem can be solved using break loop as follows:
for(i=0;i<10;i++){ /*block of statement*/ if(i==5) break; }
When the break statement is executed the control is transferred to the statement present immediately after the for loop. Do-While Loop For Loop Nested For Loop While Loop
Page 16
Instructions in C
The Continue Statement Sometimes there arises a situation where we dont want to execute the certain statements within the loop but we want to continue the execution of the loop till the condition is satisfied. This can be done using continue statement. It is used for Skipping part of Loop. Consider the below example,
for(i=0;i<10;i++){ /*statement-1*/ /*statement-2*/ /*statement-3*/ /*statement-4*/ }
Let us suppose that, when the value of i equals to 5 we want to skip the execution of statement-3 and statement-4. Then, we can use the continue statement to perform the above task as follows.
for(i=0;i<10;i++){ /*statement1*/ /*statement2*/ if(i ==5)
continue;
/*statement3*/ /*statement4*/ }
Here, when value of i equals to 5, statement3 and statement4 are skipped and control gets transferred to the increment part of for loop and for loop is executed as normal.
Page 17