0% found this document useful (0 votes)
14 views45 pages

2 1 Loops

The document provides an overview of loops in C programming, including while, do-while, for, and nested loops. It explains the syntax and functionality of each loop type, along with examples and common use cases such as break and continue statements. Additionally, it includes programming exercises and problems related to loop implementation.

Uploaded by

rajaraja96547
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)
14 views45 pages

2 1 Loops

The document provides an overview of loops in C programming, including while, do-while, for, and nested loops. It explains the syntax and functionality of each loop type, along with examples and common use cases such as break and continue statements. Additionally, it includes programming exercises and problems related to loop implementation.

Uploaded by

rajaraja96547
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
You are on page 1/ 45

Loops

Programming in C
Today’s Topics

► while and do-while loop


► break, continue, goto statements
► for loop
► Nested loops
while loop

► expression test condition

while(expression)
{

// body of the loop;

S1. First, it will evaluate expression


S2. If it is True, then execute the body of the loop,
and then repeat from S1.
Otherwise, skip the body of the loop.
while loop

How many times printf execute ?


#include<stdio.h>
void main()
{
int i=0;
while(i<=5)
{
printf("%d",i);
}
}
ASCII Value Printing
ASCII code of enter is 10

Output ?
EXAMPLE 1:
#include<stdio.h>
void main()
{
int sum=0;
char ch=’0’;
while(ch!=10)
{
printf("(%c, %d)\n",ch,ch);
scanf("%c",&ch);
}
}

Read line of characters, and print


ASCII value corresponding along
with the character.
ASCII Value Printing
ASCII code of enter is 10
Output ?
Output ? EXAMPLE 2:
EXAMPLE 1: #include<stdio.h>
#include<stdio.h> void main()
void main() {
{ int sum=0;
int sum=0; char ch=’0’;
char ch=’0’; while()
while(ch!=10) {
{ printf("(%c, %d)\n",ch,ch);
printf("(%c, %d)\n",ch,ch); scanf("%c",&ch);
scanf("%c",&ch); }
} }
}
► Output: Error
Read line of characters, and print
ASCII value corresponding along ► Expression is not
with the character. optional in while loop.
Interesting Evaluation

Output ?
#include<stdio.h>
void main()
{
int i=0;
while(i<3, i=0, i<1)
{
printf("Loop ");
i++;
}
}
Interesting Evaluation

Output ? Output ?
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
int i=0; int n,i=0;
while(i<3, i=0, i<1) while(scanf("%d",&n)==1)
{ {
printf("Loop "); printf("END\n");
i++; if(n==0) break;
} }
} }

Infinite Loop
The break and continue Statements
break
• Causes immediate exit from a while, for, do/while or
switch structure
• Program execution continues with the first statement after
the structure
Common uses of the break statement
• Escape early from a loop
• Skip the remainder of a switch structure
The break and continue Statements

Continue
Skips the remaining statements in the body of a while,
for or do/while structure
Proceeds with the next iteration of the loop
while and do/while
Loop-continuation test is evaluated immediately after the
continue statement is executed
for
Increment expression is executed, then the loop-continuation test
is evaluated
Interesting Evaluation

How many times printf will execute ?


#include<stdio.h>
void main()
{
int i=4, j=7;
while(++i < --j)
printf("Loop");
}
Interesting Evaluation

Write a program to test a


given number is
Armstrong or not ?.

Armstrong number: Sum


of cubes of each digit of
the number is equal to
number itself (e.g.,
153 = 13 + 53 + 33 )
Interesting Evaluation

Armstrong Number
#include<stdio.h>
#include<math.h>
Write a program to test a void main()
given number is {
Armstrong or not ?. int n, sum=0, temp;
scanf("%d",&n);
temp=n;
Armstrong number: Sum while(temp !=0)
of cubes of each digit of {
sum = sum + pow((temp%10),3);
the number is equal to temp = temp/10;
number itself (e.g., }
153 = 13 + 53 + 33 ) if(n == sum)
printf("Armstrong Number");
else
printf("Not Armstrong Number");
}
while loop - Example

► while loop:

Write a program to print


sum of numbers
presented in the given line
of text.

Input: a12wse4gf320rd
Output: 12 + 4 + 320 =
336
do-while loop

► expression test condition

do
{

// body of the loop;

}while(expression); //semicolon

S1. First, execute the body of the loop


S2. Then, it will evaluate expression
S3. If it is True, then repeat from S1.

Otherwise, skip the body of the


loop.
A good example of when a do-while loop is more motivating than a while loop is
when you want to create a menu-driven program that allows the user to perform an
action at least once and then continue as long as they choose to continue.

do {
printf("Welcome to the Menu:\n");
printf("1. Option 1\n");
printf("2. Option 2\n");
printf("3. Quit\n");
printf("Enter your choice: ");
scanf(" %c", &choice);

switch (choice) {
case '1':
printf("You selected Option 1.\n");
break;
case '2':
printf("You selected Option 2.\n");
break;
case '3':
printf("Goodbye!\n");
break;
default:
printf("Invalid choice. Please try again.\n");
}
} while (choice != '3');
goto statement

goto myLabel;
........

myLabel:
statements;

► Must be defined within a function


► Each label in one function must have a
unique name. It cannot be a reserved C
word.

► You can use the same name for a


variable and a label.
► When the code reaches the goto
statement, the control of the program
”jumps” to the label. Then the execution
continues normally.
while using goto statement

#include <stdio.h>

int main() {
int i = 0;

start:
if (i < 5) {
printf("%d ", i);
i++;
goto start; // Jump back to the 'start' label
}

return 0;
}
► for loop
► nested for loop
for loop

for( expression-1; expression-2; expression-3)


{

// body of for loop;

► expression-1 initialize counter


► expression-2 test condition
► expression-3 re-evaluation
for loop
How many times printf execute ?
#include<stdio.h>
void main()
{
int i;
for(i=0; i<5; i++)
{
printf("%d",i);
}
}
Various forms of for loop
for(; ;) // no argument (infinite)

for(i=0; i<=5; ) // i not inc/decrement (infinite)

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


printf("%d",i);

for(i=8; i>=0; i--)


for loop
Write a program to print first five natural numbers starting from 1
together with their squares.
Program
#include<stdio.h>
void main()
{
int i;
for(i=1; i<=5; i++)
printf("num: %5d square: %8d\n", i, i*i);
}
27

Loop repetition types


• Counter-controlled repetition
– Definite repetition: know how many
times loop will execute int counter = 1;
while ( counter <= 10 ) {
– Control variable used to count printf( "%d\n", counter );
repetitions ++counter;
}

• Sentinel-controlled repetition
– Indefinite repetition
– Used when number of repetitions not
known
– Sentinel value indicates "end of data"
© 2000 Prentice H
28

Sentinel controlled repetition


#include <stdio.h>

int main() {
int num, sum = 0;

printf("Enter a series of numbers, and enter -1 to


calculate the sum: \n");
while (1) {
printf("Enter a number (or -1 to calculate the sum):
");
scanf("%d", &num);
if (num == -1) {
break; // Exit the loop when -1 is entered
}
sum += num;
}
printf("The sum of the numbers entered is: %d\n", sum);

return 0;
}
© 2000 Prentice H
Terminate the program in our choice
What this program will do ?
#include<stdio.h>
int main()
{
char ch; int i;
printf("Enter the sequence of characters\n");
scanf("%c",&ch);
for( ;ch!=’e’&&ch!=’E’; )
{
switch(ch<=’9’ && ch>=’0’)
{
case 1: printf("%c",ch);
scanf("%c",&ch);
break;
case 0: scanf("%c",&ch);
break;
}
}
}
Nested loops
What this program will do ?
#include<stdio.h>
int main()
{
int i,j;
for(i=0;i<=3;i++)
{
for(j=0;j<=4;j++)
printf("%d",j);
printf("\n");
}
}

Visualize code
Nested while loop
#include <stdio.h>

int main() {
int i = 0;
while (i <= 3) {
int j = 0;
while (j <= 4) {
printf("%d", j);
j++;
}
printf("\n");
i++;
}
return 0;
}
• Loops can be nested multiple times.
• Any combination of loops like for, while, and do while
can be nested together.
Printing pyramid 1
#include <stdio.h>

int main() {
int rows, i, j;

printf("Enter the number of rows for


the pyramid: ");
scanf("%d", &rows);

for (i = 1; i <= rows; i++) {


// Print asterisks
for (j = 1; j <= i; j++) {
printf("* ");
}

// Move to the next line


printf("\n");
}

return 0;
}
Printing pyramid 2
#include <stdio.h>

int main() {
int rows, i, j;

printf("Enter the number of rows for the pyramid: ");


scanf("%d", &rows);

for (i = 1; i <= rows; i++) {


// Print asterisks
for (j = 1; j <= rows - i; j++)
printf(" ");
for (j = 1; j <= i; j++) {
printf("* ");
}

// Move to the next line


printf("\n");
}

return 0;
}
Pyramid Printing – Another logic

#include<stdio.h>
void main()
{
int i,j,k,n;
printf("Enter a number: ");
scanf("%d",&n);
k=2*n-2;
for(i=0;i<n;i++)
{
for(j=0;j<k;j++)
printf(" ");
k=k-1;
for(j=0;j<=i;j++)
printf("* ");
printf("\n");
}
}
Homework
Pyramid Printing
Problems
• Write a program to read a number and find the sum of its
individual digits repeatedly till the result is a single digit.

• Write a program to read a number and find the


frequency of a given digit in that number.
• Print the following pyramid pattern:
Problems
• Print Pascals triangle

• Read a number and print its reverse


• Write a program to count digits, white space characters, and
other characters from the given input ?
• Write a C program that accepts input from the keyboard and counts the positive,
negative integers and zero until * is entered.
• Write a C program to calculate and print xn.
• Write a C program to print the sum of ‘n’ numbers.
• Write a C program to print the factorial of a number.
• Write a C program to print all the even and odd numbers of a certain range as
indicated by the user and find their respective sum.
• Write a C program to print the binary equivalent of an integer.
• Write a C program to print the prime factors of a number.
• Write a C program to check whether a number is a power of 2 or not.
• Write a C program to print the GCD of two numbers.
• Write a C program to print the prime numbers in a given range.
• Write a C program to print the sum of the series: 1 + x + x2 /2! + x3 / 3! +…
• Write a C program to print the sum of the series: x - x3/ 3! + x5 / 5! - ….
• Write a C program to generate calendar of a month, given the start day of the
week and the number of days in that month.
• Write a C program to print the multiplication table up to ‘n’ numbers.
Predict the output of the following programs
for loop
Output of the below program:
Program
#include<stdio.h>
void main()
{
int i;
for(i=1;i<=10;i++)
printf("%5d",i);
printf("\n");
for( ;i-- > 1; )
printf("%5d",i);
}
for loop
Output of the below program:
Program
#include<stdio.h>
void main()
{
int i;
for(i=1;i<=10;i++)
printf("%5d",i);
printf("\n");
for( ;--i > 1;)
printf("%5d",i);
}
for loop
Output of the below program:
Program
#include<stdio.h>
void main()
{
int i=5, j=5;
for( ; ;(i++, j--))
{
printf("%5d %5d\n",i,j);
if(j==0)
break;
}
}

You might also like