Beginner's C question

  • Thread starter SN1987a
  • Start date
  • #1
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.
 

Answers and Replies

  • #2
chroot
Staff Emeritus
Science Advisor
Gold Member
10,226
34
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
jtbell
Mentor
15,640
3,688
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
35
0
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
chroot
Staff Emeritus
Science Advisor
Gold Member
10,226
34
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
chroot
Staff Emeritus
Science Advisor
Gold Member
10,226
34
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
35
0
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
chroot
Staff Emeritus
Science Advisor
Gold Member
10,226
34
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
jtbell
Mentor
15,640
3,688
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
chroot
Staff Emeritus
Science Advisor
Gold Member
10,226
34
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
35
0
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
35
0
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:
 

Related Threads on Beginner's C question

  • Last Post
Replies
10
Views
2K
  • Last Post
Replies
17
Views
222
  • Last Post
Replies
1
Views
773
  • Last Post
Replies
2
Views
2K
  • Last Post
Replies
2
Views
2K
  • Last Post
Replies
12
Views
102K
Replies
169
Views
221K
Replies
4
Views
3K
Replies
5
Views
4K
Replies
10
Views
2K
Top