iasteele

 

Ky

Page history last edited by Anonymous 2 yrs ago

 

Ky Kiefer

Mr. Steele

C++ Enrichment

21 April 2007

 

Variable types: variable types are used to identify what type of numbers or characters you are dealing with.  A few of the types are int, float, char.  For example, if you enter "5/3=%i", the answer will be 1.   If you input "5/3=%f", the answer will be 1.66.

 

Printf: printf is what the users see.  For instance, when asking for the users name, you would enter: printf("What is your name?").

 

Scanf: scanf gets input from the user and puts them into variables.  For example, if the user was asked to type in his/her name, and the user entered John. The %s would be John.

 

if/else: 'if' blank is true, the program does something.  The most obvious example was in the Pick A Number game.  The 'if' function let the user know whether to guess higher or lower.  'Else' function makes the program perform something if the input is false.

 

Loops (while and for): there are 3 parts to a 'for' loop: initialization, condition, increment.  Initialization tells where to start, condition tells the computer when to stop counting, and increment tells what to count by.  Loops repeat the program until the condition is achieved or does not fit.  'While' loops continue to loop until the condition is false.  In other words, while it is true.

 

Arrays: a list of a type of variables.  Are used for names or a series of numbers.  Arrays allowed the program to recognize strings (%s).

 

Functions: set of code that performs a specifc command.   It acts as a shortcut almost, but also lets your previous variables to be changed while allowing the function to still be true.

 

Sample Program: Pick A Number

 

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

 

 

void main()

{

     int r = rand() % 100;

     int score = 0;

     int guess = -1;

     char return_key;

 

     srand( (unsigned int)time(0) );

     r = rand() % 100;

 

     while( guess != r )

     {

          printf("Pick a number between 0 and 99: ");

          scanf("%i%c",&guess, &return_key);

          score = score + 1;

          if( guess == r )

          {

               printf("Correct! Your score is %i.", score);

          }

          if( guess > r )

          {

               printf("Wrong. Try Lower.\n");

          }

          if( guess < r)

          {

               printf("Wrong. Try Higher.\n");

          }

     }

 

     while (1);

}

Comments (0)

You don't have permission to comment on this page.