Lec 03 Programming - Basics
Lec 03 Programming - Basics
Programming Basics
19th March, 2024
1
Another Simple Program:
Adding Two Integers
• Variables
—Location in memory where value can be stored
—Common data types
• int - integer numbers
• char - characters
• double - floating point numbers
—Declare variables with name and data type before
use
int integer1;
int integer2;
int sum;
—Can declare several variables of same type in one
declaration
• Comma-separated list int integer1, integer2, sum; 2
Another Simple Program:
Adding Two Integers
• Variables
—Variable names
• Valid identifier
– Series of characters (letters, digits, underscores)
– Cannot begin with digit
– Case sensitive
3
Another Simple Program:
Adding Two Integers
• Input stream object
— >> (stream extraction operator)
• Used with std::cin
• Waits for user to input value, then press Enter (Return) key
• Stores value in variable to right of operator
– Converts value to variable data type
• = (assignment operator)
— Assigns value to variable
— Binary operator (two operands)
— Example:
sum = variable1 + variable2;
4
1 // Fig. 1.6: fig01_06.cpp
2 // Addition program.
3 #include <iostream>
4
5 // function main begins program execution
6 int main()
7 { Declare integer variables.
8 int integer1; // first number to be input by user
9 int integer2; // second number to be input by user
10 int sum; Usewhich
// variable in stream extraction
sum will be stored
11 operator with standard input
12 std::cout << "Enter first stream to obtain
integer\n"; user input.
// prompt
13 std::cin >> integer1; // read an integer
14
15 std::cout << "Enter second integer\n"; // prompt
16 std::cin >> integer2; // read
Calculations can an integer
be performed in output statements: alternative f
Stream manipulator
17 lines 18 and 20:
18 sum = integer1 + integer2; // assign result to sum
std::endl outputs a
19 std::cout << "Sum is " <<
newline, then “flushes output
integer1 + integer2 << std::end
20 std::cout << "Sum is " << sum << std::endl; // print sum buffer.”
21
22 return 0; // indicate that program ended successfully
23 Concatenating, chaining or 5
24 } // end function main
cascading stream insertion
Enter first integer
45
Enter second integer
72
Sum is 117
6
Variables/Memory Concepts
• Variable names
—Correspond to actual locations in computer's memory
—Every variable has name, type, size and value
—When new value placed into variable,
overwrites previous value
—An identifier must start with either a letter or the
underscore symbol, and all the rest of the characters
must be letters, digits, or the underscore symbol
7
Memory Concepts
integer1 12
int integer1, integer2, sum; integer2 0
– declare three variables sum -3
– starting values are arbitrary
integer1 45
std::cin >> integer2; integer2 72
– Assume user entered 72 sum -3
9
Programming Practice
1. Write a C++ program to Compute following:
1. Area and Perimeter of a rectangle
• Area=Length * Width Perimeter =2*(Length+Width)
2. Area of a triangle
• Area=(1/2)*base*height
3. Area and circumference of a circle
• Area=PI*radius*radius circumference=2*PI*raduis
10
Programming Practice
Write a C++ program, i) user input distance in
meters, compute the distance in feet and inches.
ii) user input distance in feet, compute the
distance in meters and inches.
iii) user input distance in inches, compute the
distance in meters and feet.
11
Operator Precedence
• Why we need?
— Some arithmetic operators are solved at first & some at last
— Example: Find the average of three variables a, b and c
— do not use: a + b + c / 3
— use: (a + b + c ) / 3
• Rules of operator precedence
— Operators in parentheses evaluated first
• Nested/embedded parentheses
– Operators in innermost pair first
— Multiplication, division, modulus applied next
• Operators applied from left to right
— Addition, subtraction applied last
• Operators applied from left to right 12
Operator Precedence
#include <iostream>
using namespace std;
int main() {
// evaluates 17 * 6 first
int num1 = 5 - 17 * 6;
return 0;
}
13
Operator Precedence
14
Operator Precedence
• Evaluation of quadratic equation: ax2+bx+c
15
Operator Precedence
ax2+bx+c=a*x*x+b*x+c;
16
Assignment Operators
• Assignment expression abbreviations
—Addition assignment operator
c = c + 3; abbreviated to
c += 3;
• For example:
d -= 4; d = d - 4;
e *= 5; e = e * 5;
f /= 3; f = f / 3;
g %= 9; g = g % 9;
17
Increment and Decrement
Operators
• Increment operator (c++ or ++c)
can be used instead of c += 1
• Decrement operator (c-- or --c)
can be used instead of c -= 1
—Pre-increment (++c, --c)
• When the operator is used before the variable (++c or --c)
• Variable is changed, then the surrounding expression
evaluated.
—Post-increment (c++, c--)
• When the operator is used after the variable (c++ or c--)
• Surrounding expression is evaluated/executed,
then the variable is changed.
18
Example (a++ vs ++a)
• Suppose a contains 5. What gets printed?
cout << ++a;
• Answer
• c is changed to 6,
• then (cout << c) is evaluated, and 6 is printed.
• Suppose a contains 5. What gets printed?
cout << a++;
• Answer:
• 5 is printed.
(cout << c) is evaluated before the increment
• c then becomes 6
19
1 // Fig. 2.14: fig02_14.cpp
2 // Preincrementing and postincrementing.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 // function main begins program execution
9 int main()
10 {
11 int c; // declare variable
12
13 // demonstrate postincrement
14 c = 5; // assign 5 to c
15 cout << c << endl; // print 5
16 cout << c++ << endl; // print 5 then postincrement
17 cout << c << endl << endl; // print 6
18
19 // demonstrate preincrement
20 c = 5; // assign 5 to c
21 cout << c << endl; // print 5
22 cout << ++c << endl; // preincrement then print 6
23 cout << c << endl; // print 6
24
25 return 0; // indicate successful termination
26
27 } // end function main 20
C++ Keywords
• Reserve words in C++ Language
• Can not be used for identifier names
—Variable names
—Method names
auto break case char const
continue default do double else
enum extern float for goto
if int long register return
short signed sizeof static struct
switch typedef union unsigmed void
volatile while
21
Relational Operators
• Binary operators
• Compare the two values/variables
• Result of comparison gives the Boolean values
— True: if the relation between 2 values/variables is correct
— False: if the relation between 2 values/variables is
incorrect
• Equality Operator (==)
— Should not be confused with assignment (=) operator
22
Relational and Equality
Operators
if ( grade >= 60 )
cout << "Passed";
—Indenting makes programs easier to read
• C++ ignores whitespace characters
(tabs, spaces, etc.)
true
grade >= 60 print “Passed”
false
26
1 // Fig. 1.14: fig01_14.cpp
2 // Using if statements, relational
3 // operators, and equality operators.
4 #include <iostream>
5
6 using std::cout; // program uses cout
7 using std::cin; // program uses cin using statements eliminate
8 using std::endl; // program uses endl need for std:: prefix.
9
10
Declare variables.
// function main begins program execution
11 int main()
12 {
Can write cout and cin
13 int num1; // first number to be read from user
14
without std:: prefix.
int num2; // second number to be read from user
15
16 cout << "Enter two integers,ifand I willcompares
structure tell you\n"
values
17 << "the relationships they satisfy: ";
of num1 and num2 to test for
If condition is true (i.e.,
18 cin >> num1 >> num2; // read two integers
equality. values are equal), execute this
19
if structure compares
statement.values
20 if ( num1 == num2 )
of num1 and num2
If condition is true (i.e.,
to test for
21 cout << num1 << " is equal to " << num2 << endl;
22
inequality. values are not equal), execute
23 if ( num1 != num2 ) this statement.
27
24 cout << num1 << " is not equal to " << num2 << endl;
26 if ( num1 < num2 )
27 cout << num1 << " is less than " << num2 << endl;
28
29 if ( num1 > num2 )
30 cout << num1 << " is greater than " << num2 << endl;
Statements may be split over
31
32 if ( num1 <= num2 )
several lines.
33 cout << num1 << " is less than or equal to "
34 << num2 << endl;
35
36 if ( num1 >= num2 )
37 cout << num1 << " is greater than or equal to "
38 << num2 << endl;
39
40 return 0; // indicate that program ended successfully
41
42 } // end function main
if ( grade >= 60 )
cout << "Passed";
else
cout << "Failed";
Ternary operator (?:)
• Three arguments:
(condition, value if true, value if false)
cout << ( grade >= 60 ? “Passed” : “Failed” );
false true
grade >= 60
int main () {
// local variable declaration:
int a = 100;
int b = 200;
return 0; 32
}
if/else Ladder Structure
• Multi-way branching else if structures
—One inside another, test for multiple cases
—Once condition met, other statements skipped
if student’s grade is greater than or equal to 90
Print “A”
else
if student’s grade is greater than or equal to 80
Print “B”
else
if student’s grade is greater than or equal to 70
Print “C”
else
if student’s grade is greater than or equal to 60
Print “D”
else
Print “F”
if/else Ladder Structure
• Example
if ( grade >= 90 ) // 90 and above
cout << "A";
else if ( grade >= 80 ) // 80-89
cout << "B";
else if ( grade >= 70 ) // 70-79
cout << "C";
else if ( grade >= 60 ) // 60-69
cout << "D";
else // less than 60
cout << "F";
if/else Ladder Structure
35
if/else Ladder Structure
36
if/else Ladder Structure
#include <iostream>
#include<cctype>
int main()
{
char ch;
cout<<"Enter a Alphabet Character: ";
cin>>ch;
switch ( variable ) {
case value1: // taken if variable == value1
statements
break; // necessary to exit switch
case value2:
case value3: // taken if variable == value2 or == value3
statements
break;
true
case a case a action(s) break
false
true
case b case b action(s) break
false
.
.
.
true
case z case z action(s) break
false
default action(s)
39
Switch Statement
• Create a calculator using Switch statement, the user
inputs two numeric values and selects the
arithmetic operator from the following list:
(“*”, “/”, “-”, “+”, ). The program displays the result
according to operation selected by the user.
40
Switch Statement
int main() {
char oper;
float num1, num2;
cout << "Enter an operator (+, -, *, /): ";
cin >> oper;
cout << "Enter two numbers: " << endl;
cin >> num1 >> num2;
switch (oper) {
case '+':
cout << num1 << " + " << num2 << " = " << num1 + num2;
break;
case '-':
cout << num1 << " - " << num2 << " = " << num1 - num2;
break;
case '*':
cout << num1 << " * " << num2 << " = " << num1 * num2;
break;
case '/':
cout << num1 << " / " << num2 << " = " << num1 / num2;
break;
default:
cout << "Error! The operator is not correct";
break;
}
return 0; } 41
Conditional Statements
42
Programming Tasks
Task#1: Write a C++ program that asks the user
to enter two numbers, obtains the two numbers
from the user and prints the sum, product,
difference, and quotient of the two numbers.
43
Programming Tasks
Task#2:Write a C++ program that asks the user
to enter two integers, obtains the numbers from
the user, then prints the larger number followed
by the words "is larger." If the numbers are equal,
print the message "These numbers are equal."
int num1, num2
num1==num2; num1” is equal to ” num2;
num1>num2; num1” is Larger than ” num2;
num1<num2 num1” is Smaller than ” num2;
44
Programming Tasks
Task#4:(Displaying Shapes with Asterisks) Write a
program that prints a box, an oval, an arrow and
a diamond as follows:
45