0% found this document useful (0 votes)
4 views59 pages

Loops

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views59 pages

Loops

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

DECISION MAKING &

LOOPING

Dr. Sourav Kanti Addya


Department of Computer Science & Engineering
National Institute of Technology Karnataka, Surathkal
Email: souravkaddya@[Link]
Previous topics - Branching

 Instruction of a programs are executed either


 Sequential manner
 Branching

 C language supports the following decision making


statements.
 if statement
 switch statement
 conditional operator
 goto statement
Loops
• A loop allows a program to repeat a group of statements, either any number
of times or until some loop condition occurs.

• Convenient if the exact number of repetitions are known

• We can use all of them for event-controlled and counter-controlled loops.

• Loop Consists of
• Body of the loop
• Control Statement
Body of Loop
Test False
Condition

True False
Test
Condition
Body of Loop

True

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


Steps in looping
• Initialization of condition variable

• Execution of body of the loop

• Test the control statement

• Updating the condition variable


Common loops

for while do while


Pretest Pretest Post-test
Repetition occurs as long as a condition is true

false

true
Body
Loop - while

expression 1; initialization
while (expression 2) condition checking
{
statements;
expression 3; updation of condition
}
 The statement is executed repeatedly as long as the expression is true
(non zero)

 The cycle continues until expression becomes zero, at which point


execution resumes after statement.
Loop - while
Loop - while
 If the test expression in a while loop is false initially, the
while loop will never be executed

int i = 1, sum = 0;
while (i <= 10)
{
sum = sum + i;
i= i + 1;
}
printf(“Sum = %d\n”, sum);
Example 1

#include<stdio.h>
int main(void)
{
int i=9;
while(i<10)
printf(“NITK Surathkal”);
i++;
return 0;
}
Example 2

#include<stdio.h>
int main()
{
int i=1,number=0,b=9;
printf("Enter a number: ");
scanf("%d",&number);
while(i<=10)
{
printf("%d \n",(number*i));
i++;
}
return 0;
}
Example 3
Example 3 (Cont..)
Loop - for
A for loop is used when a loop is to be executed a known
number of times. We can do the same thing with a while loop,
but the for loop is easier to read and more natural for counting
loops.
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
Loop - for
While vs. for
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
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 1 to 100 */
int celsius;
for (celsius = 0; celsius <= 100; celsius++)
printf(“Celsius: %d Fahrenheit: %d\n”, celsius, (celsius * 9) / 5 + 32);
}
Examples 2… (Cont..)
Examples 3
Examples 3… (Cont..)
Infinitive for loop in C

#include<stdio.h>
void main ()
{
for(;;)
{
printf(“NITK");
}
}

If you run this program, you will see above statement infinite times.
Multiple initialization inside for Loop in C

for (i=1,j=1;i<10 && j<10; i++, j++)

• It is initializing two variables. Note: both are separated by comma (,).


• It has two test conditions joined together using AND (&&) logical
operator. Note: You cannot use multiple test conditions separated by
comma, you must use logical operator such as && or || to join conditions.
• It has two variables in increment part. Note: Should be separated by
comma.
Multiple initialization inside for Loop in C
#include <stdio.h>
int main()
{
int i,j;
for (i=1,j=1 ; i<3 || j<5; i++,j++)
{
printf("%d, %d\n",i ,j);
}
return 0;
}
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
Outer_loop
{
Inner_loop
{
// inner loop statements.
}
// outer loop statements.
}
General form
for (loop1_exprs) while(condition)
{
{ while(condition)
loop_body_1a {
// inner loop statements.
for (loop2_exprs) }
{ // outer loop statements.
}
loop_body_2
}
loop_body_1b
}
Example
#include <stdio.h>
int main()
{
int n; // variable declaration
printf("Enter the value of n :");
// Displaying the n tables.
for(int i=1;i<=n;i++) // outer loop
{
for(int j=1;j<=10;j++) // inner loop
{
printf("%d\t",(i*j)); // printing the value.
}
printf("\n");
} }
#include <stdio.h>
int main()
{
int n, i;
unsigned long long fact = 1;
printf("Enter an integer: ");
scanf("%d", &n);
// shows error if the user enters a negative integer
if (n < 0)
printf("Error! Factorial of a negative number doesn't exist.");
else
{
for (i = 1; i <= n; ++i)
{
fact *= i;
}
printf("Factorial of %d = %llu", n, fact);
}
return 0;
}
Examples 4 A Simple Nested for Loop
Examples 4… (Cont..)
Loop do-while

 When a loop is constructed using while, the test for continuation is


carried out at the beginning of each pass

 With do-while the test for continuation takes place at the end of each
pass

do
{
statement
} while (expression);
Loop do-while
Example
int i = 1, sum = 0;

do

sum = sum + i;

i= i + 1;

}while(i<=10);

printf(“Sum = %d\n”, sum);


Example Two Simple Loops
Example Two Simple Loops
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
while vs. do-while Pre- and Post-test Loops
while vs. do-while Example
Adding a List with the do…while
while vs. do-while Example
Adding a List with the do…while
while vs. do-while Example
Comparison of while and do…while
while vs. do-while Example
Comparison of while and do…while
Jumps in loops
Jump Statement makes the control jump to another section of the program
unconditionally when encountered. It is usually used to terminate the loop or
switch-case instantly. It is also used to escape the execution of a section of the
program.
These interrupt normal flow of control.

• break
• continue
• goto
• return
Jumps in loops break and 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

break
A break statement is used to terminate the execution of the rest of the block
where it is present and takes the control out of the block to the next
statement.
It is mostly used in loops and switch-case to bypass the rest of the statement
and take the control to the end of the loop.
Jumps in loops break and continue
continue
The continue jump statement like any other jump statement interrupts or
changes the flow of control during the execution of a program. Continue is
mostly used in loops.
Rather than terminating the loop it stops the execution of the statements
underneath and takes control to the next iteration.
Similar to a break statement, in the case of a nested loop, the continue passes
the control to the next iteration of the inner loop where it is present and not to
any of the outer loops.
Example
while (expression) while (expression)
{ {
statements; statements
if(condition) continue;
break; more_statements
more_statements }
}
Example
#include <stdio.h> Output:-
1
int main() 2
{ 3
int i; 4
5
for (i = 1; i <= 15; i++) 6
{ 7
printf("%d\n", i); 8
9
if (i == 10) 10
break;
}
return 0;
}
Example
Output:-
#include <stdio.h> 1
int main() 3
{ 4
int i, j; 1
for (i = 1; i < 3; i++) 3
4
{
for (j = 1; j < 5; j++)
{
if (j == 2)
continue;
printf("%d\n", j);
}
}
return 0;
}
Jumps in loops
goto
goto jump statement is used to transfer the flow of control to any part of the
program desired. The programmer needs to specify a label or identifier with
the goto statement in the following manner:
goto label;
Example
#include <stdio.h>
int main()
{ Output:-
int i, j; 1
for (i = 1; i < 5; i++) Two
{
if (i == 2)
goto there;
printf("%d\n", i);
}
there:
printf("Two");
return 0;
}
Jumps in loops
return
return jump statement is usually used at the end of a function to end or
terminate it with or without a value. It takes the control from the calling
function back to the main function(main function itself can also have a
return).
An important point to be taken into consideration is that return can only be
used in functions that is declared with a return type such as int, float, double,
char, etc.
The functions declared with void type does not return any value. Also, the
function returns the value that belongs to the same data type as it is declared.
Example
#include <stdio.h>

char func(int ascii) Output:-


{ Enter any ascii value in decimal:
return ((char) ascii); 110
} The character is : n

int main()
{
int ascii;
char ch;
printf("Enter any ascii value in decimal: \n");
scanf("%d", & ascii);
ch = func(ascii);
printf("The character is : %c", ch);
return 0;
}
Assignments

1. Given a list of marks WAP to compute and print the number


of students
 obtained more than 80 marks
 obtained more than 60 marks
 obtained more than 40 marks
 obtained less than 40 marks
 in range 81-100
 range 61-80
 range 41-60
 range 0-40
2. Print Floyd’s triangle
1
23
456
.
.
79……….91

3. WAP to compute real roots of a quadratic equation. Use


following rules
 No sol if both a and b are zero
 There is only one root if a=0
 There is no real roots if b2-4ac is negative
 Otherwise there are two real roots
4. WAP to read three integer values and display output stating that they are
the sides of right angled triangle
5. WAP to find the prime numbers between 2 to 100
6. WAP to find factorial of a number
7. WAP to print Fibonacci Series
1 1 2 3 5 8 13 21………
8. WAP to print based on user input
(a) 1 (b) *
22 **
333 ***
4444 ****
9. WAP that reads a positive integer and print its binary equivalent
10. WAP to accept any number upto six digits and print that in words
ex: 1265 IS one two six five
11. WAP for the following
1
1 2 1
1 3 3 1
1 4 6 4 1
12. WAP to generate all combinations of 1 2 and 3
13. WAP to print multiplication table of a number
14. WAP to print ascii values and their equivalent char using while loop
15. WAP to print armstrong number between 1 to 500
ex: 153 = (1*1*1)+(5*5*5)+(3*3*3)

You might also like