Beginner's C: While Loops for Data Input

  • Thread starter SN1987a
  • Start date
In summary: The conditional checks to see if c is equal to 'x'; if it is, the loop ends and the user is prompted for the next data point. If c is anything else, the while loop keeps going.
  • #1
SN1987a
35
0
Hi guys, I'm really new to computer programming, and I've been sortof thrown into it without much introduction. This is a short C program I have to write for one of my physics courses.

To biggin with, the program has to prompt the user for a bunch of real numbers, which are to be stored in an array and to be used for computations later. My problem is at the very beginning. I'm thinking of using scanf to read the input and assigning it to a slot in the array. I would do something like this:

int i;
float data[10];
for(i=0;i<10;++i)
scanf("%f", &data);

This seems to work, but for some reason, my professor asks me to use a while loop here. Why and most importantly how would I get a while loop to do the job?

I'm not even sure I understand how a while loop works. So we have that while certain codition is satisfied, then something happens (or there can be multiple possibilities with if/else statements). But I don't see how a while loop can help with gathering a bunch of data and dumping it into an array.

I really need help to get started on this. I'm pretty cofused about C, and most importantly I think, I know very little syntax.
 
Technology news on Phys.org
  • #2
A for loop like yours can be turned into a while loop:

int i = 0;
while (i < 10) {
...
i = i + 1;
}

Why your teacher wants you to use a while loop, I don't know -- it seems like the for loop is the obvious choice, as it simplifies the code.

- Warren
 
  • #3
In fact, a for-loop can always be rearranged into a while-loop and vice versa. This generic for-loop:

Code:
for (initialize; comparison; update)
{
     body;
}

is almost completely equivalent to the following while-loop:

Code:
initialize;
while (condition)
{
     body;
     update;
}

The only way in which they are not equivalent is that if "initialize" declares a variable (e.g.
Code:
int k = 0
), then with the for-loop the variable is available only inside the loop, whereas with the while-loop the variable is also available everywhere after the loop until the end of the current function.

The main reason the two different forms exist is that most programmers find one idiom to be more "natural" than the other in certain situations. I also consider the for-loop to be more natural for dealing with arrays. The only legitimate reason I can think of, why your instructor insists on a while-loop, is that he wants you to get some practice with while-loops.
 
  • #4
Thanks guys, I think i get the idea of a while loop, but somehow the details still need a lot of improvement :redface:

This is the while loop i wrote

while((c=getchar()),c!='x'&&i<10)
{ printf("datapoint %d:", i+1);
scanf("%f", &point);
data=point;
i=i+1;
}

This is meant to
1. stop the loop either when the user is done and he imputs 'x', as he was instructed to previously, or when i hits ten, because my array only has 10 slots
2.prompt the user for the ith data point
3.get the number inputed and assign it to the variable point
4.assign the value of point to the ith spot in the array
5.update the value of i

Does my while loop look like it should do what i meant it to, or did I miss something?

In fact I know I did miss something, but don't know why. I tested this, and it goes wrong in two places
1. it wants a line of input before displaying the "datapoint 1" prompt; whatever i input there just disappears into thin air, it's not permanently stored anywhere because after the while loop i print all the variables and whatever i input on that line doesn't show up anywhere
2. if i don't put in the right type of stuff (ie real numbers), it acts funny; eg: i type in 2 letters, it jumps two "datapoint" prompts; this is what it actually looks like

1
datapoint 1:3.5
datapoint 2:7.3434
datapoint 3:0.00005
datapoint 4:a
datapoint 5:ff
datapoint 6:datapoint 7:What's wrong with my loop?
 
Last edited:
  • #5
Suggestion: do not, ever, write while loops with conditions like that. Don't put statements -- lines of code that modify variables -- in conditional expressions.

Such code is said to have "side-effects." Consider this piece of code:

if ( (c = getchar()) == 'x' ) { ... }

This condition does not just return true or false if the next character is an 'x'; it also modifies the value of c, and the standard input stream's marker.

This kind of code, while syntactically correct, is a nightmare to debug.

Put only conditionals (which don't change any variables' values) in the conditional of your while loop.

Try writing it this way:

int i = 0;
while(i<10)
{
printf("datapoint %d:", i+1);
c=getchar()
if (c == 'x') continue;
scanf("%f", &point);
data=point;
i=i+1;
}

Note how much easier this loop is to understand -- the statements are simply executed in order, and the conditional of the while loop is as simple as can be.

- Warren
 
  • #6
Actually, even better, I'd suggest you also avoid 'continue' and 'break.' These keywords can be very useful at times, but they also promote sloppy code that's hard to debug.

Consider this instead:

Code:
int i = 0;
while(i<10)
{
    printf("datapoint %d:", i+1);
    c=getchar()
    if (c != 'x') {
        scanf("%f", &point);
        data[i]=point;
        i=i+1;
    }
}

- Warren
 
  • #7
Thanks chroot. I didn't realize changing variables inside the while condition was sloppy. In fact, that was an idea i had taken from my class notes, my teacher had used the exact same example :while((x=getchar()), condition) {body}

I think my while loop works now. It puts the right things at the right places. Now I have to do computations with the values in my array. I want to compute the following value (inside a for loop)
vars=vars+pow((data-mean),2) / ndata

Although i included the math.h library and used the "-lm" option when I compile, the compiler still complains that it does not recognize the binary operator / . What does it want?
 
Last edited:
  • #8
You do not need to link in the math library just to do division -- you need it for the pow() operator. Can you copy and paste the compiler's exact error message?

- Warren
 
  • #9
chroot said:
Don't put statements -- lines of code that modify variables -- in conditional expressions.

That's good advice in general, but (as with any "rule") there may be generally-accepted idioms that are exceptions. For example, in C++ it's generally considered good style to write input loops similar to this:

Code:
int x;
while (infile >> x)
{
    // do something with x
}

which reads one int at a time (separated by whitespace) from a file, terminating at the end of file or when it encounters something that isn't an integer.

(I know this thread is about C, but I'm just illustrating a general principle here.)
 
  • #10
jtbell,

That's a good point.

When the behavior of the statement is very well-defined, as in the case of "infile >> x", it may be permissible to use a statement in a conditional. (I'm thinking from a zero-defect mindset, in which you can mathematically prove code correctness.) In almost every other case, however, side-effects are to be avoided.

- Warren
 
  • #11
the compiler complains:
t.c: In function `main':
t.c:46: error: invalid operands to binary /

Might this be because I am dividing a float variable by an integer variable?
If this is the case, what should i do?
 
  • #12
oh, well, i fiddled some more with my little program, changed a few things (nothing inside teh while loop) and now it works (still have a float/an integer). But I honestly have no clue what made it work, in my opinion i changed nothing that should have affected that computation...:confused:
 

1. What is a while loop in C?

A while loop in C is a control structure that allows for the repetition of a specific block of code as long as a condition remains true. This condition is typically a logical expression that is evaluated before each iteration of the loop. As long as the condition is true, the code within the loop will continue to execute. Once the condition becomes false, the loop will terminate and execution will move on to the next line of code.

2. How do you use a while loop for data input in C?

To use a while loop for data input in C, you will typically first declare a variable to hold the input data. Then, you will prompt the user for input using the scanf() function and store the input in the variable. Next, you will use a while loop to continuously prompt the user for input and update the variable until a specific condition is met (e.g. the user enters a certain value or the input reaches a certain length).

3. What is the difference between a while loop and a do-while loop in C?

The main difference between a while loop and a do-while loop in C is that a while loop checks the condition before each iteration, while a do-while loop checks the condition after each iteration. This means that a do-while loop will always execute at least once, even if the condition is initially false, while a while loop may never execute if the condition is initially false.

4. Can you give an example of using a while loop for data input in C?

Yes, here is an example of using a while loop for data input in C:

int input;

printf("Enter a number: ");

scanf("%d", &input);

while (input < 10) {

printf("Enter another number: ");

scanf("%d", &input);

}

In this example, the while loop will continue to prompt the user for input until they enter a number that is greater than or equal to 10.

5. What are some common errors to watch out for when using a while loop for data input in C?

One common error when using a while loop for data input in C is forgetting to update the variable that is being used to check the condition. This can result in an infinite loop if the condition always remains true. Another error is not properly handling unexpected input, which can cause the program to crash or behave unexpectedly. It is important to use input validation techniques, such as checking for the correct data type, to prevent these errors.

Similar threads

  • Programming and Computer Science
Replies
4
Views
733
  • Programming and Computer Science
Replies
2
Views
1K
  • Programming and Computer Science
Replies
8
Views
2K
  • Programming and Computer Science
2
Replies
66
Views
4K
  • Programming and Computer Science
Replies
8
Views
1K
  • Programming and Computer Science
Replies
31
Views
2K
  • Programming and Computer Science
Replies
2
Views
977
  • Engineering and Comp Sci Homework Help
Replies
3
Views
503
  • Programming and Computer Science
Replies
17
Views
1K
  • Programming and Computer Science
Replies
2
Views
1K
Back
Top