Getting Input Into Your Programs

Create a project called "Stooges". Create a source file called "Stooges.c" and enter the following program:

 

/* Written by … */

#include <stdio.h>

int main(void) {

int moe, shep, curly;

printf("Enter three integers : ");
scanf ("%i %i %i", &moe, &shep, &curly);
printf("\n\n\t %i %i %i\n\n", curly, shep, moe);

return 0;

}

 

Variables allow you to store and manipulate information in your program. In the C programming language, all variables must be declared before they are used in your program. The declaration tells the compiler what kind of information will be stored in each variable.

 

The declaration

int moe, shep, curly;

tells the computer that the variables called "moe", "shep", and "curly" will be integers. An integer is a whole number from -32768 to 32767. Variable names can be any length, but must begin with a letter. They are also case sensitive … moe is not the same as Moe!!

The "scanf" function reads information from the console window into the specified variables. For example

scanf ("%i %i %i", &moe, &shep, &curly);

reads three integers (this is what each "%i" means) and saves them into the variables moe, shep, and curly. The "&" character is the C programming language's way of telling the computer where the variable is in memory. You only use the "&" when a function changes a value you pass to it. Be careful! Leaving these out or using them when you should not may cause bad things to happen!

The second printf is a little more complicated than what you've seen before:

printf("\n\n\t %i %i %i\n\n", curly, shep, moe);

The string in quotes tells the computer to skip two lines ("\n\n"), then to indent one tab stop ("\t"). Next, three integers will be printed, and two more lines are skipped. Then the variables containing the three integers are listed.

Compile and run this program. Enter three integers, separated by spaces, and press return. What happens? Is this what you expected?

 

Assignment #2

Change this program to ask for four integers. You will need to add an additional stooge. When you print the numbers which were read, print them in the same order they were entered.

 
Intro | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | Project