CS101
CS101
C++
Welcome to C++!
10}
Welcome
to
C++!
Multiple lines can be printed with one
statement.
Lecture 08: C++ CS 101: Introduction7to Computing
Another Simple Program:
Adding Two Integers
• Variables
– Location in memory where a value can be stored for use by a program
– Must be declared with a name and a data type before they can be used
– Some common data types are:
• int - integer numbers
• char - characters
• double - floating point numbers
– Example: int myvariable;
• Declares a variable named myvariable of type int
– Example: int variable1, variable2;
• Declares two variables, each of type int
Enter first integer Variables can be output using std::cout << variableName
45
Enter second integer
72
Lecture 08: C++ CS 101: Introduction10
to Computing
Memory Concepts
• Variable names
– Correspond to locations in the computer's memory
– Every variable has a name, a type, a size and a value
– Whenever a new value is placed into a variable, it replaces the previous
value - it is destroyed
– Reading variables from memory does not change them
• A visual representation
integer1 45
Arithmetic
• Arithmetic operators:
C ++ o p e ra tio n Arith m e tic Alg e b ra ic C ++ e xp re ssio n
o p e ra to r e xp re ssio n
Addition + f+7 f + 7
Subtraction - p–c p - c
Multiplication * bm b * m
Division / x/y x / y
Modulus % r mod s r % s
• Rules of operator precedence:
Operator(s) Operation(s) Order of evaluation (precedence)
Relational operators
> > x > y x is greater than y
< < x < y x is less than y
Equality operators
= == x == y x is equal to y
!= x != y x is not equal to y
4#include <iostream>
10 int main()
11 {
13
20
cout << num1 << " is equal to " << num2 << endl;
the relationships The
they satisfy:
if statements test the truth of the
21 if ( num1 != num2 ) 3 7 condition. If it is true, body of if
statement is executed. If not, body is
22 cout << num1 << " is not equal to " << num2 << endl;
skipped.
23 3 isTo include
not multiple
equal to 7in a
statements
24 if ( num1 < num2 ) body, delineate them with braces {}.
25 cout << num1 << " is less than " << num2 << endl;
26 3 is less than 7
27 if ( num1 > num2 )
28 cout << num1 << " is greater than " << num2 << endl;
29
33
34 if ( num1 >= num2 )
35 cout << num1 << " is greater than or equal to "
36 << num2 << endl;
37
38 return 0; // indicate that program ended successfully
39 }
References
Dietal and Dietal : How to Program C++
3rd Edition
Quiz 2
– Write a C++ program to input 5 numbers using while loop and find there
sum, average, and product.