Uploaded by Fungai B Msonza

c++ theory FUNGAI MSONZA

advertisement
C++ THEORY
1.If statement
#include<iostream>
using namespace std;
// This program will determine whether you able to watch rated 18 movie or not
int main() {
int age;
cout << ” enter your age ”<<endl;
cin>>age;
if(age< 18){
cout<<” sorry you cannot watch this movie” <<endl;
} else{
cout<<” enjoy the movie” <<endl;
}
return 0;
}
The program interacts with the user when you enter the age below 18, Result from the above
program will show: (output) sorry you cannot watch this movie
Else it will show: (output)enjoy the movie
2.for loop
#include<iostream>
using namespace std;
// this program will calculate the multiples of 2 up to 20
int main(){
for(int i=2; i<=20; i+=2) {
cout<<i<<endl;
}
return 0;
C++ THEORY
}
Result of the above program output: 2, 4, 6, 8, 10,12,14,16,18,20
The for loop for infinity but if you set a limit to the loop it will stop.
3.do while
#include <iostream>
using namespace std;
// this program will loop the given character
int main(){
int i= 1;
do {
cout<<” fungai ”<<endl;
i+=1;
} while(i<20);
return 0;
}
Output: fungai, fungai, fungai, fungai…….19 times
This program loops any number, character, string for 19 times
4.Switch statement
#include <iostream>
using namespace std;
int main(){
char preference;
// this program will interact with the user into choosing the given choices
cout<<” choose your type of house between the following z, x and c ”endl;
C++ THEORY
cout<<” Enter your preference: ”<<endl;
cin>>preference;
switch(preference) {
case ‘z’:
cout<<” you chose a normal house with a swimming pool” <<endl;
break;
case'x':
cout<<"you chose a mansion with a swimming pool and sports yard"<<endl;
break;
case'c':
cout<<"you chose a triple story house with a swimming pool and sports yard"<<endl;
break;
default:
cout<<"sorry invalid information"<<endl;
b
}
return 0;
}
The program interacts with the user when you enter the given letters it will show the output.
For instance, if you enter ‘x’ the output will be: “you chose a mansion with a swimming pool
and sports yard”
Download