(You can see Part 2 of the tutorial here: while loop tutorial – Part 2)


Some more simple programs using while loop in C. Pls refer to the pictures above.

Q.1. Write a program to display Jai Sriman Narayana 5 times.

Answer.
// Program to display Jai Sriman Narayana 5 times

#include <stdio.h>
int main()
{
int i = 1; //initialisation of the loop counter

while (i <= 5) //condition
{
printf("Jai Sriman Narayana\n"); //display Jai Sriman Narayana
i++; //increment the loop counter
}
printf("Thank you!\n");
return 0;

}

output:
Jai Sriman Narayana
Jai Sriman Narayana
Jai Sriman Narayana
Jai Sriman Narayana
Jai Sriman Narayana
Thank you!


Q.2. What will the following code fragment output?
int k = 1;
while (k < 5)
{
printf("Jai Sriman Narayana\n");
k++;
}
printf("Thank you!\n");
Answer

Output:

Jai Sriman Narayana
Jai Sriman Narayana
Jai Sriman Narayana
Jai Sriman Narayana
Thank you!
Explanation

Initially, the value of k is 1.

The loop condition is k < 5.

Value of kCondition (k < 5)Action
1TruePrint “Jai Sriman Narayana”
2TruePrint “Jai Sriman Narayana”
3TruePrint “Jai Sriman Narayana”
4TruePrint “Jai Sriman Narayana”
5FalseExit the loop

Therefore, “Jai Sriman Narayana” is printed 4 times.

After exiting the loop, the statement

printf("Thank you!\n");

is executed, so “Thank you!” is printed.


Q.3. What will the following code fragment produce?
int k = 1;
while (k < 5)
{
printf("Have a nice day\n");
k += 2;
}
printf("Thank you!\n");

Answer.
Output:

Have a nice day
Have a nice day
Thank you!

Explanation:
Value of kCondition (k < 5)Action
1True (1 is < 5)Print Have a nice day once
3True (3 is < 5)Print Have a nice day once
5False (5 is not < 5)Exit the loop

Hence, “Have a nice day” is printed 2 times.

(Note that the value of k increases by 2 in each iteration of the loop.)


Q.4. What will be the output –
int i = 4;
while (i < 12)
{
printf("Namaste!\n");
printf("Have a good day\n");
i += 3;
}
printf("Here now!\n");

Answer:
Output –

Namaste!
Have a good day
Namaste!
Have a good day
Namaste!
Have a good day
Here now!

Explanation
Value of iCondition (i < 12)Action
4True (4 is < 12)Print Namaste!, print Have a good day
7True (7 is < 12)Print Namaste!, print Have a good day
10True (10 is < 12)Print Namaste!, print Have a good day
13False (13 is not < 12)Exit the loop

Note: The value of i starts at 4, and increases by 3 in each iteration of the loop.


In this lesson, we played around with various aspects of the while loop, such as the initial value of the loop counter, the loop condition, and the increment value. We saw how our output changes when we change these things.

Posted in

One response to “while loop tutorial – Part 3. Learn C Programming easily”

  1. […] while loop tutorial – Part 3. Learn C Programming easily […]

    Like

Leave a comment

Is this your new site? Log in to activate admin features and dismiss this message
Log In