C++ Exercises II
C++ Exercises II
Write a program that asks the user to type an integer and writes "YOU WIN" if the value is between 56 and 78 (both included). In the other case it writes "YOU LOSE".
Solution
#include<iostream> using namespace std; int main() { int a; cout << "Type an integer : "; cin >> a; if ( (a >= 56) && (a <= 78) ) cout << "YOU WIN" << endl; else cout << "YOU LOSE" << endl; return 0; }
EXERCISE 2
Write a program that asks the user to type all the integers between 8 and 23 (both included) using a for loop.
Solution
int main() { int typedInt = 0; cout << "Type all numbers between 8 and 23: " << endl; for(int i = 8; i <= 23; i++) { cin >> typedInt; if (typedInt != i) { cout << "You Missed the sequence the next number was " << i << endl; } } return 0; }
EXERCISE 3
Same exercise but you must use a while.
Solution
EXERCISE 4
Write a program that asks the user to type 10 integers and writes the sum of these integers.
Solution
#include <iostream> using namespace std; int main() { //Define variables int i = 1; int n = 0; int temp;
cout << "This program sums ten user entered integers\n\n"; for (i = 1 ; i <= 10 ; i++) { cout << "Type integer " << i << ": "; cin >> temp; n = n + temp; } cout << "\nThe sum of the integers is: " << n << endl; return 0; } #include<iostream> using namespace std; int main() { int i,s=0,x; for(i=0;i<10;i++) { cout<<"Type an integer: ";cin>>x; s=s+x; } cout<<"The sum is : "<<s<<endl; return 0; }
EXERCISE 5
Write a program that asks the user to type an integer between 0 and 20 (both included) and writes N+17. If someone types a wrong value, the program writes ERROR and he must type another value.
Solution
#include<iostream> using namespace std; int main() { int N; bool ok; do
{ cout<<"Type the value of N between 0 et 20 :";cin>>N; ok= N<=20 && N>=0; if(!ok)cout<<"ERROR"<<endl; }while(!ok); N=N+17; cout<<"The final value is : "<<N<<endl; return 0; }
EXERCISE 6
Write programs that ask the user to type strictly positive integer. When the user types a negative value the program write ERROR and ask for typing an other value. When the user types 0, that means that the last value has been typed and the program must write the average of the strictly positive integers. If the number of typed values is zero the program writes 'NO AVERAGE'.
// Solution 1 #include<iostream> using namespace std; int main() { int x, s=0,nb=0; double average; do{ cout<<"Type an integer:";cin>>x; if(x>0){s=s+x;nb++;} else if(x<0)cout<<"ERROR "; }while(x!=0); if(nb==0)cout<<"NO AVERAGE"<<endl; else { average=(double)s/nb; cout<<"The average is : "<<average<<endl; } return 0; }
Solution