P.1 โ Warm-up problems (chapters 1โ4)
Try each problem yourself first. Stuck? Press Show hint. Still stuck? That's fine โ read the answer, then try again tomorrow without looking.
Every answer has a โถ Run button. Change the code and run it again to see what happens.
Problems#
Ask the user for a number of seconds. Print it as minutes and seconds. For 135, print 2 minutes and 15 seconds.
Integer division / gives the minutes. The remainder % gives the seconds left over.
#include <iostream> int main(){ std::cout << "Seconds: "; int total {}; std::cin >> total; std::cout << total / 60 << " minutes and " << total % 60 << " seconds\n"; return 0;}Ask for three whole numbers and print the biggest one.
Start by assuming the first one is the biggest. Then check the other two with if.
#include <iostream> int main(){ int a {}, b {}, c {}; std::cout << "Enter three numbers: "; std::cin >> a >> b >> c; int biggest { a }; if (b > biggest) biggest = b; if (c > biggest) biggest = c; std::cout << "Biggest: " << biggest << '\n'; return 0;}A year is a leap year if it can be divided by 4, except years divided by 100, unless they can also be divided by 400. Ask for a year and say whether it's a leap year. (2024 โ yes, 1900 โ no, 2000 โ yes.)
"Can be divided by 4" means year % 4 == 0. Combine the three rules with && and ||.
#include <iostream> int main(){ std::cout << "Year: "; int year {}; std::cin >> year; bool leap { (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 }; std::cout << year << (leap ? " is" : " is not") << " a leap year.\n"; return 0;}Ask for a test score from 0 to 100. Print the grade: 90+ is A, 80+ is B, 70+ is C, 60+ is D, below 60 is F. If the number is outside 0โ100, print an error instead.
Check for the error first. Then use an if / else if chain from the highest grade down.
#include <iostream> int main(){ std::cout << "Score (0-100): "; int score {}; std::cin >> score; if (score < 0 || score > 100) std::cout << "That's not a valid score.\n"; else if (score >= 90) std::cout << "A\n"; else if (score >= 80) std::cout << "B\n"; else if (score >= 70) std::cout << "C\n"; else if (score >= 60) std::cout << "D\n"; else std::cout << "F\n"; return 0;}Ask for an amount of cents (like 287). Print how many quarters (25), dimes (10), nickels (5) and pennies (1) make it, using as few coins as possible.
Use / to count how many of the biggest coin fit, then % to keep what's left over for the next coin.
#include <iostream> int main(){ std::cout << "Cents: "; int cents {}; std::cin >> cents; std::cout << "Quarters: " << cents / 25 << '\n'; cents %= 25; std::cout << "Dimes: " << cents / 10 << '\n'; cents %= 10; std::cout << "Nickels: " << cents / 5 << '\n'; cents %= 5; std::cout << "Pennies: " << cents << '\n'; return 0;}Tip: press โ / โ to move between lessons, / to search.