PROGRAMMING LANGUAGE C++ lecture2 أ. منى الزهراني
A Simple Program: Printing a Line of Text أ. منى الزهراني 1 // Fig // Printing a line with multiple statements. 3 #include 4 5 // function main begins program execution 6 int main() 7 { 8 std::cout << "Welcome "; 9 std::cout << "to C++!\n"; return 0; // indicate that program ended successfully } // end function main Multiple stream insertion statements produce one line of output. Welcome to C++!
أ. منى الزهراني
Printing multiple lines with a single statement أ. منى الزهراني 1 // Fig // Printing multiple lines with a single statement 3 #include 4 5 // function main begins program execution 6 int main() 7 { 8 std::cout << "Welcome\nto\n\nC++!\n"; 9 10 return 0; // indicate that program ended successfully } // end function main Welcome to C++! Using newline characters to print on multiple lines.
Compound Assignments: أ. منى الزهراني A common operation in programming is to apply an operator to a variable, and then store the result in the same variable. For example, the following assignment doubles the value of j: j = j * 2; This can be rewritten as: j *= 2; And the other operator as the previous one: +=, -=, /=, %=
أ. منى الزهراني a = 5 ; b = 3 a += 2; b += 1; a = ……….., b = ………… ________________________ x = 5 ; y = 3 x *= 2; y *= 3; X = ……….., y = ………… Examples:
أ. منى الزهراني Examples: a = 1; // a = 1 b = ++a; // a = 2, b = 2 c = a++; // a = 3, c = 2 a = 5; b = 3; n = ++a + b--; a = , b = , n = a = 5; b = 3; n = ++a * ++b; a = , b = , n = n = a++ * b++; a = , b = , n = a = 5; b = 3; n = a++ * --b; a = , b = , n =
أ. منى الزهراني a = 1; // a = 1 a = 2, b = 2 b = ++a; // a = 2, b = 2 a = 3, c = 2 c = a++; // a = 3, c = 2 a = 5; b = 3; a = 6, b = 2, n = 9 n = ++a + b--; // a = 6, b = 2, n = 9 a = 5; b = 3; a = 6, b = 4, n = 24 n = ++a * ++b; // a = 6, b = 4, n = 24 a = 6, b = 4, n = 15 n = a++ * b++; // a = 6, b = 4, n = 15 a = 5; b = 3; a = 6, b = 2, n = 10 n = a++ * --b; // a = 6, b = 2, n = 10 Examples:
Converting mathematical expression to sentences in the C++ language: أ. منى الزهراني
Converting mathematical expression to sentences in the C++ language: أ. منى الزهراني
Example 1: If you have the following sentences: Int A=2, B=2, C=3, R; Find the value of R? (1) R= 2B – 4AC (2) R= B+A+(CBA)/6 (3) R= C%A+BC/A (4) R= 17% (C+A) B+6
أ. منى الزهراني Solution (1) R= 2*B – 4*A*C = 2*2 – 4*2*3 =4- 24 = -20 (2) R= B+A+ (C*B*A)/6 = /6 = = 6
أ. منى الزهراني Solution (3) R= C%A+B*C/A = 3%2+2*3/2 1+6/2 = 5+6/2 1+3 =5+3 4 = = 8 (4) R= 17% (C+A) *B+6 = 17% (3+2)*2+6 = 17% 5*2+6 2*2+6 =4* = =14
أ. منى الزهراني Example 2: If you have the following sentences: Int A=3, B=8, R? Find the value of R? (1) R= (A>=0) + (A!=B) (2) R= (A+5B) <= (30/A)
أ. منى الزهراني Solution (1) R= (3>=0) + (3!=8) = 1+1 = 2 (2) R= (3+5*8)<= (30/3) = (3+40) <= 10 = 43<=10 = 0