0% found this document useful (0 votes)
31 views44 pages

Lecture # 2

This document discusses variables, data types, and input/output constructs in C++. It covers topics such as variables and identifiers, data types including integers, floating point, characters, strings, and Booleans. It also discusses input using cin, output using cout, and escape sequences. The document provides examples of declaring and initializing variables, assigning values, and performing input and output of different data types.

Uploaded by

Amaim Fatima
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views44 pages

Lecture # 2

This document discusses variables, data types, and input/output constructs in C++. It covers topics such as variables and identifiers, data types including integers, floating point, characters, strings, and Booleans. It also discusses input using cin, output using cout, and escape sequences. The document provides examples of declaring and initializing variables, assigning values, and performing input and output of different data types.

Uploaded by

Amaim Fatima
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Variables, Data types

and Input/output
constructs

Lecture # 2
Course Instructor:
Dr. Afshan Jamil
Outline
Layout of
Assignment
simple ++ Variables Identifiers
statements
program

Uninitialized Output Input using Escape


variables using cout cin sequences

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

• // 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
CONTD… 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 computer’s
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( _ ).
CONTD…
• 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
compiler—and, ultimately, the computer—what
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.
CONTD…
Name Escape Description
sequence
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.
CONTD…
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";
CONTD…
• 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;
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

• 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
CONTD…
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.
CONTD…
• 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)
CONTD…

#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
• After the strings are input, they should be
substituted into the story below and output to the

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

You might also like