Nothing Special   »   [go: up one dir, main page]

5 Loops

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 46

Repetition Structures

CSE115: Programming Language I


An Example Problem
• Read in 10 integers and output their sum
An Example Problem
• Read in 10 integers and output their sum
#include <stdio.h> printf("Enter a number: ");
int main() scanf("%d",&a);
{ sum += a;
int a, sum = 0; printf("Enter a number: ");
printf("Enter a number: scanf("%d",&a);
"); sum += a;
scanf("%d",&a); printf("Enter a number: ");
sum += a; scanf("%d",&a);
printf("Enter a number: sum += a;
"); printf("Enter a number: ");
scanf("%d",&a); scanf("%d",&a);
sum += a; sum += a;
printf("Enter a number: printf("Enter a number: ");
"); scanf("%d",&a);
scanf("%d",&a); sum += a;
sum += a; printf("Total is %d\n", sum);
printf("Enter a number: return 0;
"); }
scanf("%d",&a);
sum += a;
printf("Enter a number:
Repetition Structure (Loop)
• Executes a number of statements more than one time
without having to write the statements multiple times.
• Two designs of loop :
• To execute a number of instructions from the program for a
finite, pre-determined number of time (Counter-controlled
loop)
• To execute a number of instructions indefinitely until the user
tells it to stop or a special condition is met (Sentinel-controlled
loop)
Repetition Structure (Loop)

Loop
condition
cond? false

Each round of the


true
loop is called an
iteration. Some
statement(s)

loop body
Repetition Structure (Loop)

• There are 3 types of loops in C:


• while
• for
• do while
Repetition : while Loop
• Syntax : Similar as in the if statement, the condition
is an expression that can return true or
while (condition) false.
statement;
 As long as the condition is met (the condition
expression is true), the statement inside the while
loop (also called loop body) will get executed.
• When the condition is no longer met (the condition
expression is false), the program will continue on
with the next instruction (the one after the while
false
loop). cond?

• Example: int i = 0;
true
while (i < 5)
{ Loop
printf(“i = %d\n”, i); body
i++;
}
printf(“Done”);
Repetition : while Loop
• In this example :
• (i < 5) is known as loop repetition condition (counter-
controlled) .
• i is the loop counter variable.
• In this case, this loop will keep on looping until the counter variable
is equal to 4. Once i = 5, the loop will terminate.
• The printf() statement will get executed as long as the variable i is
less than 5. Since the variable i is incremented each time the loop is
executed, the loop will stop after the 5th output.
• Output:
i = 0
i = 1
i = 2
i = 3
i = 4
Done
Sum of 10 Integers
#include <stdio.h>
int main()
{
int i, a, sum;
sum = 0; Initialization
i = 0;
while(i < 10) Loop condition
{
printf("Enter a number: ");
scanf("%d", &a);
sum = sum + a;
i++; Increment/decrement
} Loop body
printf("Total is %d\n", sum);
return 0;
}
Repetition : for Loop
• Syntax :
for (expression1; expression2; expression3)
statement;
• expression1: initialize variables including the loop counter variable
• expression2: the loop condition
• expression3: changes the value of loop counter variable after each iteration
(one cycle of the loop)

• Note that each expression is separated by a semicolon (;)


Sum of 10 Integers
#include <stdio.h> Initialization
int main()
{ Loop condition
int i, a, sum;
sum = 0;
for(i = 0; i < 10; i++) Increment/decrement
{
printf("Enter a number: ");
scanf("%d",&a);
sum += a;
}
printf("Total is %d\n", sum); Loop body
return 0;
}
Repetition : for Loop

• Notice that the output is the same as the one for the
while loop example. In fact, the two examples are
exactly equivalent. Using a for loop is just another
way of writing a while loop that uses a controlling
variable.
Repetition : for Loop
• It is also possible to omit one or more of the for loop
expressions. In such a case, we just put the semicolon without
the expression.
#include <stdio.h>
int main()
{
int i, a, sum;
sum = 0;
i = 0;
for(; i < 10; i++)
{
printf("Enter a number: ");
scanf("%d",&a);
sum += a;
}
printf("Total is %d\n", sum);
return 0;
}
Repetition : for Loop
• It is also possible to have multiple
initializations/increment/decrement statements separated by
comma.
#include <stdio.h>
int main()
{
int i, a, sum;
for(i = 0, sum = 0; i < 10; i++)
{
printf("Enter a number: ");
scanf("%d",&a);
sum += a;
}
printf("Total is %d\n", sum);
return 0;
}
Loop Until User Inputs 100
#include <stdio.h>
int main()
{
int a, sum = 0;
printf("Enter a number: ");
scanf("%d",&a);
sum += a;
while(a != 100)
{
printf("Enter a number: ");
scanf("%d",&a);
sum += a;
}
printf("%d",sum);
return 0;
}
Repetition : do while Loop
• Syntax
do
{
statement;
} while(condition);
• A do while loop is pretty much the same as the while loop
except that the condition is checked after the iteration is
complete.
• When there is a do while loop, the statement(s) inside it will be
executed once no matter what. Only after that, the condition
will be checked to decide whether the loop should be executed
again or just continue with the rest of the program.
Repetition : do while Loop
#include <stdio.h>
int main()
{
int a = 0, sum = 0;
do
{
printf("Enter a number: ");
scanf("%d",&a);
sum += a;
}
while(a != 100);
printf("%d",sum);
return 0;
}
Repetition : do while Loop
• Print the digits of an integer number in reverse order. For
example if the input is 45718, your program should
output 81754.
Repetition : do while Loop
• Print the digits of an integer number in reverse order. For
example if the input is 45718, your program should
output 81754.
#include <stdio.h>
int main()
{
int number, digit;
printf(“Enter a number: ");
scanf("%d", &number);
while(number > 0)
{
digit = number % 10;
printf("%d", digit);
number = number / 10;
}
return 0;
}
Repetition : do while Loop
• Sample run 1:
• Enter a number: 2145
• 5412
• Sample run 2:
• Enter a number: 9
•9
• Sample run 3:
• Enter a number: 0

• Sample run 4:
• Enter a number: 8711541
• 1451178
Repetition : do while Loop
• Print the digits of an integer number in reverse order. For
example if the input is 45718, your program should
output 81754.
#include <stdio.h>
int main()
{
int number, digit;
scanf("%d", &number);
do
{
digit = number % 10;
printf("%d", digit);
number = number / 10;
}while(number > 0);
return 0;
}
Infinite Loop
#include <stdio.h>
int main()
{
int i;
for(i = 0; i != 9; i+=2)
printf("i = %d\n", i);
return 0;
}
How many times will the loop iterate?
Infinite Loop
• If somehow the program never goes out of the loop,
the program is said to be stuck in an infinite loop.
• The infinite loop error happens because the condition
expression of the while loop always return a true.
• If an infinite loop occurs, the program would never
terminate and the user would have to terminate the
program by force.
Anything
non-zero

1. for(;;) 1.while(1) 1.do


2. { 2. { 2.{
3. printf("Hello javatpoint"); 3. i++; 3. // body of the loop..
4. printf("i is : 4.}while(1);
4. } %d",i);
5. }
Example
• Calculate the sum of the following series ( and are user
inputs).
Example
• Calculate the sum of the following series ( and are user
inputs).

#include <stdio.h>
int main()
{
int x, m, term = 1, sum = 1;
scanf("%d%d", &x, &m);
for(i=1; i<=m; i++)
{
term = term * x;
sum = sum + term;
}
printf("Sum = %d", sum);
return 0;
}
Example
• Calculate the sum of the following series ( is user input).
Example
• Calculate the sum of the following series ( is user input).
Example
• Calculate the sum of the following series ( is user input).

#include <stdio.h>
int main()
{
int n, i;
double term, sum = 0;
scanf("%d", &n);
for(i=1; i<=n; i++)
{
term = 1.0 / i;
if(i%2 == 0)
sum = sum - term;
else
sum = sum + term;
}
printf("Sum = %lf", sum);
return 0;
}
Selection Inside Loop
• Read a positive integer and determine if it is
a prime number.
• Pseudo-code:
• Read integer and store it in number
• Set flag to 1
• For i = 2 to (number-1)
• If number is divisible by i then
• Set flag to 0
• If flag equals 1, then the number is a prime
number, otherwise not
Selection Inside Loop
• Read a positive integer and determine if it is
a prime number.
#include <stdio.h>
int main()
{
int number, i, flag = 1;
scanf("%d", &number);
for(i=2; i<number; i++)
{
if(number % i == 0)
flag = 0;
}
if(flag == 1)
printf("%d is a prime number",number);
else printf("%d is not a prime number",number);
return 0;
}
Using break Inside Loop
• In the prime number example, we do not need to
continue the loop till the end once the value of flag is set
to zero.
#include <stdio.h>
int main()
{
int number, i, flag = 1;
scanf("%d", &number);
for(i=2; i<number; i++)
{
if(number % i == 0)
{ The break statement makes
flag = 0; the loop terminate
break;
prematurely.
}
}
if(flag == 1)
printf("%d is a prime number",number);
else printf("%d is not a prime number",number);
return 0;
}
Using continue Inside Loop
• Read 10 integers from the user and calculate the sum of the
positive numbers.

#include <stdio.h>
int main()
{
int number, i, sum = 0;

for(i=0; i<10; i++)


{
printf("Enter a number: "); The continue
scanf("%d", &number);
statement forces next
if(number < 0)
continue; iteration of the loop,
sum = sum + number; skipping any remaining
printf("%d is added\n", number); statements in the loop
}
printf("Total = %d",sum);
return 0;
}
Using continue Inside Loop
• Read 10 integers from the user and calculate the sum of the
positive numbers.
Output:
Enter a number: 1
#include <stdio.h> 1 is added
int main() Enter a number: 2
{ 2 is added
int number, i, sum = 0; Enter a number: 3
3 is added
for(i=0; i<10; i++) Enter a number: -4
{ Enter a number: -5
printf("Enter a number: "); Enter a number: 6
scanf("%d", &number); 6 is added
if(number < 0) Enter a number: 7
continue; 7 is added
sum = sum + number; Enter a number: 8
printf("%d is added\n", number); 8 is added
} Enter a number: -9
printf("Total = %d",sum); Enter a number: 10
return 0; 10 is added
} Total = 37
Example: A Travelling Man
• Suppose a man (say, A) stands at (0, 0) and waits for user to give
him the direction and distance to go.
• User may enter N E W S for north, east, west, south, and any value
for distance.
• When user enters 0 as direction, stop and print out the location
where the man stopped
N

W E

S
float x=0, y=0;
char dir;
float mile;
while (1) {
printf("Please input the direction as N,S,E,W (0 to exit): ");
scanf("%c", &dir); fflush(stdin);
if (dir=='0'){ /*stop input, get out of the loop */
break;
}
if (dir!='N' && dir!='S' && dir!='E' && dir!='W') {
printf("Invalid direction, re-enter \n");
continue;
}
printf("Please input the mile in %c direction: ", dir);
scanf ("%f",&mile); fflush(stdin);
if (dir == 'N'){ /*in north, compute the y*/
y+=mile;
} else if (dir == 'E'){ /*in east, compute the x*/
x+=mile;
} else if (dir == 'W'){ /*in west, compute the x*/
x-=mile;
} else if (dir == 'S'){ /*in south, compute the y*/
y-=mile;
}
}
printf("\nCurrent position of A: (%4.2f,%4.2f)\n",x,y); // output
Nested Loop
• What is the output of the following program?

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


{
for (j=1; j<=4; j++)
{
printf("*");
}
printf("\n");
}
Nested Loop
• What is the output of the following program?

Output
for (i=1; i<=5; i++)
{ ****
for (j=1; j<=4; j++) ****
{ ****
printf("*"); ****
****
}
printf("\n");
}
Nested Loop
• What is the output of the following program?

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


{
for (j=1; j<=i; j++)
{
printf("*");
}
printf("\n");
}
Nested Loop
• What is the output of the following program?

Output
for (i=1; i<=5; i++)
{ *
for (j=1; j<=i; j++) **
{ ***
printf("*"); ****
*****
}
printf("\n");
}
Nested Loop
• Write a program that generates the following pattern.

Output

*
++
***
++++
*****
Nested Loop
• Write a program that generates the following pattern.

Output
int i, j;
for(i=1; i<=5; i++) *
{ ++
for(j=1; j<=i; j++) ***
{ ++++
*****
if (i % 2 == 0)
printf("+");
else
printf("*");
}
printf("\n");
}
Nested Loop
• Write a program that generates the following pattern.

Output
int i, j;
for(i=1; i<=5; i++) *
{ *+
for(j=1; j<=i; j++) *+*
{ *+*+
*+*+*
if (j % 2 == 0)
printf("+");
else
printf("*");
}
printf("\n");
}
Nested Loop
• Write a program that generates the following pattern.

Output

*
**
***
****
*****
Nested Loop
• Write a program that generates the following pattern.

Output
scanf(“%d”, &n); (for n=5)
for(i=1; i<=n; i++)
{ *
for(j=1; j<=n-i; j++) **
printf(" "); ***
****
for(j=1; j<=i; j++)
*****
printf("*");
printf("\n");
}
Practice
1. Calculate the sum of the following series, where is
provided as user input.

2. Write a program that calculates the factorial of a positive


integer n provided as user input.
3. Write a program that calculates , where and are
provided as user inputs.
4. Calculate the sum of the following series, where and is
provided as user input.
Practice
5. Write programs that generate the following patterns. In
each case, the number of lines is the input.
***** * *********
**** *** *******
*** ***** *****
** ******* ***
* ********* *

********** * *
**** **** * * **
*** *** * * ***
** ** * * ****
* * * * *****
** ** * * ****
*** *** * * ***
**** **** * * **
********** * *

You might also like