Share
C Programming

Course Outline

Week 1
Week 2
Week 3
Week 4
Week 5

REPETITION AND LOOP STATEMENTS

  • The while statement
  • The for statement
  • Nested loops
  • do-while loop statement and flag-controlled loops

SponsoredAdvertise

Explanation to week content

The While Statement


Branch statements allow you to direct the flow of a program’s execution down one path or another.

The simplest form of looping statement is the while loop. Here’s what the while loop looks like:


while(condition)
{
// ...repeatedly executed as long as condition is true
}


From the above statement, the block of code in the while repeats over and over again until the condition in the while loop is false.


Example


Write a program that takes two numbers and output the minimum and maximum of the entered numbers. The program should repeat until a user decides to quit the program.


Solution


We will use a char variable to determine if the user want to continue using the program or to exit.

Initially we have to set the variable to a value that will make the loop condition to be true so whatever code we put in the loop will be executed. After the code is executed we ask the user to enter a character that we specify which will make the loop condition to be false to exit the loop or any other letter that will make the loop condition true, for another execution of the code in the loop.


#include 
#include 
int main()
{
    double num_1, num_2;
    char exit = 'c';
    while(exit !='e'){
        printf("Enter the first number > ");
        scanf("%lf",&num_1);
        printf("Enter the second number > ");
        scanf("%lf",&num_2);
        if(num_1>num_2){
            printf("Minimum: %.2f Maximum: %.2f",num_2,num_1);
        }else{
            printf("Minimum: %.2f Maximum: %.2f",num_1,num_2);
        }
        printf("\nEnter e to exit or any other letter to continue the program > ");
        scanf("%s",&exit);
    }
    return 0;
}


NOTE:


The character to determine whether to exit the program or run the code again is taken before the loop ending curly bracket. In other words is in the loop.

You should also note that the placeholder for the character in the scanf this time is %s and not %c. %c will not work in this case so always remember this.


Write a program that prints out the numbers from 1 to 10 in

i) Horizontal

ii) Vertical


Solution


#include 
#include 

int main()
{
    printf("i. In Horizontal\n");
    int num = 1;
    while(num <= 10){
        printf("%d ",num);
        num ++;
    }
    printf("\nii. In Vertical\n");
    num = 1;
    while(num <= 10){
        printf("%d\n",num);
        num ++;
    }
    return 0;
}


The while loop will keep on repeating so far as the condition num<=10 is true. num needs to be initialized to make the condition true in order for the block of code in the while loop to start execution. The repetition ends when num<=10 is false. Thus when num is more than 10. num++; increases the num variable anytime that line of code is executed. num++; is the same as num = num+1;


Detail Explanation


Repetition Value of i Condition Boolean Loop Status
0 num = 1 1 <= 10 True While loop continues
1 num++; num = 2 
same as num = 1+1
2 <= 10 True While loop continues
2 num++; num = 3 
same as num = 2+1
3 <=10 True While loop continues
3 num++; num = 4
same as num = 3+1
4 <=10 True While loop continues
4 num++; num = 5
same as num = 4+1
5 <=10 True While loop continues
5 num++; num = 6
same as num = 5+1
6 <=10 True While loop continues
6 num++; num = 7
same as num = 6+1
7 <=10 True While loop continues
7 num++; num = 8
same as num = 7+1
8 <=10 True While loop continues
8 num++; num = 9
same as num = 8+1
9 <=10 True While loop continues
9 num++; num = 10
same as num = 9+1
10 <=10 True While loop continues
10 num++; num = 11
same as num = 10+1
11 <=10 False While loop then ends


In summary while loop is written in the form below:

//initialize the loop control variable(s). The expression must be true to start the loop.

while (expression)

{

.

.

.

//update the loop control variable(s). This will make the expression to be false at a point in time.

.

.

.

}


NOTE: 


If your loop control variable(s) update doesn’t make the expression false at certain point in time, you will end up with an endless loop.


The Do … while statement


A separate, less frequently used version of the while loop known as the do … while appears identical except the condition isn’t tested until the bottom of the loop:


do
{
// ...the inside of the loop
} while (condition);


Because the condition isn’t tested until the end, the body of the do … while is always executed at least once. Thus since the condition is tested at the bottom, the block of code in the do{} is run at least once before the condition is tested. If the condition is true, the loop continues and if not it is not repeated.

 

Example


#include 
#include 

int main()
{
  int a = 2;
  int e = 10;
  do{
    printf("%d\n",a);
    a = e-a;
  }while(a>3);

    return 0;
}


The syntax in the do{} will run even though a which is 2 is less than 3. This is because the condition is only tested at the bottom.


The above code is therefore not the same as the while loop with the same syntax.


#include 
#include 

int main()
{
  int a = 2;
  int e = 10;
  while(a>3){
    printf("%d\n",a);
    a = e-a;
  }

    return 0;
}


The above code will not output anything because the condition is tested at the top. a which is 2 is less than 3 and so the condition is false, therefore the syntax in the while loop won’t be executed.

 

A do...while loop can be used for input validation. Suppose that a program prompts a user to enter a test score, which must be greater than or equal to 0 and less than or equal to 100.If the user enters a score less than 0 or greater than 100, the user should be prompted to re-enter the score. The following do...while loop can be used to accomplish this objective:


#include 
#include 

int main()
{
    double score;
    do
    {
        printf("Enter a score between 0 and 100: ");
        scanf("%lf",&score);
    }
    while (score < 0 || score > 100);
    
    if(score>=80){
        printf("%.2f percent is a grade A",score);
    }else if(score>=75){
        printf("%.2f percent is a grade B+",score);
    }else if(score>=70){
        printf("%.2f percent is a grade B",score);
    }else if(score>=65){
        printf("%.2f percent is a grade C+",score);
    }else if(score>=60){
        printf("%.2f percent is a grade C",score);
    }else if(score>=55){
        printf("%.2f percent is a grade D+",score);
    }else if(score>=50){
        printf("%.2f percent is a grade D",score);
    }else{
        printf("%.2f percent is a grade E",score);
    }

    return 0;
}


In the above code, the score input is continually taken until the user enters the correct input. The do while loop is used to achieve that.


The for statement

 

The most common form of loop is the for loop. The for loop is preferred over the more basic while loop because it’s generally easier to read (there’s really no other advantage).


The for loop has the following format:

 

declare the loop control variable;


for (initialization; conditional; increment or decrement)
{
// ...body of the loop
}


The for loop is equivalent to the following while loop:

declare the loop control variable;


initialization;
while(conditional)
{
// ...body of the loop
increment or decrement;
}


Examples

 

Write a program that takes an integerfrom the user and output the multiplication table for that user. For instanceif a user enters 2, the output should look something like this:

 

1 x 2 = 2

2 x 2 = 4

3 x 2 = 6

4 x 2 = 8

5 x 2 = 10

6 x 2 = 12

7 x 2 = 14

8 x 2 = 16

9 x 2 = 18

10 x 2 = 20

11 x 2 = 22

12 x 2 = 24


Solution


#include 
#include 

int main()
{
    int multiples;
    int i;
    printf("Enter a number to print out the multiples > ");
    scanf("%d",&multiples);
    for(i=1;i<=12;i++){
        printf("%d x %d = %d\n",i,multiples,i*multiples);
    }

    return 0;
}


Declaration of the control variable

int i;

Initialization

i= 1

Condition

i<=12


Increment or decrement

Itis increment because i will start from 1 to 12

Thus i++


Write a program which ask the user toenter the current year

i) Prints out years starting from the current year to the past 100th year.

ii) Prints out years starting from the past 100th year to the current year.


Solution


#include 
#include 

int main()
{
    int year;
    int i;
    printf("Enter the current year > ");
    scanf("%d",&year);
    printf("The last 100 years\n");
    for(i=year;i>=year-100;i--){
        printf("%d\n",i);
    }

    return 0;
}


i.  Prints out years starting from the 100th year to the current year.


#include 
#include 

int main()
{
    int year;
    int i;
    printf("Enter the current year > ");
    scanf("%d",&year);
    printf("The last 100 years\n");
    int start = year-100;
    for(i=start;i<=year;i++){
        printf("%d\n",i);
    }

    return 0;
}


ASSIGNMENT


1.

.

Write a program which ask a user to enter 1 to calculate the force of a body 2 to calculate the work done by a body. When the option is entered, the program should ask the necessary information and compute and show the result. When the program finishes, the user should be given an option to enter a letter to exit the program or any other letter to continue the program.


Design:


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

  FORCE & WORK DONE CALCULATOR

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


1. Calculate Force of a body

2. Calculate Work Done

1

Enter the mass of the body > 24.5

Enter the acceleration due to gravity > 9.8

The force of a body of mass 24.500000Kg and acceleration due to gravity of 9.800000 m/second square is 240.100000N

Enter e to exit or any other letter to continue > c

1. Calculate Force of a body

2. Calculate Work Done

2

Enter the mass of the body > 20.5

Enter the acceleration due to gravity > 9.8

Enter the distance moved > 4.2

The work done on a body of mass 20.500000Kg and acceleration due to gravity of 9.800000 m/second square at a distance of 4.200000m is 843.780000J

Enter e to exit or any other letter to continue > e


Formula:

force = mass x acceleration due to gravity

work done = force x distance;


2.


Write a program which ask a student to enter the score. The student should be alerted the gift to be given by the teacher base on the score. The gift table is shown below:


90 - 100 Laptop
80 - 89 iPhone
70 - 79 Mouse
60 - 69 Pen Drive
Below 60 Nothing


When the program finishes, the user should be given an option to enter a letter to exit the program or any other letter to continue the program.


Design


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

  GIFT FROM THE LECTURER

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

Enter your score > 65.5

Gift: Pen drive

Enter e to exit or any other letter to continue > c

Enter your score > 89.999

Gift: iPhone

Enter e to exit or any other letter to continue > c

Enter your score > 59

You are not qualified for any gift

Enter e to exit or any other letter to continue > e

SponsoredAdvertise

Kuulchat Premium