Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

LAB # 13

To Understand the Control Structure Using WHILE and DO


WHILE Loop
Objective

This lab demonstrates when to use which loop.

The While Loop


The ‘for’ loop does something a fixed number of times. But in a case where you don’t know how
many times you want to do something before you start the loop, you use a different loop: the
while loop. Here is the syntax template for the While loop:
SYNTAX:
while (condition_expr)
statement; / Block
Program 1
#include <stdio.h>

int main () {

/* local variable definition */


int a = 10;

/* while loop execution */


while( a < 20 ) {
printf("value of a: %d\n", a);
a++;
}

return 0;
}

Program 2
1. #include<stdio.h>
2. int main(){
3. int i=1,number=0,b=9;
4. printf("Enter a number: ");
5. scanf("%d",&number);
6. while(i<=10){

1
7. printf("%d \n",(number*i));
8. i++;
9. }
return 0;
}

The Do-While Statement


The Do-While statement is a looping control structure in which the loop condition is tested at the
end (bottom) of the loop. This format guarantees that the loop body executes at least once. Here
is the syntax template for the Do-While loop:

SYNTAX:
do
{
statement; / Block
}
while (condition_expr);
Also note that the Do-While ends with a semicolon.

Program 3
This program will execute once, even if the initial value of feet is 0
// Program to add numbers until the user enters zero

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

// the body of the loop is executed at least once


do {
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
}
while(number != 0.0);

printf("Sum = %.2lf",sum);

return 0;
}

2
3
Program 4
#include <stdio.h>

int main ()
{
char size;
printf("Enter the letter on the tag of your shirt [X, L, M, S]:");
scanf("%c",&size);
switch (size)
{
case 'X':
printf("Your shirt's size is Extra Large\n");
break;
case 'L':
printf("Your shirt's size is Large\n");
break;
case 'M':
printf( "Your shirt's size is Medium\n");
break;
case 'S':
printf( "Your shirt's size is Small\n");
break;
default:
printf( "The entered letter is invalid\n");
}
return 0;
}

4
LAB TASK:
Lab Task. 14.1) Write a program to generate a number table of the given value. The user
should be asked for RE-RUN or EXIT the program giving up the following massage; “Do
You Want To Continue (Y/N)”.

Lab Task. 14.2) Write a program to find a factorial using while loop.

Note: Attach with manual every above mentioned task.

You might also like