Create a program that asks the user to enter a number from 1 to 50.
Print the statement "Programming is fun" the number of times entered by the user using a for loop.
Print the statement "Spring break is fun" the same number of times using a while loop.© BrainMass Inc. brainmass.com August 18, 2018, 6:12 pm ad1c9bdddf
Please see the attachment <I>loops.c</I> for the complete program.
As usual, we start with the standard empty program:
Since we have to get a number (between 1 and 50) as input from the user, declare an integer <I>n</I>. Now, we have to use two loops (one after the other), and this means we need a <I>loop counter</I> variable (conventionally named <I>i</I>):
int n, i;
Get the input from the user. The problem statement tells us to specify that the number should be between 1 and 50, but nothing is mentioned about actually checking whether this is so. So I have included an if statement for checking whether <I>n</I> is greater than 50, and if so, setting it equal to 50. But I have commented this, in case it is not required. You can either uncomment or delete it.
The general syntax of a for loop is:
for(</I>initialization expression<I>; </I>condition<I>; </I>update expression<I>)
Here, <I>initialization expression</I> is a statement that is executed exactly once just before the loop starts; <I>condition</I> is an expression with true/false (that is, zero or non-zero) value that is evaluated at the start ...
The same task is done using both a for loop and a while loop in C. This illustrates the difference in syntax and the similarity in the functioning of the two loops.