Purchase Solution

C Programming - for and while loops

Not what you're looking for?

Ask Custom Question

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.

Purchase this Solution

Solution Summary

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.

Solution Preview

Please see the attachment <I>loops.c</I> for the complete program.

As usual, we start with the standard empty program:

<I>
#include <stdio.h>

int main()
{

return 0;
}
</I>

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>):

<I>
int n, i;
</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:

<I>
for(</I>initialization expression<I>; </I>condition<I>; </I>update expression<I>)
{
</I>body<I>
}
</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 ...

Purchase this Solution


Free BrainMass Quizzes
C# variables and classes

This quiz contains questions about C# classes and variables.

Javscript Basics

Quiz on basics of javascript programming language.

Word 2010: Table of Contents

Ever wondered where a Table of Contents in a Word document comes from? Maybe you need a refresher on the topic? This quiz will remind you of the keywords and options used when working with a T.O.C. in Word 2010.

Basic Networking Questions

This quiz consists of some basic networking questions.

Word 2010: Tables

Have you never worked with Tables in Word 2010? Maybe it has been a while since you have used a Table in Word and you need to brush up on your skills. Several keywords and popular options are discussed as you go through this quiz.