[Courses] C Programming For Absolute Beginners, Lesson 3: Else If, While, Operators
Carla Schroder
carla at bratgrrl.com
Mon Feb 27 22:21:52 UTC 2012
C Programming For Absolute Beginners, Lesson 3: Else If, While, Operators
Thanks everyone who shared their homework! There is always more than one way
to do things, and multiple examples make better learning.
Let's review a few things from Lesson 2. It is important to understand data
types so that we use them correctly, and understand why our programs behave
the way that they do when we make mistakes. Read these articles if you need a
refresher:
Primitive data types, Wikipedia
http://en.wikipedia.org/wiki/Primitive_data_type#Numeric_data_type_ranges
C Data Types
http://cprogramminglanguage.net/c-data-types.aspx
data types, Wikipedia
http://en.wikipedia.org/wiki/C_data_types
==================
Femke Snelting gave an interesting example of what happens with incorrect
input:
#include <stdio.h>
int main()
{
int a, b, c;
puts( "Please enter any number up to three digits:" );
scanf( "%d", &a );
printf( "You entered %d. Now enter another number up to three digits:\n",
a );
scanf( "%d", &b );
c = a + b;
printf("%d + %d = %d\n", a, b, c);
return 0;
}
===
The output:
===
Please enter any number up to three digits:
no thanks
You entered -1216996267. Now enter another number up to three digits:
-1216996267 + 134513929 = -1082482338
===
> Why does the program not wait for the second user-input when the first is of
the wrong type?
How does the program decide 'b' is 134513929 (it is always the same)?
Kathryn Hogg explains: "The secret is in the man page under scanf. In the
return value section it says that scanf returns an int whose value is the
number of items successfully matched and assigned.
> How does the program decide 'b' is 134513929 (it is always the same)?
"When you declared "int a, b, c;" you didn't assign them any values so
C says their values are "undefined". They can be anything so never rely
on uninitialized variables having a particular value.
"I'm pedantic so I recommend always explicitly initializing variables:
"int a = 0, b = 0, c = 0;"
========================
This is easy to see in action:
// wronginput, experimenting with errors
#include <stdio.h>
int main()
{
int a=0, b=0, c=0;
puts( "Please enter any number up to three digits:" );
scanf( "%d", &a );
printf( "You entered %d. Now enter another number up to three digits:\n",
a );
scanf( "%d", &b );
c = a + b;
printf("%d + %d = %d\n", a, b, c);
return 0;
}
$ wronginput
Please enter any number up to three digits:
no thanks
You entered 0. Now enter another number up to three digits:
0 + 0 = 0
==========================
It is no longer random.
Some terminology: 'int a' is declaring a variable, and 'int a=0' is
initializing a variable.
Now let's have a little else-if fun. This is a simple example of programming
different responses for different user input:
==========
// howold1, demonstrating multiple possible responses
// depending on what the user inputs
#include <stdio.h>
int main()
{
int age=0;
printf( "Please enter your age: " );
scanf( "%d", &age );
printf("OK, you say you are %d years old. ", age);
if ( age > 200 ){
printf ("I'm sorry, but you need to enter a smaller number. I just can't
believe you're over 200 years old. Unless you are a sturgeon or a Joshua tree.
\n" );
}
else if ( age < 100 ) {
printf ("You are pretty young!\n" );
}
else if ( age == 100 ) {
printf( "Hey, you're just getting warmed up.\n");
}
else {
printf( "You are really old, lol creaky old geezer!\n" );
}
return 0;
}
===========
This little program asks one question, accepts one answer, and then prints a
reply based on your answer:
$ howold1
Please enter your age: 555
OK, you say you are 555 years old. I'm sorry, but you need to enter a smaller
number. I just can't believe you're over 200 years old. Unless you are a
sturgeon or a Joshua tree.
$ howold1
Please enter your age: 100
OK, you say you are 100 years old. Hey, you're just getting warmed up.
$ howold1
Please enter your age: 105
Wow, you are 105 years old. You are really old, lol creaky old geezer!
This is a conditional expression, and if you look at real-life source code
you'll see that it is used a lot. The flow is simple:
if (condition 1 is met)
then statement 1;
else if (condition 2 is met)
then statement 2;
else (the default response for any other condition)
then statement 3;
You can stack up the else-if conditions as high as you like. Start with an
'if' statement, load up on 'else if', and always end with a final 'else'.
Though of course there are better ways to handle more complex scenarios which
we will get to in this course.
ASSIGNMENT OPERATORS
Our little howold1 program illustrates nicely the difference between = and ==.
== is a relational operator, and it means "equal to." = is an assignment
operator, and it means "assign this value to this variable." If you change
'else if ( age == 100 )' to 'else if ( age = 100 )' you will get different
results:
$ howold1
Please enter your age: 110
OK, you say you are 110 years old. Hey, you're just getting warmed up.
You'll never reach the final 'else' condition which is supposed to handle the
values from 101 to 200, because 'else if ( age = 100 )' does not mean 'test
to see if the user input equals 100.' It means 'the value of age is 100',
which is not a conditional test.
Our little howold1 program has to be restarted for the user to get another
chance at entering correct input. How can we write it so the program does not
exit after a wrong answer? Let's try a simple 'while' statement:
// howold2, using a 'while' statement to
// keep the program from exiting until the
// user enters the correct input
#include <stdio.h>
int main()
{
int age=0;
printf( "Please enter your age: " );
scanf( "%d", &age );
printf("OK, you say you are %d years old. ", age);
while ( age > 200 ){
printf ( "I'm sorry, but you need to enter a smaller number. I just can't
believe you're over 200 years old. Unless you are a sturgeon or a Joshua tree.
\n");
scanf( "%d", &age );
printf("Now you say you are %d years old. ", age);
}
if ( age < 100 ) {
printf( "Looks like you have a few good years left.\n" );
}
else if ( age == 100 ) {
printf( "That is a nice even number.\n" );
}
else {
printf( "Hey, you're just getting warmed up.\n");
}
return 0;
}
You should see output like this:
$ howold2
Please enter your age: 333
OK, you say you are 333 years old. I'm sorry, but you need to enter a smaller
number. I just can't believe you're over 200 years old. Unless you are a
sturgeon or a Joshua tree.
99
Now you say you are 99 years old. Looks like you have a few good years left.
$ howold2
Please enter your age: 19
OK, you say you are 19 years old. Looks like you have a few good years left.
$ howold2
Please enter your age: 100
OK, you say you are 100 years old. That is a nice even number.
'while' is called a loop statement, and a controlled flow statement, and a
repeating if statement. 'while' loops back as long as our conditions are met.
Our little program will not exit as long as we keep entering an age value
higher than 200.
We still are not verifying for numbers instead of letters. But patience,
grasshoppers, for that is yet to come. And anyone that wants to leap ahead and
show some ways to do this is welcome.
When you're writing the output for your own 'else if' statements, be sure to
mix it up so you know exactly which statement is executing. I've seen examples
where they all output "Thank you!" which does not tell you which statement is
executing.
HOMEWORK
Write your own 'howold' variation with three different conditions: how many
socks in your drawer, it's your party and you will...what?, what happens when
the price of gasoline hits various levels...it can be anything you want. Let
your imagination take over. It doesn't have to be complicated, though you're
welcome to make it longer and add whatever flourishes you wish.
If you are not familiar with C operators, please do a bit of research and
learn what they are. Because, as we saw with howold1, they can bite in subtle
ways.
Anyone who feels like discussing other methods of looping or input validation
is welcome to chime in.
Thank you and see you next week!
--
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Carla Schroder
ace Linux nerd
author of Linux Cookbook,
Linux Networking Cookbook,
Book of Audacity
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
More information about the Courses
mailing list