0% found this document useful (0 votes)
6 views

Control Structures in C

Uploaded by

Kirtimaya Swain
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Control Structures in C

Uploaded by

Kirtimaya Swain
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

25-09-2024

Dr. Madhusmita Sahu

CONTROL STRUCTURES IN C Associate Professor


Department of Computer Science
and Information Technology

CONTROL STATEMENT
Specifies the order in which the various instructions in the program are executed.
The order of statement execution is called the flow of control
Unless specified otherwise, the order of statement execution through a function is linear: one
statement after another in sequence
Some programming statements allow us to:

1. decide whether or not to execute a particular statement


2. execute a statement over and over, repetitively
These decisions are based on boolean expressions(or conditions) that evaluate to true or false

1
25-09-2024

CONTROL FLOW STATEMENTS


Control Flow
Statements

Conditional Unconditional
Statements statements

Selection Iteration Jump /Skipping


Statements Statements Statements

DECISION MAKING
Decision making is about deciding the order of execution of statements based on
certain conditions or repeat a group of statements until certain specified conditions
are met.
C language handles decision-making by supporting the following selection/branching
statements,
 if statement
 switch statement
 conditional operator statement
 goto statement

2
25-09-2024

if statement
• It is used to control flow of execution of statement.
• It is two-way decision statement and is used in conjuction with an expression
Syntax- if (condition)
{ statement 1; Entry
……………..
}
Test expression False
?

Ex: if (age is more than 55) True


Person is retired

DIFFERENT FORMS OF IF STATEMENT

simple if if-else nested if-else else if ladder

3
25-09-2024

SIMPLE IF STATEMENT
The general form of a
simple if statement is,
if( expression ) condition
evaluated
{
statement inside;
} true
statement outside; false

statement
If the expression is true, then
'statement-inside' it will be
executed, otherwise 'statement-
inside' is skipped and only Next statement
'statement-outside' is executed.

Program of simple if statement


main()
{
int a,b,c,d;
float ratio;
printf(“\n enter four integer value”);
scanf(“%d%d%d%d”,&a,&b,&c,&d);
if(c-d !=0)
{
ratio= (float) (a+b)/(float)(c-d);
printf(“Ratio= %f”, ratio);
}
} Output- enter four integer values
12 23 34 45
Ratio= -3.181818

4
25-09-2024

Example
Write a program to check entered character is digit or uppercase or lowercase alphabet.
#include <stdio.h>
int main( )
{ char ch;
printf(“Enter the character”);
scanf(“%c”,&ch);
if (ch>=‘0’ && ch<=‘9’ )
printf(“\n It is a digit");
if (ch>=‘A’ && ch<=‘Z’ )
printf(“\n It is a uppercase alphabet");
if (ch>=‘a’ && ch<=‘z’ )
printf(“\n It is a lowercase alphabet");
return 0;
}

The if…else statement entry


Syntax- if( Condition)
{ true Condition
true block statement; false
}
else True block statement False block statement
{
false block statement;
}
statement x; Statement x

Ex-: if (code== 1) if (code==1)


boy=boy+ 1; boy=boy+1;
if ( code== 2) else
girl=girl+1; girl=girl+1;

5
25-09-2024

IF...ELSE STATEMENT
The general form of a simple if...else statement is,
if( expression )
{
statement block1;
}
else
{
statement block2;
}
If the 'expression' is true, the 'statement-block1' is executed, else
'statement-block1' is skipped and 'statement-block2' is executed.

EXAMPLE
Write a program to check if a given number is even or odd.
#include<stdio.h>
Int main ()
{
int var;
printf("Enter a Number : ");
scanf("%d",&var);
if(var%2= =0)
{
printf(“%d is even number”,var);
}
else
{
printf(“%d is even number”,var);
}
}
output- Enter a Number :
46
46 is an even number

6
25-09-2024

EXAMPLE
Write a program to check greater of two number.

#include <stdio.h>
int main( )
{
int x,y;
x=15; y=18; Output:
if (x > y ) y is greater than x
{
printf("x is greater than y");
}
else
{
printf("y is greater than x");
}
return 0;
}

Example
Write a program to confirm a year is leap or not.

#include<stdio.h>
int main()
{
int year;
printf(“Enter value of a year:”);
scanf(“%d”, &year);
if(year %100 !=0 && year%4==0 || year%400==0)
printf(“\n The year is a leap year.”);
else
printf(“\n The year is a not leap year.”);

return 0;
}

7
25-09-2024

Example
Write a program to calculate root of a quadratic equation.

#include<stdio.h>
#include<math.h>
int main()
{
float a,b,c,r1,r2,t;
printf(“Enter value of a,b,c:”);
scanf(“%f%f%f”,&a,&b,&c);
t=b*b-4*a*c;
if(t<0)
printf(“\n Roots are imaginary.”);
else
{ r1=(-b+sqrt(t))/2*a;
r2=(-b-sqrt(t))/2*a;
printf(“\n root1=%f”,r1);
printf(“\n root2=%f”,r2);
}
return 0;
}

NESTED IF....ELSE STATEMENT


We can have another if-else statement in the if block or the else block.
This is called nesting of if-else statements.
Syntax-
if( test condition 1)
{
if (test condition 2)
{
statement 1;
}
else
{
statement 2;
}
}
else
{
statement 3;
}
statement x ;

8
25-09-2024

NESTED IF....ELSE STATEMENT


 The general form of a
nested if...else statement is, if( expression )
{
if( expression1 )
{
•if 'expression‘ is false the statement block1;
'statement-block3' will be }
executed, otherwise it else
{
continues to perform the test statement block2;
for 'expression 1' . }
•If the 'expression 1' is true }
else
the 'statement-block1' is {
executed statement block3;
otherwise 'statement-block2' is }
executed.

EXAMPLE
Program to find greatest between
three numbers.

9
25-09-2024

#include <stdio.h>
void main ( ) {
int a,b,c, large;
printf (“Enter the three nunber : ”);
Enter the three number 5 6 4
scanf (“%d%d%d”,&a,&b,&c);
if (a > b) {
if (a > c) Check a > b i.e 5 > 6 , it is false
large = a; Then go to the else part of the
else first if statement .
large = c;
} Check b > c i.e 6 > 4 , it is true
else{
if (b > c)
large =b; So assign the value of b i.e 6 to
else large.
large=c;
}
Out put :
printf(“larger number is %d\n”,large); Enter the three number :
} 564
larger number is 6

DANGLING ELSE PROBLEM


• It occurs when a matching 1. In such situations, else clause
else is not available for an belongs to the closest if statement
if. which is incomplete that is the
• In nested if statements, innermost if statement.
when a single “else clause” 2. However, we can make else clause
occurs, the situation happens belong to desired if statement by
to be dangling else! For enclosing all if statements in block
example: outer to which if statement to
associate the else clause.
For example

/* dangling else, as to
which if statement, else
clause associates */

10
25-09-2024

ELSE IF LADDER
The general form of else-if ladder is
shown in the diagram.
The expression is tested from the top(of if(expression1)
the ladder) downwards. {
statement block1;
As soon as the true condition is found, the }
statement associated with it is executed. else if(expression2)
{
statement block2;
}
else if(expression3 )
{
statement block3;
}
else
default statement;

ELSE IF LADDER

11
25-09-2024

Example

EXAMPLE
Write a program to check the divisibility of 5 and 8.

#include <stdio.h>
int main( )
{
int a=40 ; Output:
if( a%5==0 && a%8==0)
{ divisible by 5
printf("divisible by both 5 and 8");
}
else if( a%8==0 )
{
printf("divisible by 8");
}
else if(a%5==0)
{
printf("divisible by 5");
}
else
{
printf("divisible by none");
}
return 0;
}

12
25-09-2024

Example
WAP to check entered character is digit or uppercase or lowercase alphabet .
#include <stdio.h>
int main( )
{ char ch;
printf(“Enter the character”);
scanf(“%c”,&ch);
if (ch>=‘0’ && ch<=‘9’ )
printf(“\n It is a digit");
else if (ch>=‘A’ && ch<=‘Z’ )
printf(“\n It is a uppercase alphabet");
else if (ch>=‘a’ && ch<=‘z’ )
printf(“\n It is a lowercase alphabet");
else
printf(“\n Special character”);
return 0;
}

POINTS TO REMEMBER
1. In if statement, a single statement can be included without enclosing it into curly
braces { } No curly braces are required in the above case, but if we have more
than one statement inside if condition, then we must enclose them inside curly
braces.

int a = 5;
if(a > 4)
printf("success");

2. == must be used for comparison in the expression of if condition, if you use = the
expression will always return true, because it performs assignment not comparison.

13
25-09-2024

POINTS TO REMEMBER
3. Other than 0(zero), all other values are considered as
true.
In below example, hello will be printed.
if(27)
printf("hello");

Original statement Simplified statement


if(a!=0) if(a)
statement statement
if(a==0) if(!a)
statement statement

SWITCH STATEMENT
1. One of the classic problem encountered in nested if-
else / else-if ladder is called problem of Confusion.

2. It occurs when no matching else is available for if .

3. As the number of alternatives increases the


Complexity of program increases drastically.

4. To overcome this, C Provide a multi-way decision


statement called ‘Switch Statement‘

14
25-09-2024

SEE HOW DIFFICULT IS THIS SCENARIO ?

SYNTAX SWITCH STATEMENT


• When a case constant is found that
matches the switch expression,
switch (variable or integer expression ) control of the program passes to
{ the block of code associated with
case value1 : code to be executed that case.
if expression is
• In the above pseudocode, suppose
equal to value1
break; the value of expression is equal
case value2 : code to be executed to value1. The compiler will
if expression is execute the block of code
equal to value2 associate with the case statement
break; until the end of switch block, or
case ... until the break statement is
… encountered.
default :code to be executed if • The break statement is used to
expression doesn’t not
prevent the code running into the
match any values.
} next case.

15
25-09-2024

EXAMPLE
main()
{
Output:
int i=2;
switch(i) I am in Case 2
{ I am in Case 3
case 1: printf(“I am in Case 1\n”); I am in Default
case 2: printf(“I am in Case 2\n”);
case 3: printf(“I am in Case 3\n”);
default: printf(“I am in Default\n”);
}
}

POINTS TO REMEMBER
If you want that only case 2 should be executed,
Use a break statement.

16
25-09-2024

EXAMPLE
main()
{ Output:
int i=2;
switch(i)
{ I am in Case 2
case 1: printf(“I am in Case 1\n”);
break;
case 2: printf(“I am in Case 2\n”);
break;
case 3: printf(“I am in Case 3\n”);
break;
default: printf(“I am in Default\n”);
}
}

EXECUTION SWITCH STATEMENT

Steps are Shown in Circles.

17
25-09-2024

SWITCH CASE WORKING

SWITCH STATEMENT
• The switch statement provides
another way to decide which
statement to execute next.

• A switch statement work with


byte, short, char and int
primitive data type, it also
works with enumerated types
and string

18
25-09-2024

LIMITATIONS OF SWITCH CASE STATEMENT


1. Logical operators cannot be used with switch statement. For
instance
Example : case k>=20: //is not allowed

2. Switch case variables can have only int and char data type. So
float data type is not allowed.

3. In switch statement default is optional but when we use this in


switch, default is executed at last whenever all cases does not
satisfy the condition.

4. The break statement ends the switch statement. If break


statement is not used, all cases after the correct case is
executed.

RULES OF SWITCH CASE


STATEMENT
1.Case Label must be unique.
2.Case Labels must ends with Colon.
3.Case labels must have constants / constant expression.
4.Case label must be of integral Type ( Integer,Character).
5.Case label should not be ‘floating point number ‘.
6.Switch case should have at most one default label.
7.Default label is Optional.
8.Default can be placed anywhere in the switch.
9.Break Statement takes control out of the switch.
10.Two or more cases may share one break statement.
11.Nesting ( switch within switch ) is allowed.
12.Relational Operators are not allowed in Switch Statement.
13.Macro Identifier are allowed as Switch Case Label.
14.Const Variable is allowed in switch Case Statement.
15.Empty Switch case is allowed.
16.All Cases must wrapped in any of the case.

19
25-09-2024

RULE 1 : CASE LABEL MUST BE UNIQUE

RULE 2 : CASE LABELS MUST END WITH


COLON

case 1 :
printf("C Programming Language");
break;

20
25-09-2024

RULE 3 : CASE LABELS MUST HAVE CONSTANTS /


CONSTANT EXPRESSION
VALID NOT VALID

NOTE : variables are not allowed in switch case


labels.

RULE 4 : CASE LABEL MUST BE OF INTEGRAL


TYPE ( INTEGER, CHARACTER)

VALID

21
25-09-2024

CASE 5 : CASE LABEL SHOULD NOT BE ‘FLOATING POINT


NUMBER OR CASE LABELS MUST NOT CONTAIN ANY
VARIABLE
Case label must be constant
value.

NOT VALID

RULE 6 : SWITCH CASE MUST HAVE AT MOST ONE


DEFAULT LABEL

22
25-09-2024

RULE 7 : DEFAULT LABEL IS OPTIONAL


->default statement
is optional. It can
be neglected.

Rule 8 : Default can be placed anywhere in the


switch

23
25-09-2024

RULE 9 : BREAK STATEMENT


TAKES CONTROL OUT OF THE
SWITCH

RULE 10 : TWO OR MORE CASES MAY SHARE


ONE BREAK STATEMENT

24
25-09-2024

RULE 11 : NESTING ( SWITCH WITHIN


SWITCH ) IS ALLOWED
nesting of switch
case is allowed
in C.

RULE 12 : RELATIONAL OPERATORS ARE


NOT ALLOWED IN SWITCH STATEMENT.
relational operators
are not allowed as
switch label.

25
25-09-2024

RULE 13 : MACRO IDENTIFIER ARE ALLOWED


AS SWITCH CASE LABEL

as preprocessor will
replace occurrence of
MAX by constant value
i.e 2 therefore it is
allowed.

RULE 14 : CONST VARIABLE IS ALLOWED


IN SWITCH CASE STATEMENT

26
25-09-2024

RULE 14 : CONST EXPRESSIONS ARE


ALLOWED IN SWITCH STATEMENT.
Valid expressions for switch
// Constant expressions
allowed
switch(1+2+23)
switch(1*2+3%4)

Invalid switch expressions for switch:


// Variable expression not
allowed
switch(ab+cd)
switch(a+b+c)

CASE 15: EMPTY SWITCH CASE


IS ALLOWED

27
25-09-2024

CASE 16: ALL CASES MUST WRAPPED IN ANY OF


THE CASE
( Generally Compiler won’t show Error Message but It will neglect statement which does not belongs to
any case)

Output : Hi Case 1

SWITCH CASE STATEMENT SUMMARY


The switch statement evaluates an expression, then attempts to match the
result to one of several possible cases where each case contains a value
and a list of statements.

The flow of control transfers to statement associated with the first case
value that matches.

Often a break statement is used as the last statement in each case's


statement list.

A break statement causes control to transfer to the end of the switch


statement.

If a break statement is not used, the flow of control will continue into the
next case.

A switch statement can have an optional default case.

28
25-09-2024

SWITCH CASE STATEMENT SUMMARY


The default case has no associated value and simply uses the reserved word
default.

If the default case is present, control will transfer to it if no other case value
matches.

If there is no default case, and no other value matches, control falls through to
the statement after the switch.

The expression of a switch statement must result in an integral type, meaning an


integer (byte, short, int,) or a char

It cannot be a floating point value (float or double)(ex: case 2.3 is invalid).

It cannot be a string constant(ex: case “second” is invalid)

You cannot perform relational checks with a switch statement

EXAMPLE
#include<stdio.h>
int main ( )
{
char grade =‘b’ ;
switch (grade)
{
case 'a' :
printf (“value is a.\n") ;
break;
case 'b' :
printf (“value is b.\n") ;
break;
default :
printf (“Default!!\n") ;
} /* End of switch-case structure */
} /* End of main program */

29
25-09-2024

EXAMPLE
#include <stdio.h>
int main ( )
{
char grade =‘b’ ;
switch (grade)
{ Output:
case 'a' : value is b.
printf (“value is a.\n") ;
break; case
'b' :
printf (“value is b.\n") ;
break;
default :
printf (“Default!!\n") ;
} /* End of switch-case structure */
} /* End of main program */

Example
Write a program to perform all arithmetic operations to select their
corresponding operator
case ‘-' :
#include <stdio.h>
printf (“\n sub =%d”,a-b);
int main ( ) break;
case ‘*’ :
{
printf (“\n mul=%d”,a*b);
char op ; break;
case ‘/' :
int a,b; printf (“\n div=%d”,a/b);
printf(“Enter operator for operation +,-,*,/ break;
:”); default :
printf(“\n invalid
scanf(“%c”,&op); operator”);
printf(“Enter 2 numbers”); break;
}
scanf(“%d%d”,&a,&b); return 0;
switch (op) }

{
case ‘+' :
printf (“\n sum =%d”,a+b) ;
break;

30
25-09-2024

EXAMPLE
#include <stdio.h>
int main ( )
{
char grade =‘a’ ;
switch (grade)
{
case 'a' :
case 'A' :
printf ("Good Job!\n") ;
case 'b' :
case 'B' :
printf ("Pretty good.\n") ;
default :
printf ("You are failing!!\n") ;
} /* End of switch-case structure */
} /* End of main program */

EXAMPLE
#include <stdio.h>
int main ( )
{ Output:
char grade =‘a’;
switch (grade) Good Job!
{ Pretty good.
case 'a' : You are failing!
case 'A' :
printf ("Good Job!\n") ;
case 'b' :
case 'B' :
printf ("Pretty good.\n") ;
default :
printf ("You are failing!!\n") ;
} /* End of switch-case structure */
} /* End of main program */

31
25-09-2024

LOOPING
Looping is the process of executing a group of statements repeatedly either a
specified number of times or until some condition is satisfied.
Loops allow program to execute a statement or group of statements multiple times
repeatedly until certain test condition is false.
That is, Loops are used in performing repetitive task in programming.
Loop Consists of
 Body of the loop
 Control Statement

WHY USE LOOPS???


There may be a situation, when you need to execute a block of
code several number of times. Consider the scenarios:
You want to execute some code/s 100 times…
 It’s not wise to write the same code 100 times.

You want to calculate the value of n!, for any value of n…


 If n = 1000, it’s not elegant to write the code as 1*2*3*…*1000.

32
25-09-2024

Repetition occurs as long as a condition is true

false

true
Body

TYPE OF LOOPS
Depending upon the position of the control statement in the loop, loop is of two types
 Entry-controlled loop/Pretest loop
 Exit-controlled loop/Posttest loop

33
25-09-2024

Entry-controlled loop/Pretest loop

The types of loop where the test condition is tested before the execution of the
loop.

If the test condition is true, then the loop gets the execution, otherwise not.

Exit-controlled loop/Posttest loop

The body of the loop is executed without testing the condition for the first time.
Then the condition is tested.
If it is true, then the loop is executed again and continues till the result of the test
condition is not false.

34
25-09-2024

Type of loops

Body of Loop
False
Test
Condition

False
True Test
Condition

Body of Loop
True

Entry-Controlled/Pre-Test Loop Exit-Controlled/Post-Test Loop

PRETEST LOOP VS POSTTEST LOOP

35
25-09-2024

PRETEST LOOP VS POSTTEST LOOP


Pretest loop Posttest loop
1. In each iteration, the control 1. In each iteration, the loop action(s)
expression is tested first. are executed. Then, the control
expression is tested.
2. If control expression is true, the 2. If control expression is true, a new
loop continues; otherwise, the loop iteration is started; otherwise, the
is terminated. loop is terminated.
3. Initialization: 1 3. Initialization: 1
4. Number of tests: n+1 4. Number of tests: n
5. Action executed: n 5. Action executed: n
6. Updating executed: n 6. Updating executed: n
7. Minimum iterations: 0 7. Minimum iterations: 1

STEPS IN LOOPING
Initialization of condition variable
Execution of body of the loop
Test the control statement
Updating the condition variable

36
25-09-2024

COMMON LOOPS

for while do while

THE WHILE LOOP

A while loop is an entry control loop having the following


syntax:

Working Principle:

while (condition)  If the condition is true, the


statement/s is executed.
Body {
of Statements;  Then the condition is evaluated
the
} again, and if it is still true, the
loop
statement is executed again.

 The statement is executed


repeatedly until the condition
becomes false.

C. V. RAMAN COLLEGE OF ENGINEERING 74

37
25-09-2024

LOGIC OF A WHILE LOOP

Syntax: condition
evaluated
while (condition)
{
true false
Statements;
}
statement

Out of Body of Loop

C. V. RAMAN COLLEGE OF ENGINEERING 75

AN EXAMPLE OF WHILE LOOP


count
int count = 1;
while (count <= 5)
{
printf(“HELLO\n”); TRUE 5 4 3 2 1
count++;
} FALS 6
E

OUTPUT: The condition (count <=5) remains


HELLO TRUE for :
HELLO count=1 count =2 count =3
count =4 count = 5
HELLO
HELLO For count = 6….the condition
HELLO becomes FALSE
C. V. RAMAN COLLEGE OF ENGINEERING 76

38
25-09-2024

ANOTHER EXAMPLE
Condition is TRUE for
count = 1, 2, 3, 4,5
int count = 1;
while (count <= 5)
{
printf(“count=%d\t”,count);
count++;
}

OUTPUT
1 2 3 4 5

Prints the value of count


until the condition becomes
false

C. V. RAMAN COLLEGE OF ENGINEERING 77

CONTD…
Condition is FALSE from
the first time.
int count = 10;
while (count <= 5)
{
printf(“HELLO\n”);
count++; NO
}
OUTPUT

• If the condition of a while loop is FALSE initially, the statement


is never executed.
• Therefore, the body of a while loop will execute zero times.

C. V. RAMAN COLLEGE OF ENGINEERING 78

39
25-09-2024

CONTD…
Loop control variable is the
variable whose value controls
loop repetition

int count = 1;
while (count <= 5)
{
printf(“HELLO\n”); In this
count++; example,
} count is the
loop control
variable.

C. V. RAMAN COLLEGE OF ENGINEERING 79

PROGRAM TO FIND SUM OF DIGITS OF A


NUMBER

main( ) Output :
{
Enter a number : 1452
int n, sum=0, rem;
Sum of digits = 12
printf(“Enter a number : ”);
scanf(“%d”, &n);
while(n>0)
Taking a number as input
{
rem = n%10;
sum = sum + rem; Checking the condition:
n = n/10; True or False
}
printf(“Sum of digits =%d\n”, sum);
}

C. V. RAMAN COLLEGE OF ENGINEERING 80

40
25-09-2024

LETS SEE THE WORKING OF


THE LOOP
Consider the input given as
n = 1452

Before loop starts rem=garbage value sum=0 n =1452

After 1st iteration rem=1452%10=2 sum=0+2=2 n =145

After 2nd iteration rem=145%10=5 sum=2+5=7 n =14

After 3rd iteration rem=14%10=4 sum=7+4=11 n =1

After 4th iteration rem=1%10=1 sum=11+1=12 n =0

For the 5th iteration as n = 0 now….the condition becomes FALSE and


we are out of the loop body

C. V. RAMAN COLLEGE OF ENGINEERING 81

PROGRAM TO CHECK PALINDROME

41
25-09-2024

PROGRAM TO CHECK PALINDROME


#include <stdio.h>
int main()
{
int n, reversedInteger = 0, remainder, Ouput
originalInteger; Enter an integer:
printf("Enter an integer: "); 1001
scanf("%d", &n); 1001 is a
originalInteger = n; palindrome.
while( n!=0 )
{
remainder = n%10;
reversedInteger = reversedInteger*10 +
// reversed
remainder;
integer is stored
n /= 10;
in variable
}
if (originalInteger == reversedInteger)
printf("%d is a palindrome.",
originalInteger); // palindrome if original
else Integer and reversed
printf("%d is not a palindrome.", Integer are equal
originalInteger);
return 0;
}

PROGRAM TO CHECK ARMSTRONG


NUMBER

42
25-09-2024

PROGRAM TO CHECK ARMSTRONG


NUMBER
A positive integer is called an Armstrong number of order n if
abcd... = an + bn + cn + dn + ...

In case of an Armstrong number of 3 digits, the sum of cubes of


each digits is equal to the number itself.
For example:

153 = 1*1*1 + 5*5*5 + 3*3*3 // 153 is an Armstrong


number

CHECK ARMSTRONG NUMBER OF THREE


DIGITS
START
IMPLEMENTATION
Step 1 : Take integer variable #include <stdio.h>
Arms int main() {
Step 2 : Assign value to the int arms = 153;
variable int check, rem, sum = 0;
Step 3 : Split all digits of Arms check = arms;
Step 4 : Find cube-value of each while(check != 0) {
digits rem = check % 10;
Step 5 : Add all cube-values sum = sum + (rem * rem * rem);
together check = check / 10;
Step 6 : Save the output to Sum }
variable if(sum == arms)
Step 7 : If Sum equals to Arms printf("%d is an armstrong number.", arms);
print Armstrong Number else
Step 8 : If Sum not equals to Arms printf("%d is not an armstrong number.",
print Not Armstrong Number arms);
return 0;
STOP }

43
25-09-2024

CONVERSION OF DECIMAL TO
BINARY ???

CONVERSION OF DECIMAL TO BINARY


#include<stdio.h>
void main()
{
int dec,rem,i=1;
long int bin=0;
printf("Enter the decimal number : ");
scanf("%d",&dec);
while(dec>0)
{
rem=dec%2;
dec=dec/2;
bin=bin+(i*rem);
i=i*10;
}
printf("The binary number is %ld",bin);

44
25-09-2024

INFINITE LOOPS

The body of a loop eventually must make the condition false and
terminate at a point.

If not, it is called an infinite loop, which will execute until the user
interrupts the program or until an underflow error occurs.

This is a common logical (semantic) error.

Example:
int count = 1; Here the condition is
while (count <= 25) always true so it is an
{ infinite loop.
printf(“%d\t”,count);
count = count - 1;
}

C. V. RAMAN COLLEGE OF ENGINEERING 89

WAYS OF INFINITE WHILE LOOP


1 : Semicolon at the end of while loop Explanation :
1.In the above program ,
#include<stdio.h> Condition is specified in the
void main() While Loop
{
int num=300; 2.Semicolon at the end of
while(num>255); //Note it while indicated while
Carefully without body.
printf(“Hello”); 3.In the program variable
} num doesn’t get
incremented , condition
Output : remains true forever.
It won't Print anything
4.As Above program does
not have Loop body , It
Above
won’t statement
print can be interpreted as –
anything
while(num>255){
}

45
25-09-2024

WAYS OF INFINITE WHILE LOOP


2 : Non-Zero Number as a Parameter Explanation :
1.We can specify any
#include<stdio.h>
non-zero positive
void main()
number inside while
{
loop
while(1)
printf(“Hello”);
2.Non zero number is
}
specified in the while
loop which means that
Output while loop will
remains true forever.
Infinite Time "Hello" word

WAYS OF INFINITE WHILE LOOP


3 : Subscript variable remains the same Explanation :
1.Condition is specified
#include<stdio.h> in while Loop, but
void main() terminating condition is
{ not specified and even
int num=20; we haven’t modified
while(num>10) the condition variable.
{
printf(“Hello”); 2.In this case our
} subscript variable
} (Variable used to
Repeat action) is not
Output : either incremented or
decremented
Infinite Time "Hello C" word
3.so while remains true
forever

46
25-09-2024

WAYS OF INFINITE WHILE LOOP


4 : Character as a Parameter in While LoopExplanation :

1.Character is
#include<stdio.h> Represented in integer
void main() in the form of ASCII
{ internally.
while(‘A’)
printf(“Hello”); 2.Any Character is
} Converted into Non-
zero Integer ASCII
Output : value

Infinite Time "Hello" word 3.Any Non-zero ASCII


value is TRUE condition
, that is why Loop
executes forever

SOME MORE EXAMPLES OF INFINITE


LOOPS

while(1) while(100)
{ {
printf(“Good Morning\n”); printf(“Good Morning\n”);
} }

while(‘A’) while(-525)
{ {
printf(“Good Morning\n”); printf(“Good Morning\n”);
} }

C. V. RAMAN COLLEGE OF ENGINEERING 94

47
25-09-2024

NESTED LOOPS

When the body of one loop contains another loop, then it is called a
Nested Loop.

Nested loops contain an outer loop with one or more inner loops.

Here for each iteration of the outer loop ,the inner loop iterates completely.

EXAMPLE Outer while


loop
count1 = 1;
while (count1 <= 10)
{ Inner while loop
count2 = 1;
while (count2 <= 20)
{ For each value of count1…
printf("Hello"); count2 will be executed 20 times.
count2++;
} count1 has 10 values & count2
has 20 values, therefore Hello
count1++; will be printed 10 * 20 times.
}

How many times will the above code print “Hello”???

48
25-09-2024

THE DO-WHILE LOOP


A do-while loop is an exit control loop having the following
syntax:

Working Principle:
do  Initially, the statement/s is
{ executed once and then the
Body
Statements; condition is checked.
of
the } while (condition);  If the condition is true, the
loop
statement is executed again.

 The statement is executed


repeatedly until the condition
becomes false.

LOGIC OF A DO-WHILE LOOP

Syntax:
statement
do
{
Statements; true
} while (condition); condition
evaluated

false

Out of Body of Loop

49
25-09-2024

DO-WHILE LOOP SYNTAX :


initialization;
NOTES
do
 It is Exit Controlled Loop.
{
 Initialization , Incrementation and
--------------
Condition steps are on different
--------------
Line.
--------------
 It is also called Bottom Tested
--------------
incrementation;
}while(condition);

EXAMPLE OF DO-WHILE LOOP


C program to print the table of 5 from 1 to 10.

#include<stdio.h>
OUTPUT
int main()
5*1=5
{
5 * 2 = 10
int i=1;
5 * 3 = 15
do
5 * 4 = 20
{
5 * 5 = 25
printf(“5 * %d = %d\n”,i,5*i);
5 * 6 = 30
i++;
5 * 7 = 35
}while(i<=10);
5 * 8 = 40
return 0;
5 * 9 = 45
}
5 * 10 = 50

50
25-09-2024

FOR
Syntax:

for (expr1; expr2; expr3)


statement;

 expr1 controls the looping action,

 expr2 represents a condition that ensures loop


continuation,

 expr3 modifies the value of the control variable


initially assigned by expr1

keyword final value of control variable


for which the condition is true
control variable i

for (i=1; i <= n; i = i + 1)


initial value
of control increment of control variable
variable

loop continuation
condition

51
25-09-2024

EXAMPLES
Vary the control variable from 1 to 100 in increments of 1
for (i = 1; i <= 100; i++)

Vary the control variable from 100 to 1 in increments of -1


for (i = 100; i >= 1; i--)

Vary the control variable from 5 to 55 in increments of 5


for (i = 5; i <= 55; i+=5)

EXAMPLES 2
#include <stdio.h>

void main()
{
/* a program to produce a Celsius to Fahrenheit conversion chart for the
numbers 0 to 100 */
int celsius;
for (celsius = 0; celsius <= 100; celsius++)
printf(“Celsius: %d Fahrenheit: %d\n”, celsius, (celsius * 9) / 5 + 32);
}

52
25-09-2024

NESTED FOR LOOPS


Nested means there is a loop within a loop

Executed from the inside out


 Each loop is like a layer and has its own counter variable, its own loop expression and its own loop
body

 In a nested loop, for each value of the outermost counter variable, the complete inner loop will be
executed once

General form

for (loop1_exprs) {
loop_body_1a

for (loop2_exprs) {
loop_body_2
}
loop_body_1b
}

53
25-09-2024

NESTED LOOPS
 When the body of one loop contains another loop, then it is
called a Nested Loop.
 Nested loops contain an outer loop with one or more inner
loops.
 Here for each iteration of the outer loop ,the inner loop iterates
completely.
Types of nested loops
 Nested for Loop
 Nested while loop
 Nested do-while Loop
Note: There can be mixed type of nested loop i.e. a for loop
inside a while loop, or a while loop inside a do-while loop.

NESTED FOR LOOP


A for loop inside another for loop is called nested for loop.
SYNTAX FLOWCHART

for (initialization; condition;


increment/decrement)
{
statement(s);
for (initialization; condition;
increment/decrement) {
statement(s);
... ... ...
}
... ... ...
}

54
25-09-2024

C PROGRAM TO PRINT THE FOLLOWING STAR


PATTERN
*
**
***
****
*****

C PROGRAM TO PRINT THE FOLLOWING STAR


PATTERN
*
#include <stdio.h>
**
void main() {
***
int i,j;
****
for (i=0; i<5; i++) {
*****
for (j=0; j<=i; j++)
{
printf(" * ");
}
printf("\n");
}
}

55
25-09-2024

C PROGRAM TO PRINT THE FOLLOWING STAR


PATTERN
*
**
***
****
*****

C PROGRAM TO PRINT THE FOLLOWING STAR


PATTERN
#include<stdio.h>
int main()
{
* int i,j,k,n;
printf("Enter the value of n : ");
** scanf("%d",&n);
*** for(i=0;i<n;i++)
**** {
***** printf("\n");
for(j=n-1;j>i;j--)
printf(" ");
for(j=0;j<=i;j++)
printf(" *");
printf(“\n”) ;
}
return 0;
}

56
25-09-2024

NESTED WHILE LOOP


A while loop inside another while loop is called nested while loop.

Syntax Flowchart

while (condition1)
{
statement(s);
while (condition2)
{
statement(s);
... ... ...
}
... ... ...
}

EXAMPLE
Outer
while loop
count1 = 1;
while (count1 <= 10)
Inner while
{
loop
count2 = 1;
while (count2 <= 20) For each value of
{ count1…
printf("Hello"); count2 will be executed 20
times.
count2++;
} count1 has 10 values &
count1++; count2 has 20 values,
} therefore Hello will be
printed 10 * 20 times.

How many times will the above code print “Hello”???

57
25-09-2024

C PROGRAM TO PRINT THE NUMBER PATTERN


USING NESTED WHILE LOOP
1
12
123
1234
12345

C PROGRAM TO PRINT THE NUMBER PATTERN


USING NESTED WHILE LOOP
#include <stdio.h>
int main()
{
1
int i=1,j;
12 while (i <= 5)
123 {
1234 j=1;
12345 while (j <= i )
{
printf("%d ",j);
j++;
}
printf("\n");
i++;
}
return 0;
}

58
25-09-2024

NESTED DO-WHILE LOOP


A do-while loop inside another do-while loop is called nested do-
while loop
Syntax Flowchart
do
{
statement(s);
do
{
statement(s);
... ... ...
}while(condition2);
... ... ...
}while (condition1);

PROGRAM TO PRINT THE GIVEN STAR PATTERN


USING DO WHILE LOOP
*
**
***
****
*****

59
25-09-2024

PROGRAM TO PRINT THE GIVEN STAR PATTERN


USING DO WHILE LOOP
#include <stdio.h>
int main()
{
* int i=1,j;
** do
*** {
**** j=1;
do
***** {
printf("*");
j++;
}while(j <= i);
i++;
printf("\n");
}while(i <= 5);
return 0;
}

LOOP CONTROL STATEMENTS


•Loop control statements change execution from its
normal sequence.
•When execution leaves a scope, all automatic
objects that were created in that scope are
destroyed.
•C supports the following control statements.

• Break statement
• Continue statement
• Goto Statement

60
25-09-2024

BREAK
The break statement in C programming has the following two
usages −
1. When a break statement is encountered inside a loop, the loop
is immediately terminated and the program control resumes at
the next statement following the loop.
2. It can be used to terminate a case in the switch statement
If you are using nested loops, the break statement will stop the
execution of the innermost loop and start executing the next line of
code after the block.
.
Syntax
The syntax for a break statement in C is as follows −
break;

FLOWCHART OF BREAK STATEMENT

61
25-09-2024

HOW BREAK STATEMENT WORKS?

HOW BREAK STATEMENT WORKS?

62
25-09-2024

CALCULATE THE SUM OF MAXIMUM OF 10


NUMBERS USING BREAK
# include <stdio.h> // Calculates sum until user enters positive number
int main()
{
int i;
double number, sum = 0.0;
for(i=1; i <= 10; ++i) // If user enters negative number, loop is terminated
{
printf("Enter a n%d: ",i);
scanf("%lf",&number);
if(number < 0.0)
{
break;
}
sum += number; // sum = sum + number;
}
printf("Sum = %.2lf",sum);
return 0;
}

CALCULATE THE SUM OF MAXIMUM OF 10


NUMBERS USING BREAK
# include <stdio.h> // Calculates sum until user enters positive number
int main()
{
int i;
double number, sum = 0.0;
for(i=1; i <= 10; ++i) // If user enters negative number, loop is terminated
{
printf("Enter a n%d: ",i);
scanf("%lf",&number); OUTPUT
if(number < 0.0)
{
Enter a n1: 2.4
break; Enter a n2: 4.5
} Enter a n3: 3.4
sum += number;
}
Enter a n4: -3
printf("Sum = %.2lf",sum); Sum = 10.30
return 0;
}

63
25-09-2024

CONTINUE STATEMENT
 The continue statement in C programming works somewhat
like the break statement.
 Instead of forcing termination, it forces the next iteration of the
loop to take place, skipping any code in between.
 For the for loop, continue statement causes the conditional test
and increment portions of the loop to execute.
 For the while and do...while loops, continue statement causes
the program control to pass to the conditional tests.

Syntax of continue Statement


continue;

FLOWCHART OF CONTINUE STATEMENT

64
25-09-2024

HOW CONTINUE STATEMENT WORKS?

CALCULATE THE SUM OF MAXIMUM OF 10


NUMBERS USING CONTINUE
# include <stdio.h> // Negative numbers are skipped from calculation
int main()
{
int i;
double number, sum = 0.0;
for(i=1; i <= 10; ++i)
{
printf("Enter a n%d: ",i);
scanf("%lf",&number);
if(number < 0.0) // If user enters
{ negative number,
continue; loop is terminated
}
sum += number; // sum = sum + number;
}
printf("Sum = %.2lf",sum);
return 0;
}

65
25-09-2024

CALCULATE THE SUM OF MAXIMUM OF 10


NUMBERS USING CONTINUE
# include <stdio.h> // Negative numbers are skipped from calculation
int main()
{
int i;
double number, sum = 0.0;
OUTPUT
for(i=1; i <= 10; ++i)
{
Enter a n1: 1.1
printf("Enter a n%d: ",i); Enter a n2: 2.2
scanf("%lf",&number); Enter a n3: 5.5
if(number < 0.0) // If user enters Enter a n4: 4.4
{ negative number, Enter a n5: -3.4
continue; loop is terminated Enter a n6: -45.5
} Enter a n7: 34.5
sum += number; // sum = sum + number; Enter a n8: -4.2
}
Enter a n9: -1000
printf("Sum = %.2lf",sum);
return 0;
Enter a n10: 12
} Sum = 59.70

BREAK VS CONTINUE
break causes an exit from the
innermost enclosing loop

continue causes the current iteration of


a loop to stop and the next iteration to
begin immediately

66
25-09-2024

WHILE VS. DO-WHILE


while -- the expression is tested first, if the result is false, the loop body is never
executed

do-while -- the loop body is always executed once. After that, the expression is
tested, if the result is false, the loop body is not executed again

C GOTO STATEMENT
The goto statement is used to alter the normal sequence
of a C program.

67
25-09-2024

SYNTAX OF GOTO STATEMENT


The label is an identifier. When goto statement is
encountered, control of the program jumps to label: and
starts executing the code.

goto label;
... .. ...
... .. ...
... .. ...
label:
statement;

CALCULATE THE SUM AND AVERAGE OF


MAXIMUM OF 5 NUMBERS USING GOTO
# include <stdio.h>
int main()
{
const int maxInput = 5;
int i;
double number, average, sum=0.0;
for(i=1; i<=maxInput; ++i)
{
printf("%d. Enter a number: ", i);
scanf("%lf",&number);

if(number < 0.0) // If user enters negative number, flow


goto jump; of program moves to label jump

sum += number;
}
jump:
average=sum/(i-1);
printf("Sum = %.2f\n", sum);
printf("Average = %.2f", average);
return 0;
}

68
25-09-2024

CALCULATE THE SUM AND AVERAGE OF


MAXIMUM OF 5 NUMBERS USING GOTO
# include <stdio.h>
int main()
{
const int maxInput = 5;
int i;
double number, average, sum=0.0;
for(i=1; i<=maxInput; ++i)
{
printf("%d. Enter a number: ", i);
scanf("%lf",&number);

if(number < 0.0) // If user enters negative number, flow of


goto jump; program moves to label jump

sum += number;
}
jump:
average=sum/(i-1);
printf("Sum = %.2f\n", sum);
printf("Average = %.2f", average);
return 0;
}

CALCULATE THE SUM AND AVERAGE OF


MAXIMUM OF 5 NUMBERS USING GOTO
# include <stdio.h>
Output
int main()
{ 1. Enter a number: 3
const int maxInput = 5; 2. Enter a number: 4.3
int i;
3. Enter a number: 9.3
double number, average, sum=0.0;
for(i=1; i<=maxInput; ++i) 4. Enter a number: -2.9
{ Sum = 16.60
printf("%d. Enter a number: ", i);
scanf("%lf",&number);
// If user enters negative number, flow of program
if(number < 0.0)
goto jump; moves to label jump

sum += number;
}
jump:
average=sum/(i-1);
printf("Sum = %.2f\n", sum);
printf("Average = %.2f", average);
return 0;
}

69
25-09-2024

REASONS TOstatement
The use of goto AVOID GOTO
may lead STATEMENT
to code that is buggy and hard
to follow.

For example

REASONS TOstatement
The use of goto AVOID may GOTO STATEMENT
lead to code that is buggy and
Also, goto statement allows you
hard to follow.
to do bad stuff such as jump out
of scope.
For example
That being said, goto statement
can be useful sometimes.
For example: to break from
nested loops.

70

You might also like