// Demonstration of if and if-else conditionals
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
int i;
cout << "Type a number and 'Enter'" << endl;
cin >> i;
if(i > 5)
{cout << "It's greater than 5" << endl;}
else if(i < 5)
{cout << "It's less than 5" << endl;}
else {cout << "It's equal to 5" << endl;}
// More formal:
if(i > 5)
{cout << "It's greater than 5" << endl;}
else // i <= 5
{
if(i < 5) {cout << "It's less than 5" << endl;}
else {cout << "It's equal to 5" << endl;}
}
cout << "Type a number and 'Enter'" << endl;
cin >> i;
if(i < 10)
{
if(i > 5) // "if" is just another statement
{cout << "5 < " << i << " < 10" << endl;}
else {cout << i << " <= 5" << endl;}
}
else // Matches "if(i < 10)"
{cout << i << " >= 10" << endl;}
return 0;
}
/*
g++ Ifthen.cpp -o Ifthen
./Ifthen
Type a number and 'Enter'
1
It's less than 5
It's less than 5
Type a number and 'Enter'
2
2 <= 5
./Ifthen
Type a number and 'Enter'
5
It's equal to 5
It's equal to 5
Type a number and 'Enter'
6
5 < 6 < 10
./Ifthen
Type a number and 'Enter'
7
It's greater than 5
It's greater than 5
Type a number and 'Enter'
10
10 >= 10
*/
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
int secret = 15;
int guess = 0; // initial value needed for the first test within while()
// "!=" is the "not-equal" conditional:
while(guess != secret) // Compound statement, no semicolon here
{
cout << "Guess the number: ";
cin >> guess; // type a number and press Enter, which goes to next line
}
cout << "You guessed it!" << endl; // newline added here
return 0;
}
/*
g++ Guess1.cpp -o Guess1
./Guess1
Guess the number: 0
Guess the number: 12
Guess the number: 15
You guessed it!
*/
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
int secret = 15;
int guess; // No initialization needed here
do
{
cout << "Guess the number: ";
cin >> guess; // Initialization happens here (no newline, press Enter)
// the code is easier to read with this empty line here
} while (guess != secret); // semicolon required here
cout << "You guessed it!" << endl; // newline added here
return 0;
}
/*
g++ Guess2.cpp -o Guess2
./Guess2
Guess the number: 0
Guess the number: 12
Guess the number: 15
You guessed it!
*/
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
#include <iostream>
using std::cout;
using std::endl;
// Display all 256 ASCII characters
int main()
{
for(int i = 0; i < 256; i++)
{
cout << "char(" << i << "): '"
<< char(i) // Type conversion
<< "'" << endl;
}
return 0;
}
/*
g++ Charlist.cpp -o Charlist
./Charlist > out.txt // save result to file
*/
Do not type the comments in the terminal window. For instance, type:
./Charlist > out.txt
Here, `>' redirects the output to a file.
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
Exercose 3-2. Write a program that uses two nested for() loops and the modulus operator (%) to detect and print prime numbers (integral numbers that are not evenly divisible by any other numbers except for themselves and 1).
#include <iostream>
using std::cout;
using std::endl;
#define SIZE 100 // search for (and print) primes within 2..100
int main()
{
int max = SIZE/2; // max no of primes <= SIZE/2 for SIZE > 7
if (SIZE < 2) {return 1;} // end program, signalling error
if (SIZE <= 7) {max++;}
int primes[max]; // prime numbers found
int np = 0; // no of primes found so far
bool isPrime; // true if a number is prime
int half; // check if n is divisible by primes <= n/2 or sqrt(n)
primes[np++] = 2; // smallest and single even prime
for (int n = 3; n <= SIZE; n += 2)// check only odd numbers
{
isPrime = true; // (re)set
half = n / 2;
// we check odd numbers: n % primes[0] != 0
for (int i = 1; i < np && primes[i] <= half; i++)
{ // Test primality by successive division (modulo):
if (n % primes[i] == 0)
{
isPrime = false; // not prime
break; // out of inner for()
}
}
if (isPrime) // if (isPrime == true)
{
primes[np++] = n;
}
}
for (int i = 0; i < np-1; i++)
{
cout << primes[i] << ',' << ((i % 10 == 9) ? '\n' : ' ');
}
cout << primes[np-1] << endl;
return 0;
}
/*
g++ Primes.cpp -o Primes
./Primes
2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97
*/
Change the SIZE if you want to print more or less prime_numbers. Compare against the list_of_primes on Wikipedia.
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
// Simple menu program demonstrating the use of "break" and "continue"
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
char c; // To hold the response (input from keyboard)
while(true) // for ever
{
cout << "MAIN MENU:" << endl;
cout << "l: left, r: right, q: quit -> ";
cin >> c;
if(c == 'q')
{break;} // Out of "while(1)"
// else
if(c == 'l')
{
cout << "LEFT MENU:" << endl;
cout << "Select a or b: ";
cin >> c;
if(c == 'a')
{
cout << "You chose 'a'" << endl;
continue; // Back to main menu, to the next iteration of while()
}
if(c == 'b')
{
cout << "You chose 'b'" << endl;
continue; // Back to main menu
}
else
{
cout << "You didn't choose a or b!" << endl;
continue; // Back to main menu
}
}
// else
if(c == 'r')
{
cout << "RIGHT MENU:" << endl;
cout << "Select c or d: ";
cin >> c;
if(c == 'c')
{
cout << "You chose 'c'" << endl;
continue; // Back to main menu
}
if(c == 'd')
{
cout << "You chose 'd'" << endl;
continue; // Back to main menu
}
else
{
cout << "You didn't choose c or d!" << endl;
continue; // Back to main menu
}
}
// else
cout << "You must type l or r or q!" << endl;
} // end of while()
cout << "Quitting menu..." << endl;
return 0;
} // end of main()
/*
g++ Menu1.cpp -o Menu1
./Menu1
MAIN MENU:
l: left, r: right, q: quit -> n
You must type l or r or q!
MAIN MENU:
l: left, r: right, q: quit -> l
LEFT MENU:
Select a or b: a
You chose 'a'
MAIN MENU:
l: left, r: right, q: quit -> l
LEFT MENU:
Select a or b: c
You didn't choose a or b!
MAIN MENU:
l: left, r: right, q: quit -> r
RIGHT MENU:
Select c or d: d
You chose 'd'
MAIN MENU:
l: left, r: right, q: quit -> r
RIGHT MENU:
Select c or d: q
You didn't choose c or d!
MAIN MENU:
l: left, r: right, q: quit -> q
Quitting menu...
*/
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
// A menu using a switch statement
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
char c; // To hold the response (input from keyboard)
bool quit = false; // Flag for quitting
while(quit == false)
{
cout << "Select a, b, c, or q to quit: ";
char response;
cin >> response;
switch(response)
{
case 'a':
cout << "You chose 'a'" << endl;
break;
case 'b':
cout << "You chose 'b'" << endl;
break;
case 'c':
cout << "You chose 'c'" << endl;
break;
case 'q':
cout << "Quitting menu..." << endl;
quit = true; // to exit while
break; // out of switch()
default:
cout << "Please use a, b, c, or q!" << endl;
break;
} // end of switch()
} // end of while()
return 0;
} // end of main()
/*
g++ Menu2.cpp -o Menu2
./Menu2
Select a, b, c, or q to quit: a
You chose 'a'
Select a, b, c, or q to quit: b
You chose 'b'
Select a, b, c, or q to quit: c
You chose 'c'
Select a, b, c, or q to quit: d
Please use a, b, c, or q!
Select a, b, c, or q to quit: q
Quitting menu...
*/
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
Exercise 3-3. Write a program that uses a while() loop to read words from standard input (cin) into a string. This is an "infinite" while() loop, which you break out of (and exit the program) using a break statement. For each word that is read, evaluate it by first using a sequence of if() statements to "map" an integral value to the word, and then use a switch() statement that uses that integral value as its selector (this sequence of events is not meant to be good programming style; it’s just supposed to give you exercise with control flow). Inside each case, print something meaningful. You must decide what the "interesting" words are and what the meaning is. You must also decide what word will signal the end of the program. Test the program by redirecting a file into the program's standard input (if you want to save typing, this file can be your program's source file).
#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::cin;
using std::endl;
int main()
{
int len; // length
string word;
while(true) // for ever
{
cin >> word;
if (cin.eof()) {break;} // end program
// else
len = word.length(); // word.size();
if (len < 3) // too short, ignored
{continue;} // go to the next while() iteration
else if (len < 10) // average word length
{
switch(len)
{
case 3: case 4:
cout << "Short word (" << len << "): " << word << endl;
break;
case 5: case 6:
cout << "Medium word length (" << len << "): " << word << endl;
break;
default:
cout << "Longer word (" << len << "): " << word << endl;
break;
}
}
else if (len < 20) // long word
{
switch(len)
{
case 10: case 11: case 12:
cout << "Long word (" << len << "): " << word << endl;
break;
default:
cout << "Very long word (" << len << "): " << word << endl;
break;
}
}
else // len >= 20 (too long)
{
cout << "Too long ("<< len << ")! Won't print it!" << endl;
}
}
return 0;
}
/*
g++ Words.cpp -o Words
./Words // input from keyboard
Hello! // Enter
Medium word length (6): Hello!
Hi // Enter (`Hi' too short, is just ignored)
Hi! // Enter
Short word (3): Hi!
Well... // Enter
Longer word (7): Well...
abracadabra // Enter
Long word (11): abracadabra
baraboumbosaurus rex // Enter
Very long word (16): baraboumbosaurus
Short word (3): rex
supercalifragilistic // Enter
Too long! Won't print it!
// Ctrl^D in Linux, Ctrl^Z+Enter in Windows (EOF)
./Words < Words.cpp // input from source file
./Words < Words // input from binary file
*/
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
// A menu using 3 switch statements
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
char c; // To hold the response (input from keyboard)
bool quit = false; // Flag for quitting
while(quit == false)
{
cout << "MAIN MENU:" << endl;
cout << "l: left, r: right, q: quit -> ";
cin >> c;
switch (c)
{
case 'q':
cout << "Quitting menu..." << endl;
quit = true; // to exit while()
break; // from (outer) switch()
case 'l':
cout << "LEFT MENU:" << endl;
cout << "Select a or b: ";
cin >> c;
switch (c)
{
case 'a':
cout << "You chose 'a'" << endl;
break; // out of first inner switch()
case 'b':
cout << "You chose 'b'" << endl;
break; // out of first inner switch()
default:
cout << "You didn't choose a or b!" << endl;
break; // out of first inner switch()
} // end of first inner switch()
break; // from outer switch(), back to main menu
case 'r':
cout << "RIGHT MENU:" << endl;
cout << "Select c or d: ";
cin >> c;
switch (c)
{
case 'c':
cout << "You chose 'c'" << endl;
break; // out of second inner switch()
case 'd':
cout << "You chose 'd'" << endl;
break; // out of second inner switch()
default:
cout << "You didn't choose c or d!" << endl;
break; // out of second inner switch()
} // end of second inner switch()
break; // from outer switch(), back to main menu
default:
cout << "You must type l or r or q!" << endl;
break; // from outer switch(), back to main menu
} // end of outer switch()
} // end of while()
return 0;
} // end of main()
/*
g++ Menu3.cpp -o Menu3
./Menu3
MAIN MENU:
l: left, r: right, q: quit -> n
You must type l or r or q!
MAIN MENU:
l: left, r: right, q: quit -> l
LEFT MENU:
Select a or b: a
You chose 'a'
MAIN MENU:
l: left, r: right, q: quit -> l
LEFT MENU:
Select a or b: c
You didn't choose a or b!
MAIN MENU:
l: left, r: right, q: quit -> r
RIGHT MENU:
Select c or d: d
You chose 'd'
MAIN MENU:
l: left, r: right, q: quit -> r
RIGHT MENU:
Select c or d: q
You didn't choose c or d!
MAIN MENU:
l: left, r: right, q: quit -> q
Quitting menu...
*/
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
// The infamous goto from C is also supported in C++
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int i, j;
long val = 0;
for(i = 1; i < 1000; i++)
{
for(j = 1; j < 100; j += 10)
{
val = i * j;
if(val > 47000)
{goto bottom;} // break would only go to the outer 'for'
} // end of inner for()
} // end of outer for()
bottom: // A label
cout << i << " * " << j << " = " << val << endl;
return 0;
}
/*
g++ GoTo.cpp -o GoTo
./GoTo
517 * 91 = 47047
*/
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
// A menu using switch statements and gotos
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
char c; // To hold the response (input from keyboard)
while(true)
{
cout << "MAIN MENU:" << endl;
cout << "l: left, r: right, q: quit -> ";
cin >> c;
switch (c)
{
case 'q':
goto bottom; // break would exit (outer) switch(), goto exits while()
case 'l':
cout << "LEFT MENU:" << endl;
cout << "Select a or b: ";
cin >> c;
switch (c)
{
case 'a':
cout << "You chose 'a'" << endl;
break; // out of first inner switch()
case 'b':
cout << "You chose 'b'" << endl;
break; // out of first inner switch()
default:
cout << "You didn't choose a or b!" << endl;
break; // out of first inner switch()
} // end of first inner switch()
break; // from outer switch(), back to main menu
case 'r':
cout << "RIGHT MENU:" << endl;
cout << "Select c or d: ";
cin >> c;
switch (c)
{
case 'c':
cout << "You chose 'c'" << endl;
break; // out of second inner switch()
case 'd':
cout << "You chose 'd'" << endl;
break; // out of second inner switch()
default:
cout << "You didn't choose c or d!" << endl;
break; // out of second inner switch()
} // end of second inner switch()
break; // from outer switch(), back to main menu
default:
cout << "You must type l or r or q!" << endl;
break; // from outer switch(), back to main menu
} // end of outer switch()
} // end of while()
bottom: // A label
cout << "Quitting menu..." << endl;
return 0;
} // end of main()
/*
g++ Menu3g.cpp -o Menu3g
./Menu3g
MAIN MENU:
l: left, r: right, q: quit -> n
You must type l or r or q!
MAIN MENU:
l: left, r: right, q: quit -> l
LEFT MENU:
Select a or b: a
You chose 'a'
MAIN MENU:
l: left, r: right, q: quit -> l
LEFT MENU:
Select a or b: c
You didn't choose a or b!
MAIN MENU:
l: left, r: right, q: quit -> r
RIGHT MENU:
Select c or d: d
You chose 'd'
MAIN MENU:
l: left, r: right, q: quit -> r
RIGHT MENU:
Select c or d: q
You didn't choose c or d!
MAIN MENU:
l: left, r: right, q: quit -> q
Quitting menu...
*/
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
// Simple demonstration of recursion
#include <iostream>
using std::cout;
using std::endl;
void removeHat(char cat);
int main()
{
removeHat('A');
return 0;
}
void removeHat(char cat)
{
for(char c = 'A'; c < cat; c++)
{cout << " ";}
if(cat <= 'Z')
{
cout << "cat " << cat << endl;
removeHat(cat + 1); // Recursive call
}
else {cout << "VOOM!!!" << endl;} // end condition for recursion
}
/*
g++ CatsInHats.cpp -o CatsInHats
./CatsInHats
cat A
cat B
cat C
cat D
cat E
cat F
cat G
cat H
cat I
cat J
cat K
cat L
cat M
cat N
cat O
cat P
cat Q
cat R
cat S
cat T
cat U
cat V
cat W
cat X
cat Y
cat Z
VOOM!!!
*/
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
Exercise 3-5. Write a program that evaluates the two expressions in the Subsection labeled "Precedence" (Section "Introduction to Operators").
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int x = 1, y = 2, z = 3;
cout << x + y - 2/2 + z << endl;
cout << x + (y - 2)/(2 + z) << endl;
return 0;
}
/*
g++ Precedence.cpp -o Precedence
./Precedence
5
1
*/
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
// Shows use of auto-increment and auto-decrement operators
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int i = 0;
int j = 0;
cout << ++i << endl; // Pre-increment
cout << j++ << endl; // Post-increment
cout << --i << endl; // Pre-decrement
cout << j-- << endl; // Post decrement
return 0;
}
/*
g++ Increment.cpp -o Increment
./Increment
1
0
0
1
*/