Docsity

03 control statements and loop, Lecture notes of C programming

Toggle sidebar
bg1
Unit 3 Computer Programming Er. Yubraj Chaudhary
DEE – II/I Page 1
Control statements and loops
In C programs, statements are executed sequentially in the order in which
they appear in a program. But sometimes we may want to use a condition for
executing only a part of program. Also many situations arise where we may
want to execute some statements several times. Control statements enable us
to specify an order in which various instructions in the program are executed.
This determines the flow of control. Control statements define how the control
is transferred to other parts of a program. C language supports four types of
control statements, which are
i) if…. else
ii) goto
iii) switch
iv) loop (while, do….while, for)
Conditional operator
Conditional operator is a ternary operator (? And :) which requires three
expressions as operands.
Syntax:
Test expression ?expression1 : expression2
If the test expression is true, expression1 is evaluated otherwise expression2 is
evaluated and becomes the value of overall conditional expression.
e.g.
x=2, y=5
max=x>y ? x : y
Result: max=5
if statement
Syntax:
if(condition)
{
statement1;
statement2;
:
:
:
}
Here, if the condition is true then statement1 is executed, and if it is false, then
the next statement which is immediately after the if control statement is
executed.
Statement1
Next statement
True
False
if
(condition)
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12

Partial preview of the text

Download 03 control statements and loop and more Lecture notes C programming in PDF only on Docsity!

Unit 3 Computer Programming Er. Yubraj Chaudhary

Control statements and loops

In C programs, statements are executed sequentially in the order in which they appear in a program. But sometimes we may want to use a condition for executing only a part of program. Also many situations arise where we may want to execute some statements several times. Control statements enable us to specify an order in which various instructions in the program are executed. This determines the flow of control. Control statements define how the control is transferred to other parts of a program. C language supports four types of control statements, which are i) if…. else ii) goto iii) switch iv) loop (while, do….while, for)

Conditional operator

Conditional operator is a ternary operator (? And :) which requires three expressions as operands. Syntax: Test expression ?expression1 : expression If the test expression is true, expression1 is evaluated otherwise expression2 is evaluated and becomes the value of overall conditional expression. e.g. x=2, y= max=x>y? x : y

Result: max=

if statement

Syntax: if(condition) { statement1; statement2; : : : }

Here, if the condition is true then statement1 is executed, and if it is false, then the next statement which is immediately after the if control statement is executed.

Statement

Next statement

True

False

if (condition)

Unit – 2 Control statements and loops Er. Yubraj Chaudhary

Note: There can be a single statement or a block of statements after if statement. Single statement can be written immediately after if statement, but for a block of statements, the statements should be enclosed within curly braces after if statement.

/program to print a message if negative number is entered / void main() { intnum; printf("Enter a number:"); scanf("%d",&num); if(num<0) printf("Number entered is negative"); printf("\nValue of num is : %d",num); }

if….else

This statement is used to test a condition and take one of the two possible actions. If the condition is true, then the true-block statements, immediately following the if statement are executed. Otherwise false-block statements are executed. Syntax: if(condition) { True-block statements; } else { False-block statements; }

/Program to find whether the number is even or odd/** void main() { intnum; printf("Enter a number: "); scanf("%d",&num); if(num%2==0) printf("Number is even"); else

True if False (condition)

True-block statements

Next statement

False-block statements

Unit – 2 Control statements and loops Er. Yubraj Chaudhary

/ program to find the leap year* A centennial (divisible by 100) year is leap if it is divisible by 400, and a non- centennial year is leap if it is divisible by 4 */ void main() { int year; printf("Enter year:"); scanf("%d",&year); if(year%100==0) { if(year%400==0) printf("%d is leap year",year); else printf("%d is not leap year",year); } else { if(year%4==0) printf("%d is leap year",year); else printf("%d is not leap year",year); } }

else if ladder

In this type of nesting there is an if….else statement in every else part except the last else part.

if(condition1) statementA; else if(condition2) statementB; else if(condition3) statementC; else statementD;

if(condition1) statementA; else if(condition2) statementB; else if(condition3) statementC; else statementD;

Unit 3 Computer Programming Er. Yubraj Chaudhary

/Program to find the grade of a student when marks of eight subjects are given(using else-if ladder)/** void main() { float m1,m2,m3,m4,m5,m6,m7,m8,total,per; printf("Enter your marks eight subjects:"); scanf("%f%f%f%f%f%f%f%f",&m1,&m2,&m3,&m4,&m5,&m6,&m7,&m8); total=m1+m2+m3+m4+m5+m6+m7+m8; printf("Your total marks is %.2f\n",total); per=total/8; printf("Your percentage is %.2f\n",per); printf("Grade : "); if(per>=80.0) printf("Distinction"); else if(per>=60.0) printf("First division"); else if(per>=50.0) printf("Second division"); else if(per>=40.0) printf("Pass"); else printf("fail"); }

True

statementA

if (condition 3 )

if True (^) (condition 2 ) False

statementB

statementC

True (^) (condition1)^ if False

Next statement

False

statementD

Unit 3 Computer Programming Er. Yubraj Chaudhary

continue

The continue statement is used when we want to go to the next iteration of the loop after skipping some statements of the loop. The continue statement can be written as

continue;

it is generally used with a condition. When continue statement is encountered and if the condition is tru then all the remaining statements (statements after continue) in the current iteration are not executed and the loop continues with next iteration. The difference between break and continue is that when break is encountered the loop terminates and the control is transferred to the next statement following the loop, but when a continue statement is encountered the loop is not terminated and the control is transferred to the beginning of the loop.

switch

This is a multi-directional conditional control statement. Sometimes there is a need in program to make choice among number of alternatives. For making this choice, we use the switch statement.

switch(expression) { case constant1: statement; …………. case constant2: statement; …………. …………………. …………. caseconstatnN; statement; …………. default: statement; ………….. }

Here, switch, case and default are keywords. The expression following the

switch(expression)

case constant (expression == constant1)

default

case constant 2 (expression == constant 2 )

case constantN (expression == constantN)

statement

statement

statement

statement

break

break

break

break

out of switch

True

True

True

False

False

False

Unit – 2 Control statements and loops Er. Yubraj Chaudhary

switch keyword can be any C expression that yields any integer value. It can be value of any integer or character variable. It can also be any integer or character constant also.

The constant following the case keywords should be should be of integer or character type. They can be either constants or constant expressions. These constants must be different from one another. Each case can be followed by any number of statements. It is also possible that a case has no statement under it. For multiple statements it is not necessary to enclose them with pair of curly braces. Firstly the switch expression is evaluated, and then the value of this expression is compared one by one with every case constant. If the value of expression matches with any case constant, then all the statements under that particular case are executed. If none of the case constant matches with the value of the expression then the block of statements under default is executed. „default‟ is optional. Example: void main() { int choice; printf(“Enter your choice: “); scanf(“%d”,&choice); switch(choice) { case 1: printf(“First”); case 2: printf(“Second”); case 3: printf(“Third”); default: printf(“Wrong Choice”); } }

Output: Enter your choice: 2 Second Third Wrong Choice

On the above example‟s output, value of choice matches with second case so all the statements after case 2 are executed sequentially. The statements of case 3 and default are also executed in addition to the statements of case 2. This is known as falling through cases. To stop falling through cases, we can use a break; statement. If a break statement is encountered inside a switch, then all the statements following break are not executed and the control jumps out of the switch.

Example:

Unit – 2 Control statements and loops Er. Yubraj Chaudhary

break; case '': printf("Multiplication"); result=num1num2; break; case '/': printf("Division"); result=num1/num2; break; case '%': printf("Modulus"); result=num1%num2; break; default: printf("\n\nEnter valid operator: + or - or * or / or % "); goto start; } printf(“Result = %d",result); getch(); }

Loops

Loops are used when we want to execute a part of a program or a block of statements several times. For example, suppose we want to print “C is best” 10 times. One way to get the desired output is we write 10 printf(“C is best”); statements, which is not preferable. Other way out is to use loop. Using loop we can write one loop statement and only one printf(“C is best”); statement, and this approach is definitely better than the first one. With the help of loop we can execute a part of a program repeatedly till some condition is true. There are three loop statements in C. i) while ii) do while iii) for

while loop

while(condition) statement;

First the condition is evaluated; if it is true then the statements in the body of loop are executed. After the execution, again the condition is checked and if it is found to be true then again the statements in

while False (condition)

statements inside the body of loop

Next statement out of loop

True

Output:

Simple Arithmetic Calculator

Enter a number, operator and another number: 5+

Addition Result = 15

Unit 3 Computer Programming Er. Yubraj Chaudhary

the body of loop are executed. This means that these statements are executed continuously till the condition is true and when it becomes false, the loop terminates and the control comes out of the loop. Each execution of the loop body is known as iteration.

Example: / Program to print the numbers from 1 to 10 using while loop / void main() { int i=1; while(1<=10) { printf(“%d \t”,i); i=i+1; } }

Output 1 2 3 4 5 6 7 8 9 10

Here, initially the condition (i<1=10) is true. After each iteration of the loop, value of i increases by 1. After ten iterations the value of i becomes 11. On the eleventh time the condition becomes false and the loop terminates. Note that inside body of the loop there should be a statement that alters the value of the condition, so that the condition becomes false ultimately at some point.

/ program to print numbers in reverse order with difference of 2 / void main() { int k=1-; while(k>=2) { printf(“%d \t”, k); k=k-2; } }

Output: 10 8 6 4 2

/ program to print the sum of digits of any number / void main() { int n, sum=0, rem; printf(“Enter the number: “); scanf(“%d”, &n);

Unit 3 Computer Programming Er. Yubraj Chaudhary

do…..while loop

The do…while statement is also used for looping. The body of this loop may contain a single statement or a block of statements.

do { statement1; ………….. statementN; } while(condition);

First, statements inside body of the loop are executed and then the condition is evaluated. If the condition is true, then again the loop body is executed and this process continues until the condition becomes false. Note that unlike the while loop, here a semicolon is placed after the condition. In a while loop, first the condition is evaluated and then the statements are executed, whereas in a do…while loop, first the statements are executed and then the condition is evaluated. So if initially the condition is false, while loop will not execute at all, whereas do…while loop will always execute at least once.

Example: / Program to print the numbers from 1 to 10 using do...while loop / #include<stdio.h> #include<conio.h> void main() { int i=1; clrscr(); do { printf("%d\t",i); i=i+1; } while(i<=10); getch(); }

Output: 1 2 3 4 5 6 7 8 9 10

while False (condition)

True

Body of loop

Next statement out of loop

Unit – 2 Control statements and loops Er. Yubraj Chaudhary

/ Do..while loop used for checking validity of entered data Suppose, the valid IDs are in the range between 100 and 500 / #include<stdio.h> #include<conio.h> void main() { intemp_id; clrscr(); do { printf("Enter employee id: "); scanf("%d",&emp_id); }while(emp_id<100||emp_id>500); printf("You are welcome"); getch(); }

Output: Enter employee id: 75 Enter employee id: 680 Enter employee id: 245 You are welcome

for loop

For statement has three expressions and semicolons are placed for separating these expressions. The for statement can be written as:

for (expression1; expression2; expression3) { statement1; …………… statementN; }

Where, expression1  initialization expression expression2  conditional expression expression3  update expression

Epresssion1 is executed only once when the loop starts and is used to initialize the loop variables. Expression2 is a condition and is tested before each iteration of the loop. This conditional

True

False Condition

Initialization statements

Next statement out of loop

Body of loop

Update expression

Unit – 2 Control statements and loops Er. Yubraj Chaudhary

void main() { int n, i, c; int f1=0, f2=1, f3; clrscr(); printf("How many numbers are there in series? : "); scanf("%d", &n); printf("\n %d", f1); printf("\t %d", f2); for(c=2; c<n; c++) { f3 = f1+f2; f1 = f2; f2 = f3; printf(“\t%d",f3); } getch(); }

Nesting of loops

When a loop is written inside the body of another loop, then it is known as nesting of loops. Any type of loop can be nested inside any other type of loop. For example, a for loop may be nested inside another for loop or inside a while or do…while loop. Similarly while and do…while loops can be nested.

/program to understand nesting in for loop / #include<stdio.h> #include<conio.h> void main() { int i, j; clrscr(); for (i=1;i<=3;i++) //outer loop { printf("i = %d \n", i); for (j=1; j<=4; j++) //inner loop printf("j = %d \t", j); printf("\n"); } getch(); }

Output: How many numbers are there in series? : 10 0 1 1 2 3 5 8 13 21 34

Output: i = 1 j = 1 j = 2 j = 3 j = 4 i = 2 j = 1 j = 2 j = 3 j = 4 i = 3 j = 1 j = 2 j = 3 j = 4

Unit 3 Computer Programming Er. Yubraj Chaudhary

/ Program to print Armstrong numbers from 100 to 999 / /* Armstrong number is a three digit number in which the sum of cube of all digits is equal to the number. For example 371 is an Armstrong number. 371 = 3^3 + 7^3 + 1^3 = 27 + 343 + 1= 371 ****************************************/ #include<stdio.h> #include<conio.h> void main() { int num, n, cube, d, sum; printf("Armstrong numbers are: \n"); for (num=100; num<=999; num++) { n = num; sum = 0; while(n>0) { d = n % 10; n = n / 10; cube = d * d * d; sum = sum + cube; } if(num == sum) printf("%d \n",num); } getch(); }

Output: 153 370 371 407

Pyramids

void main() { int i, j, n; printf(“Enter n: “);