CS Extra Lab - Practice with ifs and whiles

Create a subdirectory named extra in your 1440 directory. There is nothing to turn in for this lab. It is intended to give you practice on ifs, whiles, comparison, and logical operators. It would be to your benefit to complete as much of this lab as you can.

For each of the following sections of code below, try to figure out what value would be assigned to n and then displayed by the cout statements. Study the code first and jot down what you think is assigned to n. Then copy and paste the whole thing into a file called whatisn1.C. Compile and execute the code and see if your original answer was right. (Remember to put it inside of a main function and have an include for iostream.h.)

int n;

n = 4>3 && 5<7 || 8>6;
cout << n << endl;

n = 4>5 && 5<7 || 8>6;
cout << n << endl;

n = 4>5 && 5<7 || !(8>6);
cout << n << endl;

n = !(3!=4);
cout << n << endl;

n = 3 == 4 || 3 == 3 && 5!=5;
cout << n << endl;
Okay here is another one to play with. Again, try first to figure out what is assigned to n and jot down your answer on a piece of paper. Then save this file into a file called whatisn2.C and compile and execute it to see if your answer is correct.
int a, b, n;

a = 5;
b = 3;
n = b % a;
cout << n << endl;

n = b / a;
cout << n << endl;

n = a % b;
cout << n << endl;

n = b % a;
cout << n << endl;

n = 1;
if (n == 0) n = 7;
cout << n << endl;

n = 1;
if (n = 0) n = 7;
cout << n << endl;
Think about what would be the output of the code below and jot it onto a piece of paper. Next copy the code into a file called while1.C and compile and execute it to see if you are write.
int n;

n = 10;
do 
   n = n + 3;
while (n == 10);
cout << n << endl;
Do the same again for the code below and call the file while2.C.
int n;

n = 10;
while (n == 9) 
   n = n + 3;
cout << n << endl;
Do the same again for the code below and call the file while3.C.
int i, k;

i = 5;
k = 0;
while (i == 5) 
{
   while (k < 5)
   {
      k = k + 2;
      i--;
   }
   i++;
}
cout << i << endl;
cout << k << endl;
Okay, here are some other problems to work on:
  1.  Write a program that will read in integers from the user until the user inputs a 0. At that point the program should tell the user what the number just before the 0 was. If the user inputs a 0 for his first number, the program should print the string "You had no previous number."

  2.  Print the factorials from 1 to 10. Definition of factorial: n! = n*(n-1)*(n-2)*...*(2)*(1)

  3.  Have the user enter 20 numbers from the keyboard and print out the smallest and the largest of the numbers.