Week 3 Classwork
Big N
Complete the highly useful code fragment below that prints out a giant letter 'N' that is SIZE x SIZE in dimension.
#include <iostream>
#include <string>
using namespace std;
/*
* Design a program that writes
* a 5 by 5 capital letter N
* made up of the character 'N'.
*
* Output should be:
* N N
* NN N
* N N N
* N NN
* N N
*/
int main () {
// Assume SIZE must be odd
const int SIZE = 5;
// For loop that goes through
// SIZE rows...
for (int i = 0; i < SIZE; i++) {
// And loop that goes through
// SIZE columns
for (int j = 0; j < SIZE; j++) {
if (j == 0 || j == SIZE - 1 || j == i) {
cout << "N";
// Otherwise, print a space
} else {
cout << " ";
}
}
cout << endl;
}
}
Guessing Game
Complete the code fragment below for playing a number guessing game with your computer!
#include <iostream>
#include <string>
#include <cmath>
#include <time.h>
using namespace std;
/*
* Try to guess the number your computer is thinking of!
* We first generate a random number between 0 and MAX_CHOICES,
* prompt the user for a guess, and tell them if they win,
* are 1 away from the number, or are way off (2+ away).
* Players have only MAX_TRIES turns to guess the number.
*/
int main () {
// Magic incantation: don't worry about for now
srand(time(NULL));
const int MAX_CHOICES = 5; // Guess 0 - 4
const int MAX_TRIES = 3; // Get 3 tries
// Target is the random number we're guessing
int target = rand() % MAX_CHOICES,
counter = 0,
guess,
difference;
string hint;
do {
cout << "Guess a number! ";
// [!] Collect user's guess
cin >> guess;
// abs == absolute value
difference = abs(target - guess);
switch (difference) {
case 0:
cout << "You win!" << endl;
return 0;
case 1:
cout << "Off by 1!" << endl;
break;
default:
cout << "Way off... just give up." << endl;
break;
}
cout << hint << endl;
counter++;
// [!] Keep going as long as the user has more tries
} while (counter < MAX_TRIES);
cout << "YOU LOSE! YOU GET NOTHING! GOOD DAY SIR/MADAME!" << endl;
}
Capsizer
Design a program that asks the user for text input and then swaps all capital letters for their lowercase equivalents, and vice-versa.
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
/*
* Write a program that queries the user for a string,
* swaps all lowercase letters for uppercase ones (and
* vice versa), and then prints out the result.
*/
int main () {
string s;
char c;
// Ask for a string
cout << "Gimme dat string: ";
// [!] Collect user's input
getline(cin, s);
// [!] Iterate through each string character
for (int i = 0; i < s.length(); i++) {
// [!] If it's uppercase, convert to lower, and vice versa
// We'll use the ternary conditional!
c = (isupper(s[i])) ? tolower(s[i]) : toupper(s[i]);
// Print out current value of c
cout << c;
}
cout << endl;
}