Csci 107: Copy Rights Reserved - 2009 © Metis Education
Csci 107: Copy Rights Reserved - 2009 © Metis Education
int main() {
//variable declaration
//read values input from user
//computation and print output to user
return 0;
}
After you write a C++ program you compile it; that is, you run a program
called compiler that checks whether the program follows the C++ syntax
if it finds errors, it lists them
If there are no errors, it translates the C++ program into a program in machine
language which you
Copy canReserved
Rights execute- 2009 © Metis Education
Notes
what follows after // on the same line is considered comment
indentation is for the convenience of the reader; compiler ignores all spaces
and new line ; the delimiter for the compiler is the semicolon
#include <iostream.h>
int main() {
cout << “Hello world!”;
return 0;
}
Copy Rights Reserved - 2009 © Metis Education
Variable declaration
type variable-name;
Meaning: variable <variable-name> will be a variable of type <type>
Example:
int a, b, c;
double x;
int sum;
char my-character;
Copy Rights Reserved - 2009 © Metis Education
Input statements
cin >> variable-name;
Meaning: read the value of the variable called <variable-
name> from the user
Example:
cin >> a;
cin >> b >> c;
cin >> x;
cin >> my-character;
Copy Rights Reserved - 2009 © Metis Education
Output statements
cout << variable-name;
Meaning: print the value of variable <variable-name> to the user
cout << “any message “;
Meaning: print the message within quotes to the user
cout << endl;
Meaning: print a new line
Example:
cout << a;
cout << b << c;
cout << “This is my character: “ << my-character << “ he he he”
<< endl;
Copy Rights Reserved - 2009 © Metis Education
If statements
True False
condition
if (condition) {
S1;
}
S1 S2
else {
S2;
}
S3;
S3
Boolean operators
&& and
|| or
! not
Copy Rights Reserved - 2009 © Metis Education
Examples
Assume we declared the following variables:
int a = 2, b=5, c=10;
void main() {
int a,b,c;
cin >> a >> b >> c;
if (a <=b) {
cout << “min is “ << a << endl;
}
else {
cout << “ min is “ << b << endl;
}
cout << “happy now?” << endl;
}
Copy Rights Reserved - 2009 © Metis Education
While statements
while (condition) { True False
condition
S1;
}
S1
S2;
S2
void main() {
int i, sum, x;
sum=0;
i=1;
while (i <= 100) {
cin >> x;
sum = sum + x;
i = i+1;
}
cout << “sum is “ << sum << endl;
}
Copy Rights Reserved - 2009 © Metis Education
Exercise
Write a program that asks the user
Do you want to use this program? (y/n)
If the user says ‘y’ then the program terminates
If the user says ‘n’ then the program asks
Are you really sure you do not want to use this program?
(y/n)
If the user says ‘n’ it terminates, otherwise it prints again
the message
Are you really really sure you do not want to use this
program? (y/n)
And so on, every time adding one more “really”.