Lecture # 2
Lecture # 2
and Input/output
constructs
Lecture # 2
Course Instructor:
Dr. Afshan Jamil
Outline
Layout of
Assignment
simple ++ Variables Identifiers
statements
program
Floating
Data types Integers Type char
point
Arithmetic
Class string Type bool operators and Comments
expressions
Naming
constants
Layout of a simple C++ program
Sample Program
int main() {
bool isCodingFun = true;
int i=100;
float f=23.6;
char ch=‘h’;
double d = 12E4;
string s=“Hello”;
cout << isCodingFun << endl;
cout << “value of int=“<<i<<endl;
CONTD…
cout << “value of float=“<<f<<endl;
cout << “value of double=“<<d<<endl;
cout << “value of char=“<<ch<<endl;
cout << “value of string=“<<s<<endl;
cout<<“ASCII value of
char=“<<int(ch)<<endl;
cout<<“Integer to char=<<“char(i)<<endl;
return 0;
}
CONTD…
• OUTPUT:
1
value of int=100
value of float=23.6
value of ouble=1.2e+013
value of char=h
value of string=hello
ASCII value of char=104
Integer to char=d
sizeof() Function
#include <iostream>
using namespace std;
int main()
{
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of long long: " << sizeof(long long) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
return 0;
}
Arithmetic operators and expressions
• In a C++ program, you can combine variables
and/or numbers using the arithmetic operators +
for addition, – for subtraction, * for multiplication,
and / for division.
• The % operation gives the remainder.
• The computer will follow rules called precedence
rules that determine the order in which the
operators, such as + and *, are performed. These
precedence rules are similar to rules used in algebra
and other mathematics classes.
Precedence Rules
CONTD…
Comment
• Syntax
• setprecision(number)
EXAMPLE
#include <iostream> Output:
#include<iomanip> 13.5634
using namespace std; 13.563400
int main ()
{
float f = 13.5634;
cout<<setprecision(6)<<f<<endl;
cout<<fixed<<setprecision(6)<<f;
return 0;
}
setw()
• setw function is a C++ manipulator
which stands for set width.
• The manipulator specifies the
minimum number of character
positions a variable will consume.
• In simple terms, it helps set the field
width used for output operations.
• Syntax
• setw(number)
CONTD…
Contd… console.
Dear Instructor [Instructor Name],
I am sorry that I am unable to turn in my homework
at this time. First, I ate a rotten [Food], which made
me turn [Color] and extremely ill. I came down with a
fever of [Number 100-120]. Next, my [Adjective] pet
[Animal] must have smelled the remains of the
[Food] on my homework, because he ate it. I am
currently rewriting my homework and hope you will
accept it late.
Sincerely,
[Your Name]
THE END