Introduction to Programming
Some Puzzle Pieces
Random Numbers
With these, your program can do something different each time!
Don't forget the new include lines!
Can you figure out how that complicated formula works?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char *argv[])
{
int maximum = 100;
int minimum = 1;
int my_num;
srand(time(NULL));
my_num = (rand() % (maximum-minimum+1)) + minimum;
printf("My number is %d\n", my_num);
return 0;
}
User Input
How to get a number from the person using your program
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char user_input[128];
int user_num;
printf("Type in a number: ");
fgets(user_input, 127, stdin);
user_num = atoi(user_input);
printf("You typed in %d\n", user_num);
return 0;
}
While Loops
These are a little simpler than for loops
This loop ends when the variable count_down becomes zero.
#include <stdio.h>
int main(int argc, char *argv[])
{
int count_down = 5;
while (count_down != 0)
{
printf("Counting down: %d\n", count_down);
count_down = count_down - 1;
}
return 0;
}
Bigger or Smaller?
Another example of how to use if statements to control what the program does
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int a, b;
if (argc != 3)
{
printf("I need 2 numbers!\n");
return 1;
}
a = atoi(argv[1]);
b = atoi(argv[2]);
if (a < b)
{
printf("The first number is lower!\n");
}
else if (a > b)
{
printf("The first number is greater!\n");
}
else if (a == b)
{
printf("The two numbers are equal!\n");
}
return 0;
}
Challenge
Can you take these puzzle pieces, and create a number guessing game?
The computer should think up a secret random number, and then the user should get a number of chances to guess the number. Each time the user guesses, the computer will tell him whether his guess is greater than or less than the secret number.