Write a program that asks the user to enter a month (1 for January, 2 for February, and so on) and then prints the number of days in the month. For February, print “28 or 29 days”.
Enter a month: 5
30 days
#include < iostream > using namespace std; int main(){ int month; cout << "Enter a month: " << endl; cin >> month; if(month == 2){ cout << "28 or 29 days" << endl; } else if(month == 4 || month == 6 || month == 9 || month == 11){ cout << "30 days" << endl; } // if month is 1, 3, 5, 7, 8, 10, or 12 else{ cout << "31 days" << endl; } }
Write a program that reads in three floating-point numbers and prints the largest of the three inputs. For example:
Please enter three numbers: 4 9 2.5
The largest number is 9.
#include < iostream > using namespace std; int main(){ /* Given three numbers, find the largest */ double n1,n2,n3; cout << "Type three numbers: "<< endl; cin >> n1 >> n2 >> n3; double largest = 0; if(n1 >= n2 && n1 >= n3){ largest = n1; } else if(n2 >= n1 && n2 >= n3){ largest = n2; } else{ largest = n3; } cout << "The largest is " << largest << endl; }
Please enter a number : 4
The sum is 10.
/* Calculating the sum 1 + 2 + 3 + ... + N using a for loop. */ #include < iostream > using namespace std; int main() { int num = 0; cout << "Please enter a number : "; cin >> num; int sum=0; for(int i=1;i <= num;++i){ sum += i; } cout << "The sum is " << sum << "." << endl; return 0; }
Please enter the number of scores : 4
Please enter score 1 : 90
Please enter score 2 : 70
Please enter score 3 : 65
Please enter score 4 : 98
The max is 98.
/* Finding the maximum using a for loop */ #include < iostream > using namespace std; int main() { int num = 0; cout << "Please enter the number of scores : "; cin >> num; double max = 0; for(int i = 0; i <= num; i++) { cout << "Please enter score " << i << " : "; double score; cin >> score; if(score > max) { max = score; } } cout << "The max is " << max << "." << endl; return 0; }
Exercise P3.21. Prime numbers. Write a program that prompts the user for an integer and then prints out all prime numbers up to that integer. For example, when the user enters 20, the program should print
2
3
5
7
11
13
17
19
Recall that a number is a prime number if it is not divisible by any number except 1 and itself.
#include < iostream > #include < string > using namespace std; int main(){ cout << "Type a number : "; int num; cin >> num; for(int i = 2; i <= num; i++) { bool prime = true; for(int j = 2; j < i; j++) { if(i%j==0) { prime = false; break; } } if(prime) { cout << i << endl; } } return 0; }