Download as pdf or txt
Download as pdf or txt
You are on page 1of 48

Introduction to C++ Programming

(PART 2)

Reference:
D.S. Malik. (2009). C++ Programming: From Problem Analysis to Program Design. 4th Ed.. Course
Technology, Cengage Learning. Boston, USA.
Outline
PART 1 PART 2
1. The Basic of a C++ 5. Expression
Program. 6. Input Type Conversion(Casting)
2. Data Types 7. Input
3. String Types 8.Output
4. Arithmetic Operators, 9.Increment and decrement
Operator Precedence, operators
Decision Making 10.Pre-Processor Directives

•Sem 1 20202021 •2
5. Expressions

 If all operands in an expression are integers, the


expression is called an integral expression.

 If all operands in an expression are floating-point


numbers, the expression is called a floating-point
or decimal expression.

 An expression that has operands of different data


type is called a mixed expression.

•Sem 1 20202021 •3
5. Expressions (cont’)
EXAMPLE 2.4

Consider the following C++ integral expressions:

2+3*5
3+x–y/7
x + 2 * (y – z) + 18

In these expressions, x, y and z represent variables of


the integer type: that is, they can hold integer values.

•Sem 1 20202021 •4
5. Expressions (cont’)
EXAMPLE 2.5

Consider the following C++ floating-point expressions:

12.8 * 17.5 – 34.50


x * 10.5 + y – 16.2

Here, x, and y represent variables of the floating-point


type: that is, they can hold floating-point values.

•Sem 1 20202021 •5
5. Expressions (cont’)
EXAMPLE 2.6

Consider the following C++ mixed expressions:

2 + 3.5
6 / 4 + 3.9
5.4 * 2 – 13.6 + 18 / 2

•Sem 1 20202021 •6
5. Expressions (cont’)
TWO rules apply when evaluating mixed expressions:
1. When evaluating an operator in a mixed expression:
a) If the operator has the same types of operands, the
operator is evaluated according to the type of the
operands. Integer operands yield an integer result, f-point
operands yield a f-point result.

b) If the operator has both types of operands, then during


calculation the integer is changed to a floating-point
number with the decimal part of zero and the operator is
evaluated. The result is a floating-point numbers.

•Sem 1 20202021 •7
5. Expressions (cont’)
TWO rules apply when evaluating mixed expressions: (cont’)

2. The entire expression is evaluated according to the


precedence rules; *, /, % operators are evaluated
before the + and – operators.
 Operators having the same level of precedence are
evaluated from left to right.
 Grouping is allowed for clarity.

•Sem 1 20202021 •8
5. Expressions (cont’)
EXAMPLE 2.7

3 / 2 + 5.5 = 6.5
Rule applied
Rule 1(a): 3 / 2 = 1 (integer division)
1 + 5.5
Rule 1(b): 1.0 + 5.5
6.5

•Sem 1 20202021 •9
5. Expressions (cont’)
EXAMPLE 2.8
4 * 3 + 7 / 5 – 25.5 = -12.5
Rule applied
Rule 1(a): 4 * 3 = 12
Rule 1(a): 7 / 5 = 1 (integer division)
Rule 1(a): 12 + 1 = 13
13 – 25.5
Rule 1(b): 13.0 - 25.5
-12.5
•Sem 1 20202021 •10
5. Type Conversion

MOTIVATION: cout << 8/3;

Produce

how to get correct result?


2.66667
•Sem 1 20202021 •11
6. Type Conversion

 To avoid unexpected result when evaluating an


arithmetic expression for the operator that has
mixed operands.

 The cast operator, also called type conversion or


type casting.

•Sem 1 20202021 •12


6. Type Conversion (cont’)
 The cast operator takes the following form:

static_cast<dataTypeName> (expression)

E.g.:
static_cast<int> (7.9)
•acceptable (int) 7.9
•Sem 1 20202021 •13
6. Type Conversion (cont’)

 EXAMPLE 2.9:
Expression Evaluates to
static_cast<int> (7.9) 7
static_cast<double> (8+2) 10
static_cast<double> (15/2) 7
static_cast<double> (15)/2 7.5

Quick Review: Evaluate the following expression.


static_cast<int> ( 7.8 + <double> (15)/2 )
•Sem 1 20202021 •14
7. Input

 Data must be loaded into main memory before


it can be manipulated.

 2 types of data:
1. Constant : - Data is fixed throughout program
execution.
2. Variables:- Data is modified during program
execution.

•Sem 1 20202021 •15


7. Input (cont’)
Constant
 In C++, const is used to allocate the data in main
memory.

 General Format:

const dataType IDENTIFIER = value;

•Sem 1 20202021 •16


7. Input (cont’)
METHOD#1 Using const keyword

const dataType IDENTIFIER = value ;

Example:
const double PI = 3.14;
const double DISKAUN = 0.80;
const int NO_OF_STUDENT = 100;
const char FLAG =1;
const double INTEREST_RATE=15.75;

•Sem 1 20202021 •17


7. Input (cont’)
METHOD#2 Using #define

#define IDENTIFIER value

Example:
#define PI 3.14
#define DISKAUN 0.80
#define NO_OF_STUDENT 100
#define FLAG 1
#define INTEREST_RATE 15.75

•Sem 1 20202021 •18


7. Input (cont’)
Variable
 In C++, memory location whose contents can be
modified during program execution.

 Need to declare before using it in the program.

 Variable Declaration General Format:


dataType identifier1, identifier2,…, identifier3;

•Sem 1 20202021 •19


7. Input (cont’)
Variable (cont’)
 General Format: dataType identifier_1,…, identifier_n;

Example:

double Limit_Amount= 500.00;


int counter= 100;
char ch;

•Sem 1 20202021 •20


7.1 Input:
Putting Data into Variables
How to put data into variables?

1. Use assignment statement


2. Use input (read) statement

•Sem 1 20202021 •21


7.1 Input:
Putting Data into Variables (cont’)
(1) Assignment Statement:
assignment operator

variable = expression;

Example:
num1 = 4;
Cyl_area = 2*PI*r*(r+h);
initial_name = ‘Z’;

•Sem 1 20202021 •22


7.1 Input:
Putting Data into Variables (cont’)
(1) Assignment Statement:

Quick Review : Suppose that n1, n2, and n3 are int variables
and the following segment codes are executed in sequence.

int n1, n2, n3; //variables declaration


n1 = 18;
n1 = n1 + 27;
n2 = n1;
n3 = n2/5;
n3 = n2 = n1;
What is the last value stored in n1, n2 and n3?
•Sem 1 20202021 •23
7.1 Input:
Putting Data into Variables (cont’)
(2) Input (Read) Statement:
Stream extraction operator

cin >> variable1 >> variable2 >> … >> variable_n;

Example:

cin >> miles; //read 1 input


cin >> base >> height; //read 2 inputs
cin >> temp1 >> temp2 >> temp3; //read 3 inputs
•Sem 1 20202021 •24
7.1 Input:
Putting Data into Variables (cont’)
(2) Input (Read) Statement:

Quick Review : Store the number 23 into variable feet and


then the number 7 into the variable inches. All the numbers
are entered via the keyboard.

Write the C++ statement to store these numbers.

•Sem 1 20202021 •25


8. Output
 To show the results on the standard input output
device; e.g.: computer screen

 Used cout and operator <<

Stream insertion operator

cout << manipulator or expression << … ;

•Sem 1 20202021 •26


8. Output (cont’)

cout << manipulator or expression << … ;

 The manipulator is used to format the output.


 endl is the simplest manipulator which causes the insertion
point to move to the beginning of the next line.

 The expression is evaluated and its value is printed at


the current insertion point on the output device.

•Sem 1 20202021 •27


Sample Run:

8. Output (cont’)
 Example Code:

expression

manipulator
•Sem 1 20202021 •28
8. Output (cont’)
 Another Code:

C++ is fun. The output of a+b is 13.Press any key to continue


int a=5, b=8;
cout << “ C++ is fun. ”;
cout << “The output of ”;
cout << “a+b is ” << a+b << ‘.’;

int a=5, b=8;


C++ is fun. cout << “ C++ is fun. ” << endl;
The output of cout << “The output of ” << endl;
cout << “a+b is ” << a+b << ‘.’ << endl;
a+b is 13.
Press any key to continue
•Sem 1 20202021 •29
8. Output (cont’)
 Another Code:
C++ is fun.
The output of a+b is 13.
Press any key to continue
int a=5, b=8;
cout << “ C++ is fun. \n The output of a+b is ” << a+b << ‘.’ << endl;

int a=5, b=8;


cout << “ C++ is fun. \n ”;
cout << “ The output of a+b is ” << a+b << ‘.’ << endl;

int a=5, b=8;


cout << “ C++ is fun. ” << endl;
cout << “ The output of a+b is ” << a+b << ‘.’ << endl;

•Sem 1 20202021 •30


8. Ouput (cont’)

Q1:
cout << “ Welcome to 2BMy Bank.\n Enter your password”;

Q2:
cout << “ Welcome to 2BMy Bank.”;
cout << “\n Enter your password”;

 Quick Review: Predict the output for the following segment code.

Q3:
cout << “ Welcome to 2BMy Bank.”;
cout << endl << “Enter your password”;

Q4:
cout << “ Welcome to 2BMy Bank.”<< endl << “Enter your password” <<;

•Sem 1 20202021 •31


8. Output (cont’)

• Escape sequences in C++ allows you to control the output.


Escape Meaning Description
Sequence
\n Newline Cursor moves to the beginning of the next line.
\t Tab Cursor moves to the next tab stop.
\b Backspace Cursor moves one space to the left.

\r Return Cursor moves to the beginning of the current


line.
\\ Backslash Backslash is printed.

\* Single quotation Single quotation mark is printed.

\” Double quotation Double quotation mark is printed.

•Sem 1 20202021 •32


8. Input & Output // Save result in a file.
#include<fstream>
#include<iostream>
// Display result on a screen. using namespace std;
#include<iostream>
void main()
using namespace std;
{
ofstream op; //declares as output file
void main() op.open(“C:\\res.txt”);
{
cout<<“NLKO”; op<<“NLKO”; //save result in a file
cout<<endl; op.close();
} }
•Sem 1 20202021 •33
// Read input from a file then
8. Input & Output // display it on a screen.

#include<fstream>
#include<string>
// Read input from a keyboard then
// display it on a screen. #include<iostream>
#include<iostream> using namespace std;
#include<string> void main()
using namespace std;
{
void main() string a;
{ ifstream ip; //declares as input file
string a;
ip.open(“C:\\res.txt”);
cout<<“Enter a string:”;
cin>>a; //read frm keyboard
ip>>a; //read from file; res.txt
cout<<a; //display on screen
cout<<a; //display it on screen
cout<<endl;
} ip.close();
}
•Sem 1 20202021 •34
9. Increment and Decrement Operators

 Frequently used to keep track of how many times


certain things have happened.

 Increment operator ++
 Increases the value of a variable by 1.

 Decrement operator --
 Decreases the value of a variable by 1.

•Sem 1 20202021 •35


9. Increment and Decrement Operators (cont’)

 Increment and decrement operators each have two


forms; pre and post.
Forms
Pre Post
Operators

Increment ++variable variable++


Decrement --variable variable--

•Sem 1 20202021 •36


9. Increment and Decrement Operators (cont’)

 Find the value of variable y in Example1 and Example2.

Example1: Example2:
int x, y; int x, y;
x = 5; x=5;
y=x++ ; y = 6;
y = --y + ++x;

Operator Category Operators Associativity


Remember: Unary operators - ++ -- ! sizeof (type) Right  Left

•Sem 1 20202021 •37


9. Increment and Decrement Operators (cont’)

 Quick Review: Find the value of variable y and z in Q1


and Q2.

Q1: Q2:
int x, y, z; int x, y, z;
x = 5; x = 5;
y = --x + x++ ; y = x++ + --x ;
z = x; z = x;

•Sem 1 20202021 •38


10. Preprocessor Directives

 Many of the functions and symbols needed are


provided as a collection of libraries.
 Every library has a name and is referred to by a header
file
 Example:
 cin() and cout() are contained in the header file iostream.
 pow() and sqrt() are contained in the header file cmath.

•Sem 1 20202021 •39


10. Preprocessor Directives (cont’)

 Preprocessor directives is used to tell the computer


the locations of the code provided in libraries.

 Processed by a program called a preprocessor.


 all preprocessor commands begin with #

•Sem 1 20202021 •40


10. Preprocessor Directives (cont’)
 to include a header file use preprocessor directive
include.
 General syntax to use preprocessor directive include:

#include <headerFileName>
Example: #include <iostream>
#include <cmath>
#include <string>
#include <cstring>
•Sem 1 20202021 •41
10. Preprocessor Directives (cont’)
Reserved words: using and namespace
 used to access identifiers in C++ header files.

 The using statement typically appears after all the


header files.
 If a program uses multiple header files, only ONE using
statement is needed.

•Sem 1 20202021 •42


10. Preprocessor Directives (cont’)
Reserved words: using and namespace (cont’)
 The identifiers in ANSI/ISO Standard C++ header
files are declared within namespace.
 The name of namespace in each of these header files is
std.
 Two ways to refer to the identifiers:
1. with :: scope resolution operator
2. Without :: scope resolution operator

•Sem 1 20202021 •43


10. Preprocessor Directives (cont’)
/* Description: A C++ program written with scope resolution operator :: */

#include <iostream>

void main( )
{ //begin of main function
char name[25];
std::cout << "Please enter your name>>";
std::cin >> name;
std::cout << std::endl;

std::cout<< "Hi " << name << '.' << std::endl;


std::cout << "Learning C++ is fun. :-) " << std::endl;
} // end of main function
•Sem 1 20202021 •44
10. Preprocessor Directives (cont’)
OUT scope resolution operator :: */
/* Description: A C++ program written withOUT

#include <iostream>
using namespace std;
void main( )
{//begin of main function
char name[25];
cout << "Please enter your name>>";
cin >> name;
cout << endl;

cout<< "Hi " << name << '.' << endl;


cout << "Learning C++ is fun. :-) " << endl;
} // end of main function
•Sem 1 20202021 •45
How does it works?

Fix the
error
Write the code The output of the program

Execute
Program

Compile
Build

•Sem 1 20202021 •46


Programming problem 1
• Design and write a program in C++ to
calculate the elapsed time it takes to make
a 183.67 mile trip. This is the formula for
computing elapsed time:

• Elapsed time = total distance / average speed

• The average time speed during the trip is


58 mph

•Sem 1 20202021 •47


Programming problem 2
• Design and write a program in C++ to
calculate the sum of the integers from 1 to
100. This is the formula for calculating this
sum

• Sum = (n/2) (2a + (n-1)d

• n is the number of integers to be added


• a is the first number
• d is the difference between each number

•Sem 1 20202021 •48

You might also like