0% found this document useful (0 votes)
13 views55 pages

PF Lecture (Theory) 02-Variables

Uploaded by

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

PF Lecture (Theory) 02-Variables

Uploaded by

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

Programming Fundamentals

C++
Review

#include<iostream> • The Output is


using namespace std;
int main()
{ ???
cout<<“Hello World”;
cout<<“Computer Program”;
cout<<“Bye”;
return 0;
}
Review

#include<iostream>
using namespace std;
int main()
• When we add endl output
{
will be
cout<<“Hello World”<<endl;
cout<<“Computer Program” <<endl; ???
cout<<“Bye” <<endl;
return 0;
}
endl
• Inserts a new-line character.
Variables
Variable

“A variable is a value that can change any


time. It is a memory location used to store a
data value.”
Rules for constructing Variable
Name
I. A variable name is any combination of 1 to 31
• Alphabets (A-Z or a-z), digits(0-9) or underscores(_).
• Some compilers allow variable names whose length
could be up to 247 characters. Still, it would be safer
to stick to the rule of 31 characters. Do not create
unnecessarily long variable names as it adds to your
typing effort.
II. The first character in the variable name must be
an alphabet or underscore.
III. No commas or blanks are allowed within a
variable name.
Valid or Invalid Variable name ?

Variable Name Valid/Invalid


12sal Invalid
sal12 Valid
A_12 Valid
#a12 Invalid
a 12 Invalid
_a Valid
_pr Valid
abc_ Valid
n123 Valid
val_786 Valid
Case sensitive

• Variable names are case sensitive, which specifies that


each letter of a word or term must be typed exactly as
required or shown-as a capital (upper-case) letter or a
common (lower case) letter.

• It means all the given variables are different

• Sal
• sal
• saL
• SAL
• SaL
Variable Declaration

• Variables must be declared before they can be used.


• Variable can contain integer, real or character constants.
• Data Type are used to define the type of a variable before its use.
• int
• float
• double
• char
• Modifiers---The three data types above have the following
modifiers.
• short
• long
• signed
• unsigned
Integer types

Type Storage size Value range


char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
-32,768 to 32,767 or -
int 2 or 4 bytes
2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
Floating point types

Type Storage size Value range Precision

float 4 byte 1.2E-38 to 3.4E+38 6 decimal places

double 8 byte 2.3E-308 to 1.7E+308 15 decimal places

long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places


why we declare variables
before hand?
Declaring a variable serves two purposes
• C++ knows what data type the variable is,
• C++ reserves space for the data
Declaration of Variables
Integer-Data Type float - data type
int is used to define integer float is used to define floating point
numbers. numbers.

int Count; float Miles;

char - data type double - data type


char defines characters. double is used to define BIG floating
point numbers
char Letter;
double Atoms;
Variable Initialization
• Giving value to the variable
• we have to explicitly initialize the variables we create
Declaration and initialization of
Variables
Integer-Data Type float - data type
int is used to define integer numbers. float is used to define floating point
numbers.
int Count;
Count=5; float Miles;
Miles=7.5;

char - data type double - data type


char defines characters. double is used to define BIG floating
point numbers
char Letter;
Letter=‘X’; double Atoms;
Atoms=7.345566;
Type Declaration Instruction
• To declare the type of variables used in a program.
• The type declaration statement is written at the beginning of main( ) function.
• Any variable used in the program must be declared before using it in any statement.
• For example
• int bas ;
• float rs, grosssal ;
• char name, code ;
variations of the type declaration
instruction
1. While declaring the type of variable we can also initialize it as shown
below.
int i = 10, j = 25 ;
float a = 1.5, b = 1.99 + 2.4 * 1.44 ;
variations of the type declaration
instruction
2. The order in which we define variables is sometimes important sometimes not

int i = 10, j = 25 ;
is same as
int j = 25, i = 10 ;
However,
float a = 1.5, b = a + 3.1 ;
is alright, but
float b = a + 3.1, a = 1.5 ;
is not. This is because here we are trying to use a even before defining it.
variations of the type declaration
instruction
3. The following statements would work
int a, b, c, d ;
a = b = c = 10 ;
However, the following statement would not work
int a = b = c = d = 10 ;
Once again we are trying to use b (to assign to a) before defining it.
Output Function and Variables
#include<iostream>
using namespace std;
int main()
{
int num=5;
cout<<num;
return 0;
}
Think the output

• Following are some examples of usage of output function:


float si=7.5,r=7.8;
int p=5;
cout<<si;
cout<<p<<si;
• The format string may also contain any other characters.
cout<< "Simple interest = Rs. “<<si<<endl;
cout<< "Prin = "<<p<< r<<endl;
Expression Printing
• Output function can not only print values of variables, it can also
print the result of an expression. An expression is nothing but a valid
combination of constants, variables and operators.

cout<<a + b * c – d ;
Review

#include<iostream> • The Output is


using namespace std;
int main() ???
{
int age=24;
cout<<“My age is ”<<age<<endl;
return 0;
}
Standard Input Output in
C++ & Errors
Lecture 05
Input / Output Operations
 Input operation
 an instruction that copies data from an input device
into memory.
 Input Stream: A stream ( numbers, characters,
strings..etc) that flows from an input device ( i.e.:
keyboard, disk drive, network connection) to main
memory.
 Output operation
 an instruction that displays information stored in
memory to the output devices (such as the monitor)
 Output Stream: A stream that flows from main
memory to an output device ( i.e.: screen, printer, disk
drive, network connection)
Using iostream
• The C++ iostream library provides hundreds of I/O capabilities.
• Standard iostream objects:
cout - object providing a connection to the monitor
cin - object providing a connection to the keyboard
• To perform input and output we send messages to one of these
objects
Input Stream
The Extraction Operator
(>>)
• To get input from the keyboard we use the extraction operator and the
object cin
• Format: cin >> Variable;
• The compiler figures out the type of the variable and reads in the
appropriate type
int X;
float Y;
cin >> X; // Reads in an integer
cin >> Y; // Reads in a float
Syntax
cin >> someVariable;
• cin knows what type of data is to be assigned to
someVariable (based on the type of someVariable).
Stream Input
• >> (stream-extraction)
• Used to perform stream input
• Normally ignores whitespaces (spaces, tabs, newlines) in the input
stream.
• Returns zero (false) when EOF(End of File) is encountered,
otherwise returns reference to the object from which it was invoked (i.e.
cin)
• This enables cascaded input
cin >> x >> y;
Stream Input

• cin inputs ints, chars, null-terminated strings, string objects


• but terminates when encounters space (ASCII character 32)
Chaining Calls
• Multiple uses of the insertion and extraction operator can be chained
together:
cout << E1 << E2 << E3 << … ;
cin >> V1 >> V2 >> V3 >> …;
• Equivalent to performing the set of insertion or extraction operators
one at a time
• Example
cout << “Total sales are $” << sales << ‘\n’;
cin >> Sales1 >> Sales2 >> Sales3;
Extraction/Insertion Example
cout << “Hello world! ”;
int i=5;
cout << “The value of i is “ << i << endl;
OUTPUT:
Hello World! The value of i is 5 //endl puts a new line

char letter;
cout << “Please enter the first letter of your name: “;
cin >> letter;
cout<< “Your name starts with “ << letter;
OUTPUT:
Please enter the first letter of your name: F
Your name starts with F
Output Stream
The Insertion Operator (<<)
• To send output to the screen we use the insertion
operator on the object cout
• Format: cout << Expression;
• The compiler figures out the type of the object and
prints it out appropriately
cout << 5; // Outputs 5
cout << 4.1; // Outputs 4.1
cout << “String”; // Outputs String
cout << ‘\n’; // Outputs a newline
Stream-Insertion Operator
• << is overloaded to output built-in types ( ex. int, float,…etc)
• Can also be used to output user-defined types (i.e., user-defined classes).
• cout << ‘\n’;
• Prints newline character
• cout << endl;
• endl is a stream manipulator that issues a newline character and flushes the output
buffer
• cout << flush;
• flush flushes the output buffer

a buffer is just a pre-allocated area of memory where you store your data
while you're processing it.
Cascading Stream-Insertion Operators

• << : Associates from left to right, and returns a reference to its left-operand
object (i.e. cout).
• This enables cascading
cout << "How" << " are" << " you?";

Make sure to use parenthesis:

cout << "1 + 2 = " << (1 + 2);

NOT

cout << "1 + 2 = " << 1 + 2;


Printing Variables
• cout << someVariable;
• cout knows the type of data to output
• Must not confuse printing text with printing
variables:
• int x =12;
• cout << x; // prints 12
• cout << “x”; // prints x
Formatting Stream Output

 Performs formatted and unformatted output


I. Display numbers on different width , filling spaces with Varying precision for
floating points
II. Formatted text outputs
Significant Digits in Float
If the fixed point format is not specified, the precision field specifies the maximum
number of digits to be displayed in total counting both those before and those
after the decimal point. (may convert from fixed to scientific to print):

float y = 23.1415;
cout.precision(2);
cout << y << '\n'; // Outputs 23
cout.precision(3);
cout << y << '\n'; // Outputs 23.1
Using
showpoint/noshowpoint
• showpoint specify that floating-point numbers (even for whole
numbers) should be output with a decimal point, even if they’re zeros.
Following the decimal point, as many digits as necessary are written to
match the precision.
• This setting is reset with stream manipulator noshowpoint.
• When the showpoint manipulator is not set, the decimal point is only
written for non-whole numbers.
Using showpoint/noshowpoint

#include <iostream>
using namespace std; 30.000 10000. 3.1416
int main () { 30 10000 3.1416
double a, b, pi;
a=30.0;
b=10000.0;
pi=3.14165;
cout.precision (5);
cout << showpoint << a << '\t' << b << '\t' << pi << endl;
cout << noshowpoint << a << '\t' << b << '\t' << pi << endl;
return 0;
}
Formatting Text
• To print text you need to include “” around the text
• Cout <<“This is a Beautiful Day” ;
• You can add escape sequence for further options.
Escape Sequence
Examples

cout<<"Please enter the student's grades:”;


Please enter the student's grades:

cout<<"The class average is “<< average;


Average = 95.5
The class average is 95.5

cout<<“The total area is “<< area<< “and the total cost is “<< cost << “ S.R.”; area = 60.2
The total area is 60.2 and the total cost is 4530 S.R. cost = 4530

Cout<<"The student received an ”<< grade << “ grade in the course.";


grade = ‘A’
The student received an A grade in the course.
Examples (Con.)

Cout<<”The grade is << grade << gradesymb; grade = ‘A’


The grade is A+
gradesymb = ‘+’

Cout<<"I am the first line\n”;


Cout<<“\n I am the second line\n";
I am the first line
I am the second line
Cascading Stream-Insertion Operators

• Allows creating a single output statement that prints 1


or more type of data
e.g. (1)
.e.g
int age=25; ;int age=25
cout<<“Sarah is “<<age<<“Years Old”; ;“ cout<<“Sarah is
;cout<<age
;”cout<<“Years Old
Compilers start printing from left to right Compilers start printing from top to down
Output for both

Sarah is 25 Years Old


Quick Review

Terms Meaning
• Input Stream • cin
• Output Stream • cout
• Insertion Operation • <<
• Extraction Operator • >>
• Cascading • Adding more than 1 elements
Common Programming
Errors
Errors

• An error is something you have done which is considered to be


incorrect or wrong, or which should not have been done.

Types of
Error

Syntax Run-time Logical


Error Error Error

• Debugging  Process removing errors from a program


Syntax Error

• A violation of the C++ grammar rules, detected during


program translation (compilation).
• Statement cannot be translated, and program cannot be
executed
Run Time Error
• An attempt to perform an invalid operation, detected
during program execution.
• Occurs when the program directs the computer to
perform an illegal operation, such as dividing a number
by zero.
• The computer will stop executing the program, and
displays a diagnostic message indicates the line where
the error was detected
Logic Error /Design Error
• An error caused by following an incorrect algorithm
• Very difficult to detect - it does not cause run-time error
and does not display message errors.
• The only sign of logic error – incorrect program output
• Can be detected by testing the program thoroughly,
comparing its output to calculated results
• To prevent – carefully desk checking the algorithm and
written program before you actually type it
Thank You 

You might also like