[Courses] C Programming For Absolute Beginners, Lesson 4: Getting Looped
Jacinta Richardson
jarich at perltraining.com.au
Tue Mar 6 07:04:53 UTC 2012
On 06/03/12 13:34, Carla Schroder wrote:
> // loopy, getting looped in C!
>
> #include<stdio.h>
>
> int main ()
> {
> int a = 0;
> int total = 0;
>
> for ( a = 1; a<= 50; a = a + 1 )
> total = total + a;
>
> printf ( "The sum of this loop is %i\n", total );
> return 0;
> }
>
Just a little hint to those who want to do more than one thing in their loop,
for loops often have curly braces around their statements. Without these curly
braces, you can only do one statement (such as our total calculation up there).
I've adjusted the formatting above so that you can see what's going on. So if
you want to have a running total AND calculate the total, just use curly braces:
// loopy, getting looped in C! with more!
#include<stdio.h>
int main ()
{
int a = 0;
int total = 0;
for ( a = 1; a<= 50; a = a + 1 )
{
total = total + a;
printf("My running total is: %i\n", total);
}
printf ( "The sum of this loop is %i\n", total );
return 0;
}
----------------
My running total is: 1
My running total is: 3
My running total is: 6
My running total is: 10
...
My running total is: 1176
My running total is: 1225
My running total is: 1275
The sum of this loop is 1275
In C, if you have just a single statement inside a loop or conditional the curly
braces are optional. In some other languages (like Perl) they're always
required. I recommend using them all the time, as you can get into some vary
confusing situations, where your indentation is suggesting that things are
happening inside the loop or condition, but they aren't really.
J
More information about the Courses
mailing list