際際滷

際際滷Share a Scribd company logo
Variables, Data types
and Input/output
constructs
Lecture # 2
Course Instructor:
Dr. Afshan Jamil
Outline
Layout of
simple ++
program
Variables Identifiers
Assignment
statements
Uninitialized
variables
Output
using cout
Input using
cin
Escape
sequences
Data types Integers
Floating
point
Type char
Class string Type bool
Arithmetic
operators and
expressions
Comments
Naming
constants
Layout of a simple C++ program
Sample Program
 // This is a simple C++ program.
#include <iostream>
using namespace std;
int main()
{
cout<<Welcome to Computer Programming
course;
return 0;
}
遺或鰻意禽
#include<iostream>
 A program includes various programming elements
that are already defined in the standard C++ library.
 In order to use such pre-defined elements in a
program, an appropriate header/directives must be
included in the program.
 Directives always begin with the symbol #.
 <iostream> is the name of a library that contains the
definitions of the routines that handle input from the
keyboard and output to the screen.
 Do not include extra space between the < and the
iostream file name or between the end of the file
name and the closing >.
 using namespace std;
 This line says that the names defined in
iostream are to be interpreted in the
standard way.
 int main()
 It tells that your main part of a program
starts here.
 { }
 Braces mark beginning and end of the
main function.
 return 0;
 The last line in the program. It marks
end of the program.
Variables
 Variable is the basic storage unit in a program. It is
a name given to a memory location.
 The compiler assigns a memory location to each
variable name in the program. The value of the
variable, in a coded form, is kept in the memory
location assigned to that variable.
 We do not know what addresses the compiler will
choose for the variables in our program.
 Data held in a variable is called its value or a literal;
Number/data held by a C++ variable can be
changed.
 A C++ variable is guaranteed to have some value in
it, if only a garbage number left in the computers
memory by some previously run program.
Names: Identifiers
 Identifiers are used as names for variables and
other items in a C++ program.
 To make your program easy to understand, you
should always use meaningful names for variables.
 Rules for naming variables:
 You cannot use a C++ keyword (reserved word)
as a variable name.
 Variable names in C++ can range from 1 to 255
characters.
 All variable names must begin with a letter of
the alphabet (a-z, A-Z) or an underscore( _ ).
遺或鰻意禽
 After the first initial letter, variable names
can also contain letters and numbers.
 No spaces or special characters allowed.
 C++ is case Sensitive. Uppercase characters
are distinct from lowercase characters.
 Examples:
 A, a_1, x123 (legal)
 1ab, da%, 1-2, (not acceptable)
 Test, test, TEST (case-sensitive)
Variable declarations
 Every variable in a C++ program must be declared
before the variable can be used.
 When you declare a variable, you are telling the
compilerand, ultimately, the computerwhat
kind of data you will be storing in the variable, and
what size of memory location to use for the
variable.
 Each declaration ends with a semicolon (;).
 When there is more than one variable in a
declaration, the variables are separated by
commas.
 The kind of data that is held in a variable is called
its type and the name for the type, such as int or
double, is called a type name.
Syntax
 The syntax for a programming languages is the set
of grammar rules for that language.
 The syntax for variable declarations is as follows:
 Syntax
 Type_Name Var_Name_1, Var_Name_2, ...;
 Examples
 int count, sum, number_of_person;
 double distance;
Assignment statements
 In an assignment statement, first the expression
on the right-hand side of the equal sign is
evaluated, and then the variable on the left-hand
side of the equal sign is set equal to this value.
 In an assignment statement, the expression on
the right-hand side of the equal sign can simply
be another variable or a constant.
 Syntax
 Variable = Expression;
 Examples
 sum=a; //variable
 distance = rate * time; //expression
 count=12; //constant
Uninitialized variables
 Variable that has not been given a value is
said to be uninitialized.
 One way to avoid an uninitialized variable
is to initialize variables at the same time
they are declared.
 You can initialize some, all, or none of the
variables in a declaration that lists more
than one variable.
 Examples:
 int count=0; double avg=99.9; int a=10, b,
c=0;
C++ Keywords/Reserved words
Output using cout
 The values of variables as well as strings of text
may be output to the screen using cout.
 The arrow notation << is often called the insertion
operator.
 You can simply list all the items to be output
preceding each item to be output with the arrow
symbols <<.
 Strings must be included in double quotes.
 Examples:
 cout<<This is our first c++ program;
 cout<<The sum is<<sum;
 cout<<distance is<<(time * speed);
Input using cin
 A cin statement sets variables equal to values
typed in at the keyboard.
 cin is a predefined variable that reads data from
the keyboard with the extraction operator (>>).
 Syntax
 cin >> Variable_1 >> Variable_2 >> ... ;
 Example
 cin >> number >> size;
 cin >> time;
Escape sequences
 The backslash, , preceding a character
tells the compiler that the character
following the  does not have the same
meaning as the character appearing by
itself.
 Such a sequence is called an escape
sequence.
遺或鰻意禽
Name Escape
sequence
Description
New line n Cursor moves to next line
Horizontal tab t Cursor moves to next tab stop
Beep a Computer generates a beep
Backslash  Backslash is printed
Single quote  Single quotation mark is printed
Double quote  Double quotation mark is printed
Return r Cursor moves to beginning of
current line
Backspace b Cursor moves one position left
Data Types
 Data types are used to tell the variables the type
of data it can store.
 Whenever a variable is defined in C++, the
compiler allocates some memory for that variable
based on the data-type with which it is declared.
 Every data type requires a different amount of
memory.
Integer types
 The integer data type basically represents whole
numbers (no fractional parts).
 The reason is threefold.
 First, some things in the real world are not
fractional.
 Second, the integer data type is often used to
control program flow by counting.
 Third, integer processing is significantly faster
within the CPU than is floating point processing.
遺或鰻意禽
Floating point types
 The floating-point family of data types represents
number values with fractional parts.
 They are technically stored as two integer values:
a mantissa and an exponent.
 They are always signed.
 A floating_point number can also be a scientific
number with an "e" to indicate the power of 10:
Type char
 Values of the type char are single symbols such
as a letter, digit, or punctuation mark.
 A variable of type char can hold any single
character on the keyboard e.g., A' or '+' or an
'a.
 Note that uppercase and lowercase versions of
a letter are considered different characters.
 The text in double quotes that are output using
cout are called string values.
 Be sure to notice that string constants are
placed inside of double quotes, while constants
of type char are placed inside of single quotes.
Class string
 string class is used to process strings in a manner
similar to the other data types.
 To use the string class we must first include the
string library:
 #include <string>
 You declare variables of type string just as you
declare variables of types int or double.
 string day;
 day = "Monday";
遺或鰻意禽
 You may use cin and cout to read data into
strings.
 You can use + operator between two strings to
concatenate them.
 When you use cin to read input into a string
variable, the computer only reads until it
encounters a whitespace character. Whitespace
characters are all the characters that are
displayed as blank spaces on the screen, including
the blank or space character, the tab character,
and the new-line character 'n. This means that
so far you cannot input a string that contains
spaces.
Type bool
 Expressions of type bool are called Boolean
after the English mathematician George Boole,
who formulated rules for mathematical logic.
 Boolean expressions evaluate to one of the two
values, true or false.
 Boolean expressions are used in branching and
looping statements.
Example
#include <iostream>
using namespace std;
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;
遺或鰻意禽
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;
}
遺或鰻意禽
 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
 The sizeof is a keyword, it is a compile-time
operator that determines the size, in bytes, of a
variable or data type.
 The sizeof operator can be used to get the size
primitive as well as user defined data types.
 The syntax of using sizeof is as follows:
 sizeof (data type)
Example
#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
遺或鰻意禽
Comment
 In C++ the symbols // are used to indicate the start
of a comment.
 All of the text between the // and the end of the
line is a comment.
 The compiler simply ignores anything that follows
// on a line.
 Anything between the symbol pair /* and the
symbol pair */ is considered a comment and is
ignored by the compiler. Unlike the // comments,
/* to */ comments can span several lines,
Naming constants
 When you initialize a variable inside a declaration,
you can mark the variable so that the program is
not allowed to change its value. To do this, place
the word const in front of the declaration, as
described below:
 Syntax
 const Type_Name Variable_Name = Constant;
 Examples
 const int MAX_TRIES = 3;
 const double PI = 3.14159;
setprecision()
 The setprecision function is used to format
floating-point values.
 This is a built function and can be used by
importing the iomanip library in a program.
 By using the setprecision function, we can
get the desired precise value of a floating-
point or a double value by providing the
exact number of decimal places.
遺或鰻意禽
 It can be used to format only the decimal
places instead of the whole floating-point
or double value.
 This can be done using the fixed keyword
before the setprecision() method.
 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)
遺或鰻意禽
#include <iostream> Output
#include <iomanip> Hello
using namespace std;
int main ()
{
cout <<setw(10)<<"Hello"<<endl;
return 0;
}
Class Task
 Write a program that plays the game of Mad Lib.
Your program should prompt the user to enter the
following strings:
 The first or last name of your instructor
 Your name
 A food
 A number between 100 and 120
 An adjective
 A color
 An animal
Contd
 After the strings are input, they should be
substituted into the story below and output to the
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

More Related Content

Similar to THE C++ LECTURE 2 ON DATA STRUCTURES OF C++ (20)

Lecture 2 variables
Lecture 2 variablesLecture 2 variables
Lecture 2 variables
Tony Apreku
programming week 2.ppt
programming week 2.pptprogramming week 2.ppt
programming week 2.ppt
FatimaZafar68
Best_of_438343817-A-PPT-on-C-language.pptx
Best_of_438343817-A-PPT-on-C-language.pptxBest_of_438343817-A-PPT-on-C-language.pptx
Best_of_438343817-A-PPT-on-C-language.pptx
nilaythakkar7
C language
C languageC language
C language
TaranjeetKaur72
C programming language:- Introduction to C Programming - Overview and Importa...
C programming language:- Introduction to C Programming - Overview and Importa...C programming language:- Introduction to C Programming - Overview and Importa...
C programming language:- Introduction to C Programming - Overview and Importa...
SebastianFrancis13
4 Introduction to C.pptxSSSSSSSSSSSSSSSS
4 Introduction to C.pptxSSSSSSSSSSSSSSSS4 Introduction to C.pptxSSSSSSSSSSSSSSSS
4 Introduction to C.pptxSSSSSSSSSSSSSSSS
EG20910848921ISAACDU
CHAPTER 3 STRUCTURED PROGRAMMING.pptx 2024
CHAPTER 3 STRUCTURED PROGRAMMING.pptx 2024CHAPTER 3 STRUCTURED PROGRAMMING.pptx 2024
CHAPTER 3 STRUCTURED PROGRAMMING.pptx 2024
ALPHONCEKIMUYU
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
TAlha MAlik
C tokens.pptx
C tokens.pptxC tokens.pptx
C tokens.pptx
NavyaParashir
Introduction to C
Introduction to CIntroduction to C
Introduction to C
Janani Satheshkumar
C language ppt is a presentation of how to explain the introduction of a c la...
C language ppt is a presentation of how to explain the introduction of a c la...C language ppt is a presentation of how to explain the introduction of a c la...
C language ppt is a presentation of how to explain the introduction of a c la...
sdsharmila11
Chapter02.PPTArray.pptxArray.pptxArray.pptx
Chapter02.PPTArray.pptxArray.pptxArray.pptxChapter02.PPTArray.pptxArray.pptxArray.pptx
Chapter02.PPTArray.pptxArray.pptxArray.pptx
yatakumar84
Variables, identifiers, constants, declaration in c
Variables, identifiers, constants, declaration in cVariables, identifiers, constants, declaration in c
Variables, identifiers, constants, declaration in c
GayathriShiva4
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
Rasan Samarasinghe
Chapter02.PPT
Chapter02.PPTChapter02.PPT
Chapter02.PPT
Chaitanya Jambotkar
Introduction to Problem Solving C Programming
Introduction to Problem Solving C ProgrammingIntroduction to Problem Solving C Programming
Introduction to Problem Solving C Programming
RKarthickCSEKIOT
c programming 2nd chapter pdf.PPT
c programming 2nd chapter pdf.PPTc programming 2nd chapter pdf.PPT
c programming 2nd chapter pdf.PPT
KauserJahan6
A File is a collection of data stored in the secondary memory. So far data wa...
A File is a collection of data stored in the secondary memory. So far data wa...A File is a collection of data stored in the secondary memory. So far data wa...
A File is a collection of data stored in the secondary memory. So far data wa...
bhargavi804095
introduction2_programming slides briefly exolained
introduction2_programming slides briefly exolainedintroduction2_programming slides briefly exolained
introduction2_programming slides briefly exolained
RumaSinha8
Learn C LANGUAGE at ASIT
Learn C LANGUAGE at ASITLearn C LANGUAGE at ASIT
Learn C LANGUAGE at ASIT
ASIT
Lecture 2 variables
Lecture 2 variablesLecture 2 variables
Lecture 2 variables
Tony Apreku
programming week 2.ppt
programming week 2.pptprogramming week 2.ppt
programming week 2.ppt
FatimaZafar68
Best_of_438343817-A-PPT-on-C-language.pptx
Best_of_438343817-A-PPT-on-C-language.pptxBest_of_438343817-A-PPT-on-C-language.pptx
Best_of_438343817-A-PPT-on-C-language.pptx
nilaythakkar7
C programming language:- Introduction to C Programming - Overview and Importa...
C programming language:- Introduction to C Programming - Overview and Importa...C programming language:- Introduction to C Programming - Overview and Importa...
C programming language:- Introduction to C Programming - Overview and Importa...
SebastianFrancis13
4 Introduction to C.pptxSSSSSSSSSSSSSSSS
4 Introduction to C.pptxSSSSSSSSSSSSSSSS4 Introduction to C.pptxSSSSSSSSSSSSSSSS
4 Introduction to C.pptxSSSSSSSSSSSSSSSS
EG20910848921ISAACDU
CHAPTER 3 STRUCTURED PROGRAMMING.pptx 2024
CHAPTER 3 STRUCTURED PROGRAMMING.pptx 2024CHAPTER 3 STRUCTURED PROGRAMMING.pptx 2024
CHAPTER 3 STRUCTURED PROGRAMMING.pptx 2024
ALPHONCEKIMUYU
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
TAlha MAlik
C language ppt is a presentation of how to explain the introduction of a c la...
C language ppt is a presentation of how to explain the introduction of a c la...C language ppt is a presentation of how to explain the introduction of a c la...
C language ppt is a presentation of how to explain the introduction of a c la...
sdsharmila11
Chapter02.PPTArray.pptxArray.pptxArray.pptx
Chapter02.PPTArray.pptxArray.pptxArray.pptxChapter02.PPTArray.pptxArray.pptxArray.pptx
Chapter02.PPTArray.pptxArray.pptxArray.pptx
yatakumar84
Variables, identifiers, constants, declaration in c
Variables, identifiers, constants, declaration in cVariables, identifiers, constants, declaration in c
Variables, identifiers, constants, declaration in c
GayathriShiva4
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
Rasan Samarasinghe
Introduction to Problem Solving C Programming
Introduction to Problem Solving C ProgrammingIntroduction to Problem Solving C Programming
Introduction to Problem Solving C Programming
RKarthickCSEKIOT
c programming 2nd chapter pdf.PPT
c programming 2nd chapter pdf.PPTc programming 2nd chapter pdf.PPT
c programming 2nd chapter pdf.PPT
KauserJahan6
A File is a collection of data stored in the secondary memory. So far data wa...
A File is a collection of data stored in the secondary memory. So far data wa...A File is a collection of data stored in the secondary memory. So far data wa...
A File is a collection of data stored in the secondary memory. So far data wa...
bhargavi804095
introduction2_programming slides briefly exolained
introduction2_programming slides briefly exolainedintroduction2_programming slides briefly exolained
introduction2_programming slides briefly exolained
RumaSinha8
Learn C LANGUAGE at ASIT
Learn C LANGUAGE at ASITLearn C LANGUAGE at ASIT
Learn C LANGUAGE at ASIT
ASIT

Recently uploaded (20)

CNC Technology Unit-5 for IV Year 24-25 MECH
CNC Technology Unit-5 for IV Year 24-25 MECHCNC Technology Unit-5 for IV Year 24-25 MECH
CNC Technology Unit-5 for IV Year 24-25 MECH
C Sai Kiran
Distillation Types & It's Applications 1-Mar-2025.pptx
Distillation Types & It's Applications 1-Mar-2025.pptxDistillation Types & It's Applications 1-Mar-2025.pptx
Distillation Types & It's Applications 1-Mar-2025.pptx
mrcr123
windrose1.ppt for seminar of civil .pptx
windrose1.ppt for seminar of civil .pptxwindrose1.ppt for seminar of civil .pptx
windrose1.ppt for seminar of civil .pptx
nukeshpandey5678
UHV Unit - 4 HARMONY IN THE NATURE AND EXISTENCE.pptx
UHV Unit - 4 HARMONY IN THE NATURE AND EXISTENCE.pptxUHV Unit - 4 HARMONY IN THE NATURE AND EXISTENCE.pptx
UHV Unit - 4 HARMONY IN THE NATURE AND EXISTENCE.pptx
ariomthermal2031
LA2-64 -bit assemby language program to count number of positive and negative...
LA2-64 -bit assemby language program to count number of positive and negative...LA2-64 -bit assemby language program to count number of positive and negative...
LA2-64 -bit assemby language program to count number of positive and negative...
VidyaAshokNemade
Explainability and Transparency in Artificial Intelligence: Ethical Imperativ...
Explainability and Transparency in Artificial Intelligence: Ethical Imperativ...Explainability and Transparency in Artificial Intelligence: Ethical Imperativ...
Explainability and Transparency in Artificial Intelligence: Ethical Imperativ...
AI Publications
PLANT CELL REACTORS presenation PTC amity
PLANT CELL REACTORS presenation PTC amityPLANT CELL REACTORS presenation PTC amity
PLANT CELL REACTORS presenation PTC amity
UrjaMoon
Production Planning & Control and Inventory Management.pptx
Production Planning & Control and Inventory Management.pptxProduction Planning & Control and Inventory Management.pptx
Production Planning & Control and Inventory Management.pptx
VirajPasare
Artificial intelligence and Machine learning in remote sensing and GIS
Artificial intelligence  and Machine learning in remote sensing and GISArtificial intelligence  and Machine learning in remote sensing and GIS
Artificial intelligence and Machine learning in remote sensing and GIS
amirthamm2083
PROJECT REPORT ON PASTA MACHINE - KP AUTOMATIONS - PASTA MAKING MACHINE PROJE...
PROJECT REPORT ON PASTA MACHINE - KP AUTOMATIONS - PASTA MAKING MACHINE PROJE...PROJECT REPORT ON PASTA MACHINE - KP AUTOMATIONS - PASTA MAKING MACHINE PROJE...
PROJECT REPORT ON PASTA MACHINE - KP AUTOMATIONS - PASTA MAKING MACHINE PROJE...
yadavchandan322
LA11-Case study of motherboard and internal components of motheroard.docx
LA11-Case study of motherboard and internal components of motheroard.docxLA11-Case study of motherboard and internal components of motheroard.docx
LA11-Case study of motherboard and internal components of motheroard.docx
VidyaAshokNemade
UHV unit-2UNIT - II HARMONY IN THE HUMAN BEING.pptx
UHV unit-2UNIT - II HARMONY IN THE HUMAN BEING.pptxUHV unit-2UNIT - II HARMONY IN THE HUMAN BEING.pptx
UHV unit-2UNIT - II HARMONY IN THE HUMAN BEING.pptx
ariomthermal2031
UHV UNIT-I INTRODUCTION TO VALUE EDUCATION .pptx
UHV UNIT-I INTRODUCTION TO VALUE EDUCATION  .pptxUHV UNIT-I INTRODUCTION TO VALUE EDUCATION  .pptx
UHV UNIT-I INTRODUCTION TO VALUE EDUCATION .pptx
ariomthermal2031
sensors utilized in agro meteorology sdes
sensors utilized in agro meteorology sdessensors utilized in agro meteorology sdes
sensors utilized in agro meteorology sdes
Jenitha Rajadurai
Optimize AI Latency & Response Time with LLumo
Optimize AI Latency & Response Time with LLumoOptimize AI Latency & Response Time with LLumo
Optimize AI Latency & Response Time with LLumo
sgupta86
Industry 4.0: Transforming Modern Manufacturing and Beyond
Industry 4.0: Transforming Modern Manufacturing and BeyondIndustry 4.0: Transforming Modern Manufacturing and Beyond
Industry 4.0: Transforming Modern Manufacturing and Beyond
GtxDriver
CNC Technology Unit-4 for IV Year 24-25 MECH
CNC Technology Unit-4 for IV Year 24-25 MECHCNC Technology Unit-4 for IV Year 24-25 MECH
CNC Technology Unit-4 for IV Year 24-25 MECH
C Sai Kiran
Airport Components Part1 ppt.pptx-Site layout,RUNWAY,TAXIWAY,TAXILANE
Airport Components Part1 ppt.pptx-Site layout,RUNWAY,TAXIWAY,TAXILANEAirport Components Part1 ppt.pptx-Site layout,RUNWAY,TAXIWAY,TAXILANE
Airport Components Part1 ppt.pptx-Site layout,RUNWAY,TAXIWAY,TAXILANE
Priyanka Dange
Analysis of Daylighting in Interior Spaces using the Daylight Factor - A Manu...
Analysis of Daylighting in Interior Spaces using the Daylight Factor - A Manu...Analysis of Daylighting in Interior Spaces using the Daylight Factor - A Manu...
Analysis of Daylighting in Interior Spaces using the Daylight Factor - A Manu...
Ignacio J. J. Palma Carazo
Self-Compacting Concrete: Composition, Properties, and Applications in Modern...
Self-Compacting Concrete: Composition, Properties, and Applications in Modern...Self-Compacting Concrete: Composition, Properties, and Applications in Modern...
Self-Compacting Concrete: Composition, Properties, and Applications in Modern...
NIT SILCHAR
CNC Technology Unit-5 for IV Year 24-25 MECH
CNC Technology Unit-5 for IV Year 24-25 MECHCNC Technology Unit-5 for IV Year 24-25 MECH
CNC Technology Unit-5 for IV Year 24-25 MECH
C Sai Kiran
Distillation Types & It's Applications 1-Mar-2025.pptx
Distillation Types & It's Applications 1-Mar-2025.pptxDistillation Types & It's Applications 1-Mar-2025.pptx
Distillation Types & It's Applications 1-Mar-2025.pptx
mrcr123
windrose1.ppt for seminar of civil .pptx
windrose1.ppt for seminar of civil .pptxwindrose1.ppt for seminar of civil .pptx
windrose1.ppt for seminar of civil .pptx
nukeshpandey5678
UHV Unit - 4 HARMONY IN THE NATURE AND EXISTENCE.pptx
UHV Unit - 4 HARMONY IN THE NATURE AND EXISTENCE.pptxUHV Unit - 4 HARMONY IN THE NATURE AND EXISTENCE.pptx
UHV Unit - 4 HARMONY IN THE NATURE AND EXISTENCE.pptx
ariomthermal2031
LA2-64 -bit assemby language program to count number of positive and negative...
LA2-64 -bit assemby language program to count number of positive and negative...LA2-64 -bit assemby language program to count number of positive and negative...
LA2-64 -bit assemby language program to count number of positive and negative...
VidyaAshokNemade
Explainability and Transparency in Artificial Intelligence: Ethical Imperativ...
Explainability and Transparency in Artificial Intelligence: Ethical Imperativ...Explainability and Transparency in Artificial Intelligence: Ethical Imperativ...
Explainability and Transparency in Artificial Intelligence: Ethical Imperativ...
AI Publications
PLANT CELL REACTORS presenation PTC amity
PLANT CELL REACTORS presenation PTC amityPLANT CELL REACTORS presenation PTC amity
PLANT CELL REACTORS presenation PTC amity
UrjaMoon
Production Planning & Control and Inventory Management.pptx
Production Planning & Control and Inventory Management.pptxProduction Planning & Control and Inventory Management.pptx
Production Planning & Control and Inventory Management.pptx
VirajPasare
Artificial intelligence and Machine learning in remote sensing and GIS
Artificial intelligence  and Machine learning in remote sensing and GISArtificial intelligence  and Machine learning in remote sensing and GIS
Artificial intelligence and Machine learning in remote sensing and GIS
amirthamm2083
PROJECT REPORT ON PASTA MACHINE - KP AUTOMATIONS - PASTA MAKING MACHINE PROJE...
PROJECT REPORT ON PASTA MACHINE - KP AUTOMATIONS - PASTA MAKING MACHINE PROJE...PROJECT REPORT ON PASTA MACHINE - KP AUTOMATIONS - PASTA MAKING MACHINE PROJE...
PROJECT REPORT ON PASTA MACHINE - KP AUTOMATIONS - PASTA MAKING MACHINE PROJE...
yadavchandan322
LA11-Case study of motherboard and internal components of motheroard.docx
LA11-Case study of motherboard and internal components of motheroard.docxLA11-Case study of motherboard and internal components of motheroard.docx
LA11-Case study of motherboard and internal components of motheroard.docx
VidyaAshokNemade
UHV unit-2UNIT - II HARMONY IN THE HUMAN BEING.pptx
UHV unit-2UNIT - II HARMONY IN THE HUMAN BEING.pptxUHV unit-2UNIT - II HARMONY IN THE HUMAN BEING.pptx
UHV unit-2UNIT - II HARMONY IN THE HUMAN BEING.pptx
ariomthermal2031
UHV UNIT-I INTRODUCTION TO VALUE EDUCATION .pptx
UHV UNIT-I INTRODUCTION TO VALUE EDUCATION  .pptxUHV UNIT-I INTRODUCTION TO VALUE EDUCATION  .pptx
UHV UNIT-I INTRODUCTION TO VALUE EDUCATION .pptx
ariomthermal2031
sensors utilized in agro meteorology sdes
sensors utilized in agro meteorology sdessensors utilized in agro meteorology sdes
sensors utilized in agro meteorology sdes
Jenitha Rajadurai
Optimize AI Latency & Response Time with LLumo
Optimize AI Latency & Response Time with LLumoOptimize AI Latency & Response Time with LLumo
Optimize AI Latency & Response Time with LLumo
sgupta86
Industry 4.0: Transforming Modern Manufacturing and Beyond
Industry 4.0: Transforming Modern Manufacturing and BeyondIndustry 4.0: Transforming Modern Manufacturing and Beyond
Industry 4.0: Transforming Modern Manufacturing and Beyond
GtxDriver
CNC Technology Unit-4 for IV Year 24-25 MECH
CNC Technology Unit-4 for IV Year 24-25 MECHCNC Technology Unit-4 for IV Year 24-25 MECH
CNC Technology Unit-4 for IV Year 24-25 MECH
C Sai Kiran
Airport Components Part1 ppt.pptx-Site layout,RUNWAY,TAXIWAY,TAXILANE
Airport Components Part1 ppt.pptx-Site layout,RUNWAY,TAXIWAY,TAXILANEAirport Components Part1 ppt.pptx-Site layout,RUNWAY,TAXIWAY,TAXILANE
Airport Components Part1 ppt.pptx-Site layout,RUNWAY,TAXIWAY,TAXILANE
Priyanka Dange
Analysis of Daylighting in Interior Spaces using the Daylight Factor - A Manu...
Analysis of Daylighting in Interior Spaces using the Daylight Factor - A Manu...Analysis of Daylighting in Interior Spaces using the Daylight Factor - A Manu...
Analysis of Daylighting in Interior Spaces using the Daylight Factor - A Manu...
Ignacio J. J. Palma Carazo
Self-Compacting Concrete: Composition, Properties, and Applications in Modern...
Self-Compacting Concrete: Composition, Properties, and Applications in Modern...Self-Compacting Concrete: Composition, Properties, and Applications in Modern...
Self-Compacting Concrete: Composition, Properties, and Applications in Modern...
NIT SILCHAR

THE C++ LECTURE 2 ON DATA STRUCTURES OF C++

  • 1. Variables, Data types and Input/output constructs Lecture # 2 Course Instructor: Dr. Afshan Jamil
  • 2. Outline Layout of simple ++ program Variables Identifiers Assignment statements Uninitialized variables Output using cout Input using cin Escape sequences Data types Integers Floating point Type char Class string Type bool Arithmetic operators and expressions Comments Naming constants
  • 3. Layout of a simple C++ program
  • 4. Sample Program // This is a simple C++ program. #include <iostream> using namespace std; int main() { cout<<Welcome to Computer Programming course; return 0; }
  • 5. 遺或鰻意禽 #include<iostream> A program includes various programming elements that are already defined in the standard C++ library. In order to use such pre-defined elements in a program, an appropriate header/directives must be included in the program. Directives always begin with the symbol #. <iostream> is the name of a library that contains the definitions of the routines that handle input from the keyboard and output to the screen. Do not include extra space between the < and the iostream file name or between the end of the file name and the closing >.
  • 6. using namespace std; This line says that the names defined in iostream are to be interpreted in the standard way. int main() It tells that your main part of a program starts here. { } Braces mark beginning and end of the main function. return 0; The last line in the program. It marks end of the program.
  • 7. Variables Variable is the basic storage unit in a program. It is a name given to a memory location. The compiler assigns a memory location to each variable name in the program. The value of the variable, in a coded form, is kept in the memory location assigned to that variable. We do not know what addresses the compiler will choose for the variables in our program. Data held in a variable is called its value or a literal; Number/data held by a C++ variable can be changed. A C++ variable is guaranteed to have some value in it, if only a garbage number left in the computers memory by some previously run program.
  • 8. Names: Identifiers Identifiers are used as names for variables and other items in a C++ program. To make your program easy to understand, you should always use meaningful names for variables. Rules for naming variables: You cannot use a C++ keyword (reserved word) as a variable name. Variable names in C++ can range from 1 to 255 characters. All variable names must begin with a letter of the alphabet (a-z, A-Z) or an underscore( _ ).
  • 9. 遺或鰻意禽 After the first initial letter, variable names can also contain letters and numbers. No spaces or special characters allowed. C++ is case Sensitive. Uppercase characters are distinct from lowercase characters. Examples: A, a_1, x123 (legal) 1ab, da%, 1-2, (not acceptable) Test, test, TEST (case-sensitive)
  • 10. Variable declarations Every variable in a C++ program must be declared before the variable can be used. When you declare a variable, you are telling the compilerand, ultimately, the computerwhat kind of data you will be storing in the variable, and what size of memory location to use for the variable. Each declaration ends with a semicolon (;). When there is more than one variable in a declaration, the variables are separated by commas. The kind of data that is held in a variable is called its type and the name for the type, such as int or double, is called a type name.
  • 11. Syntax The syntax for a programming languages is the set of grammar rules for that language. The syntax for variable declarations is as follows: Syntax Type_Name Var_Name_1, Var_Name_2, ...; Examples int count, sum, number_of_person; double distance;
  • 12. Assignment statements In an assignment statement, first the expression on the right-hand side of the equal sign is evaluated, and then the variable on the left-hand side of the equal sign is set equal to this value. In an assignment statement, the expression on the right-hand side of the equal sign can simply be another variable or a constant. Syntax Variable = Expression; Examples sum=a; //variable distance = rate * time; //expression count=12; //constant
  • 13. Uninitialized variables Variable that has not been given a value is said to be uninitialized. One way to avoid an uninitialized variable is to initialize variables at the same time they are declared. You can initialize some, all, or none of the variables in a declaration that lists more than one variable. Examples: int count=0; double avg=99.9; int a=10, b, c=0;
  • 15. Output using cout The values of variables as well as strings of text may be output to the screen using cout. The arrow notation << is often called the insertion operator. You can simply list all the items to be output preceding each item to be output with the arrow symbols <<. Strings must be included in double quotes. Examples: cout<<This is our first c++ program; cout<<The sum is<<sum; cout<<distance is<<(time * speed);
  • 16. Input using cin A cin statement sets variables equal to values typed in at the keyboard. cin is a predefined variable that reads data from the keyboard with the extraction operator (>>). Syntax cin >> Variable_1 >> Variable_2 >> ... ; Example cin >> number >> size; cin >> time;
  • 17. Escape sequences The backslash, , preceding a character tells the compiler that the character following the does not have the same meaning as the character appearing by itself. Such a sequence is called an escape sequence.
  • 18. 遺或鰻意禽 Name Escape sequence Description New line n Cursor moves to next line Horizontal tab t Cursor moves to next tab stop Beep a Computer generates a beep Backslash Backslash is printed Single quote Single quotation mark is printed Double quote Double quotation mark is printed Return r Cursor moves to beginning of current line Backspace b Cursor moves one position left
  • 19. Data Types Data types are used to tell the variables the type of data it can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data-type with which it is declared. Every data type requires a different amount of memory.
  • 20. Integer types The integer data type basically represents whole numbers (no fractional parts). The reason is threefold. First, some things in the real world are not fractional. Second, the integer data type is often used to control program flow by counting. Third, integer processing is significantly faster within the CPU than is floating point processing.
  • 22. Floating point types The floating-point family of data types represents number values with fractional parts. They are technically stored as two integer values: a mantissa and an exponent. They are always signed. A floating_point number can also be a scientific number with an "e" to indicate the power of 10:
  • 23. Type char Values of the type char are single symbols such as a letter, digit, or punctuation mark. A variable of type char can hold any single character on the keyboard e.g., A' or '+' or an 'a. Note that uppercase and lowercase versions of a letter are considered different characters. The text in double quotes that are output using cout are called string values. Be sure to notice that string constants are placed inside of double quotes, while constants of type char are placed inside of single quotes.
  • 24. Class string string class is used to process strings in a manner similar to the other data types. To use the string class we must first include the string library: #include <string> You declare variables of type string just as you declare variables of types int or double. string day; day = "Monday";
  • 25. 遺或鰻意禽 You may use cin and cout to read data into strings. You can use + operator between two strings to concatenate them. When you use cin to read input into a string variable, the computer only reads until it encounters a whitespace character. Whitespace characters are all the characters that are displayed as blank spaces on the screen, including the blank or space character, the tab character, and the new-line character 'n. This means that so far you cannot input a string that contains spaces.
  • 26. Type bool Expressions of type bool are called Boolean after the English mathematician George Boole, who formulated rules for mathematical logic. Boolean expressions evaluate to one of the two values, true or false. Boolean expressions are used in branching and looping statements.
  • 27. Example #include <iostream> using namespace std; 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;
  • 28. 遺或鰻意禽 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; }
  • 29. 遺或鰻意禽 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
  • 30. sizeof() Function The sizeof is a keyword, it is a compile-time operator that determines the size, in bytes, of a variable or data type. The sizeof operator can be used to get the size primitive as well as user defined data types. The syntax of using sizeof is as follows: sizeof (data type)
  • 31. Example #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; }
  • 32. 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.
  • 35. Comment In C++ the symbols // are used to indicate the start of a comment. All of the text between the // and the end of the line is a comment. The compiler simply ignores anything that follows // on a line. Anything between the symbol pair /* and the symbol pair */ is considered a comment and is ignored by the compiler. Unlike the // comments, /* to */ comments can span several lines,
  • 36. Naming constants When you initialize a variable inside a declaration, you can mark the variable so that the program is not allowed to change its value. To do this, place the word const in front of the declaration, as described below: Syntax const Type_Name Variable_Name = Constant; Examples const int MAX_TRIES = 3; const double PI = 3.14159;
  • 37. setprecision() The setprecision function is used to format floating-point values. This is a built function and can be used by importing the iomanip library in a program. By using the setprecision function, we can get the desired precise value of a floating- point or a double value by providing the exact number of decimal places.
  • 38. 遺或鰻意禽 It can be used to format only the decimal places instead of the whole floating-point or double value. This can be done using the fixed keyword before the setprecision() method. Syntax setprecision(number)
  • 39. 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; }
  • 40. 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)
  • 41. 遺或鰻意禽 #include <iostream> Output #include <iomanip> Hello using namespace std; int main () { cout <<setw(10)<<"Hello"<<endl; return 0; }
  • 42. Class Task Write a program that plays the game of Mad Lib. Your program should prompt the user to enter the following strings: The first or last name of your instructor Your name A food A number between 100 and 120 An adjective A color An animal
  • 43. Contd After the strings are input, they should be substituted into the story below and output to the 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]