Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 63

Introduction & Overview

of Programming

Introduction
Programming Basics
History & Evolution

Designed & Authored by, Mrs. Neelu J Ahuja,


Sr. Lecturer, Dept of IT & Computer Sciences
Introduction to Programming
Logic

 A program logic is a way of representing the


theory behind a program's actions.
 A computer cannot understand the words
spoken by us, and this warrants the need of a
language, which can prompt the machine to
carry the functions we desire.
 The pursuit of developing the perfect computer
language, which started from the simple
punched cards and algorithms, has taken a
whole new dimension today.
Programs………

 The present day computer languages are


immensely capable in making the computer
perform varied tasks in fields like art,
engineering, medical science etc.
 A program is set of coded instructions that
enable a machine, especially a computer, to
perform a desired sequence of operations.
 Thus programming languages deal with such
sets of instructions or algorithms, which can be
customized according to the output, we desire
from the computer.
Steps to Write Programs…

 Algorithms- objective and approach to the


problem written in simple English. Algorithm
written in simple English is called Pseudo code.
 Flow charts- pictorial representation of the
algorithm to understand the transfer of
execution of program.
 Coding- actual lines of a program and is
strictly in accordance with the syntax of the
language.
e.g to prove that (a+b)2 = a2+b2+2ab.
Algorithm.
LHS
 Step 1: add ‘a’, ‘b’ and square the sum.
 Step 2: store that value as ‘d’.

RHS

 Step 3: square ‘a’, ‘b’, mulitply ‘2’,‘a’ and ‘b’, add all
the three values.
 Store that value as ‘e’.

 COMPARISON

 Check if ‘d’ equals ‘e’, if yes print “proved”, else “not


equal”.
Showing the Flowchart
start Input a, b D =(a+b)^2

If D = E E= a^2+b^2+2*a*b

Yes Print “proved”


stop

no
Print “not equal”
Pseudocode
 Pseudo code is a kind of structured English for
describing algorithms.
 It allows the designer to focus on the logic of
the algorithm without being distracted by
details of language syntax.
 At the same time, the pseudo code needs to be
complete.
 It describe the entire logic of the algorithm so
that implementation becomes just a mechanical
task of translating line by line into source code.
Examples of Pseudocodes…
 Example #1 - Computing Sales Tax :
Pseudo-code the task of computing the final price of an item after
figuring in sales tax.
Note the three types of instructions: input (get), process/calculate
(=) and output (display)
     1.    get price of item
    2.    get sales tax rate
    3.    sales tax = price of item times sales tax rate
    4.    final price = price of item plus sales tax
    5.    display final price
    6.    stop
     variables : price of item, sales tax rate, sales tax, final price
 Note that the operations are numbered and each operation is
unambiguous and effectively computable.
We also extract and list all variables used in our pseudo-code. This will be
useful when translating pseudo-code into a programming language
 Example #2 - Computing Weekly Wages :
 Gross pay depends on the pay rate and the number of hours worked
per week. However, if you work more than 40 hours, you get paid
time-and-a-half for all hours worked over 40. Pseudo-code the task of
computing gross pay given pay rate and hours worked.
     1.    get hours worked
    2.    get pay rate
    3.    if hours worked <=  40 then
            3.1    gross pay = pay rate times hours worked
    4.    else
            4.1    gross pay = pay rate times 40 plus 1.5 times pay
rate times ( hours worked minus 40)
    5.    display gross pay
    6.    stop
     variables : hours worked, pay rate, gross pay
 This example introduces the conditional control structure. On the basis
of the true/false question asked in line 3, we execute line 3.1 if the
answer is True; otherwise if the answer is False we execute the lines
subordinate to line 4 (i.e. line 4.1). In both cases we resume the pseudo-
code at line 5.
Traditional Style of Programming: ‘C’

 C programs consist of pieces/modules called


functions.
 A programmer can create his own functions
 Advantage: the programmer knows exactly how it
works.
 The functions act like building blocks of program.
 Library of functions is pre-made and these can
be used, rather than re-writing code again and re-
inventing the wheel.
 Disadvantage: Programs are long to write and
time consuming

12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, Deptt 10
of IT & Computer Sciences, UPESDDN
C++
 C++
 Superset of C developed by Bjarne Stroustrup at
Bell Labs in early 1980’s.
 "Spruces up" C, and provides object-oriented
capabilities
 Object-oriented design very powerful
 10 to 100 fold increase in productivity
 Dominant language in industry and academia

12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, Deptt 11
of IT & Computer Sciences, UPESDDN
C++…
 It is efficient, compact, fast and a portable
language.
 It can be used in 3 ways:
 In a procedural way -using functions.
 In an Object Oriented way –using classes.
 In a Generic way –using templates.

12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, Deptt 12
of IT & Computer Sciences, UPESDDN
Why C++?
 Popular and relevant (used in nearly every application
domain):
 end-user applications (Word, Excel, PowerPoint, Photoshop,
Acrobat, Quicken, games)
 operating systems (Windows 9x, NT, XP; IBM’s K42; some
Apple OS X)
 large-scale web servers/apps (Amazon, Google)
 central database control (Israel’s census bureau; Amadeus;
Morgan-Stanley financial modeling)
 communications (Alcatel; Nokia; 800 telephone numbers;
major transmission nodes in Germany and France)
 numerical computation / graphics (Maya)
 device drivers under real-time constraints
 Stable, compatible, scalable

12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, Deptt 13
of IT & Computer Sciences, UPESDDN
C Vs C++
 C++ is C incremented
(orig.inally, “C with classes”)
 C++ is more expressive
(fewer C++ source lines needed than C source lines for same program)
 C++ is just as permissive
(anything you can do in C can also be done in C++)
 C++ can be just as efficient
(most C++ expressions need no run-time support;
C++ allows you to
 manipulate bits directly and interface with hardware without regard for safety
or ease of comprehension, BUT
 hide these details behind a safe, clean, elegant interface)

 C++ is more maintainable


(1000 lines of code – even brute force, spaghetti code will work;
100,000 lines of code – need good structure, or new errors will be
introduced as quickly as old errors are removed)

12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, Deptt 14
of IT & Computer Sciences, UPESDDN
Advantages of Coding in C++…
 Main purpose of C++ is to make writing good
programs easier and more pleasant for
individual programmers.
 C++ was originally known as ‘C with classes’ as
two languages contributed to its design –C
(which provided low-level features) and Simula-
67 (which provided the class concept).

12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, Deptt 15
of IT & Computer Sciences, UPESDDN
More about C++…
 C++ is compact and can be used for system
programming.
 It can use the existing C software Libraries.
 It also has OO capabilities similar to an
procedural language like C and as an Object
Oriented language like Simula67, Other OOLs
include Smalltalk and Ada.

12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, Deptt 16
of IT & Computer Sciences, UPESDDN
Variables & Constants…

 Variables are names given to the locations


where the constants are stored.
 Constants can be real numbers, integers, float.
And their values do not change till the end of
the program.
 The variable must be declared before it is used
and the variable can handle only that kind of
constants.
Keywords..
 These are the words that is used by the
programming language to perform
certain functions.
 e.g “printf” is a function used to print the
value on the screen.
 These words are already explained to the
compiler .
 e.g char,const,else..
Hierarchy of Operations
*, /,%- multiplication, division,
 1st-
modular division.

 2nd- +,- addition and subtraction.

 3rd- =, assignment operation.


Data Types….
 A data type is a set of values and the operations
on those values.
 Common types of data in programming
languages include primitive types (such as
integers, floating point numbers or characters) .
Following are Common Built-in
Data Types…
 char
 int
 float • A signed data type is one
 unsigned char that can hold positive
 unsigned int and negative values.
 long int • An unsigned data type
 unsigned long int can only hold positive
 short int values including zero.
 unsigned short int
 double
 long double
 bool
Storage Requirements of Built-in
datatypes…
Data Type No of Bytes on Min Value Max Value
32 bit
Computer
char 1 -128 127
int 4 -2^31 (2^31)-1
Float 4 6 digits of precision 6 digits of precision
Unsigned char 1 0 (2^8)-1
Unsigned int 4 0 (2^32)-1
Long int 4 -2^31 (2^31)-1
Unsigned long int 4 0 (2^32)-1
Short int 2 -2^15 (2^15)-1
Unsigned short int 2 0 (2^16)-1
double 8 12 digits of precision 12 digits of precision
Long double 12 16 digits of precision 16 digits of precision
bool 1 0 1
Basic steps…
 Type the program in a file. Save it (source code).
 Compile it (using a compiler).
 Link it.
 Execute it.

12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, Deptt 23
of IT & Computer Sciences, UPESDDN
Turbo C++
 This Turbo C++ IDE will be used to design
programs, compile them & execute them.
 Compile menu has the compile menu item, which
is used for code compilation.
 Compilation generates Object code
 Run option chosen would link the object code
and execute the output.
 Turbo C++ contains support for the industry
standard ANSI C and ISO/ANSI C++ languages
and libraries.
 Turbo C++ also includes the Dinkumware C++
runtime libraries and support for the popular
Boost library
12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, Deptt 24
of IT & Computer Sciences, UPESDDN
Designing a program…
 #include<iostream.h>
#include<iomanip.h>
void main()
{
cout<<“Let’s start programming”<<endl;
}

12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, Deptt 25
of IT & Computer Sciences, UPESDDN
Explanation…
 To write a C++ program, one can divide it into
major tasks.
 Each task would be handled by a different
function.
 Every executable C++ program must contain a
function called main().
 In the current program, the main() performs
the task of displaying “lets start programming”
on the standard output device.
 endl is one of the manipulators, that causes
cursor to go to next row.

12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, Deptt 26
of IT & Computer Sciences, UPESDDN
Contd…
 Every function contains a function body,
delimited by “{“ and “}” curly braces.
 Inside the main body, one or more statements
are terminated by a semicolon(;).
 In C++, a statement is a complete instruction
given to the computer.
 “cout“ is called output statement.
 “<<“ is output operator.
 It is used to direct a value to the standard
output device.
12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, Deptt 27
of IT & Computer Sciences, UPESDDN
Header Files used…..
 #include < iostream.h>
 This statement does not terminate with a semicolon.
 It is called a preprocessor directive.
 Pre-processor directives are the statements that are processed
before the program is compiled.
 This statement attaches the code of the header file iostream to
the given program.
 The header files contain all the information that is required to
make use of the C++ libraries, that are attached to the code
during the linking time.
 The C++ libraries contain the definitions of functions, classes,
and pre-defined objects like cout.
 iomanip.h header file is stores definition of endl.

12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, Deptt 28
of IT & Computer Sciences, UPESDDN
Designing a program…
 #include<iostream.h>
#include<iomanip.h>
void main() Pre-processor
{ Function name Directives

cout<<“Let’s start programming”<<endl;


}

Function body
12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, Deptt 29
Statement of IT & Computer Sciences, UPESDDN
Simple Programs for warm-up
 #include<iostream.h>
int main()
{
int var; // variable definition
var=65; // variable initialization
cout<< “I am senior citizen” << var << “years

old”;
return 0;
}
12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, 30
Deptt of IT & Computer Sciences, UPESDDN
Standard Input & Output…
 #include<iostream.h>
#include<iomanip.h>
int main()
{ int age;
cout<<“How old are you?”<<endl;
cin>>age; //inputting value into
variable
cout<<“you are “ <<age<< “years old”;
return 0;
}
12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, 31
Deptt of IT & Computer Sciences, UPESDDN
Just warm up….
 #include< iostream.h>
#include<iomanip.h>
int main()
{
char alph;
int var;
float frac;
cout<<“Enter a number followed by a single character and a
decimal”<<endl;
cin>>var>>alph>>frac;
cout<<“The whole number is “<<var<<endl<<“The decimal
number is “<<frac<<endl<<“The character is “<<alph<<endl;
return 0;
}
12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, 32
Deptt of IT & Computer Sciences, UPESDDN
Little on formatting….
 The problem of formatting can be solved with the help of a
function named setw().
 The function can only be used if the header file, iomanip.h
is included.
 #include<iostream.h>
#include<iomanip.h>
int main()
{
int var=101;
cout<<“About-”<< setw(5) << var<< setw(10) <<“ –
birds”<<endl;
return 0;
}12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, 33
Deptt of IT & Computer Sciences, UPESDDN
Contd…
 There are two spaces before 101 and four
spaces before the string “-birds” that is, by
default the strings are right aligned.

12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, 34
Deptt of IT & Computer Sciences, UPESDDN
setprecision() & sqrt()
 The function sqrt(), calculates the square root of a number.
 To use this function, the header file to be included is cmath.
 The number of decimal places can be controlled with the
setprecision() function.

 #include<iostream.h>
#include<iomanip.h>
#include<cmath.h>
int main()
{
cout<< setprecision(5) <<sqrt(25);
return 0;
}
12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer,
Deptt of IT & Computer Sciences, UPESDDN
35
The variables….
 C++ provides variables for storing and manipulating
data in programs.
 A program refers to a variable using its name.
 Certain rules and conventions govern the naming
of identifiers.
 Identifiers are programmer-defined names.
 The program does not compile if rules are not
followed.

12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, 36
Deptt of IT & Computer Sciences, UPESDDN
Rules…
 The name of the identifier needs to be without any embedded
space or symbols such as ? ! - + @ # % ^ & * ( ) [ ] { } . ; , : “ “
‘/\
 However underscore, can be used wherever spaces are to be
inserted. Ex: basic_salary
 Identifier names must be unique within a program.
 An identifier name can have any number of characters.
 An identifier name must begin with an alphabet or an
underscore (‘_’), which may be followed by a sequence of
letters, digits (0-9) or ‘_’.
 C++ is case-sensitive. That means, Customer_name is
different from customer_name.
 Keywords cannot be used as identifiers.
12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, 37
Deptt of IT & Computer Sciences, UPESDDN
Variable Naming Conventions…
 Variable names must be meaningful and short.
 They must reflect the data that the variables contain.
 For ex: employee_age
 Normally variable names are written in lower case.

12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, 38
Deptt of IT & Computer Sciences, UPESDDN
Simple Example with if construct…
 #include< iostream.h>
int main()
{
char alph;
int num;
cout<<“Enter a character”<<endl;
cin>>alph;
cout<<endl<<“Enter the number of times the character “<<“ needs to be
displayed (1-3):” <<endl;
cin>>num;
if (num==1)
{
cout<<endl <<alph;
}
else if (num==2)
{
cout<<endl<<alph;
cout<<endl<<alph;
}

12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, 39
Deptt of IT & Computer Sciences, UPESDDN
Contd…..
else if (num==3)
{
cout<<endl<<alph;
cout<<endl<<alph;
cout<<endl<<alph;
}
else
{
cout<<“Invalid Input”;
}
return 0;
}
Another example…
 #include< iostream.h>
int main()
{
char in_chr;
cout<< “enter a character in lowercase”<<endl;
cin>>in_chr;
if (in_chr == ‘a’)
cout<<endl<<“Vowel a”<<endl;
else if(in_chr == ‘e’)
cout<<endl<<“Vowel e”<<endl;
else if(in_chr == ‘i’)
cout<<endl<<“Vowel i”<<endl;
else if(in_chr == ‘o’)
cout<<endl<<“Vowel o”<<endl;
else if(in_chr == ‘u’)
cout<<endl<<“Vowel u”<<endl;
else
cout<<endl<<“the character is not a vowel<<endl;
return 0;
}

12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, 41
Deptt of IT & Computer Sciences, UPESDDN

Switch case example….
#include<iostream.h>
int main()
{
char in_chr;
cout<<endl<<“Enter a character in lowercase<<endl;
cin>>in_chr;
switch(in_chr)
{
case ‘a’:
cout<<“ Vowel a”<<endl;
break;
case ‘e’:
cout<<“Vowel e”<<endl;
break;
case ‘i’:
cout<< “Vowel i”<<endl;
break;
case ‘o’:
cout<<“Vowel o”<<endl;
case ‘u’:
cout<<“Vowel u”<<endl;
default:
}
return 0;
12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, 42
} Deptt of IT & Computer Sciences, UPESDDN
Loop Construct…
 A loop causes a section of a program to be
repeated a certain number of times.
 The repetition continues while the condition set
for it remains true.
 When the condition becomes false, the loop ends
and the control is passed to the statement
following the loop.

12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, 43
Deptt of IT & Computer Sciences, UPESDDN
While loop…
 The following program generates fibonacci series between 1 and 200.
 In this series, each number is the sum of its two preceding numbers.
 The series begins with 1.

#include <iostream.h>
int main()
{
int num1=1, num2=1;
cout<<num1<<endl;
while (num2 < 200)
{
cout<< num2<<endl;
num2 += num1; //This statement actually means: num2=num2+num1;
}
return 0;
}

12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, 44
Deptt of IT & Computer Sciences, UPESDDN
Using break statement…
 The break statement causes the program flow to exit the body of the while loop.
 #include<iostream.h>
int main()
{
int num1=1, num2=1;
cout<<num1<<endl;
while (num2 < 150)
{
cout<< num2<<endl;
num2+=num1;
num1=num2-num1;
If(num2==89)
break;
}
return 0;
}

The control exits the loop when the condition, num2 == 89, becomes true.
Hence output stops with 55, instead of 144.

12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, 45
Deptt of IT & Computer Sciences, UPESDDN
More…….
 The continue statement returns the control to the beginning of the while loop,
skipping any statement following the continue statement in the loop body.

This program shows the use of while construct in accepting input as y or n only. Any
other input is rejected by the function until valid input is provided.

 #include<iostream.h>
#include<iomanip.h>
int main()
{
char ch=‘y’;
int num;
while(ch==‘y’)
{
cout<<endl<<“Enter a number”<<endl;
cin>>num;
cout<<endl<<“Do you wish to enter more numbers (y/n)?”<<endl;
cin>>ch;
}
return 0;
}
Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, 46
12/09/2021 Deptt of IT & Computer Sciences, UPESDDN
while & switch case…
#include<iostream.h>
#include<iomanip.h>
int main()
{
char ok;
int chc;
ok=‘n’;
while(ok==‘n’)
{
ok= ‘ ‘; //beginning of while block reinitializes ok to space
cout<<endl<< “Menu”<<endl;
cout<<endl<<“1. Create a folder”<<endl;
cout<<endl<<“2. Delete a folder”<<endl;
cout<<endl<<“3. show folder”<<endl;
cout<<endl<<“4. exit”<<endl;
cout<<endl<<“your choice (1-4)”<<endl;
cin>>chc;

12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, 47
Deptt of IT & Computer Sciences, UPESDDN
Contd…..
switch(chc)
{
case 1:
cout<<“CREATING FOLDER FOR YOU”<<endl;
break;

case 2:
cout<<“ DELETION OF THE FOLDER”<<endl;
break;

case 3:
cout<<“SHOWING “<<endl;
break;
case 4:
cout<<“EXITING……….”<<endl;
break;
default:
cout<<endl<<“Invalid choice”<<endl;
ok=‘n’;
} //End of switch block
} // End of while block
return 0;
}

12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, 48
Deptt of IT & Computer Sciences, UPESDDN
do….while loop…
 The do…while loop construct is similar to the while
loop construct, it iterates until the specified loop
condition becomes false.
 It differs from the while loop, in that, the body of
the loop is executed at least once, and the condition is
evaluated for subsequent executions.

12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, 49
Deptt of IT & Computer Sciences, UPESDDN
Comparison…
do while
while

Execute body of
Evaluate loop
False
Condition

Evaluate False
True Condition
Execute body of
loop
True
12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, 50
Deptt of IT & Computer Sciences, UPESDDN
Example program repeated with
do…while to show difference
 #include<iostream.h>
int main()
{
char ok;
int chc;
do
{
ok=‘ ‘;
cout<<endl<< “Menu”;
cout<<endl<<“1. Create a folder”;
cout<<endl<<“2. Delete a folder”<<endl;
cout<<endl<<“3. show folder”<<endl;
cout<<endl<<“4. exit”<<endl;
cout<<endl<<“your choice (1-4)”<<endl;
cin>>chc;

12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, 51
Deptt of IT & Computer Sciences, UPESDDN
Contd….
switch(chc)
{
case 1:
cout<<“CREATING FOLDER FOR YOU”<<endl;
break;

case 2:
cout<<“ DELETION OF THE FOLDER”<<endl;
break;
case 3:
cout<<“SHOWING “<<endl;
break;
case 4:
cout<<“EXITING……….”<<endl;
break;
default:
cout<<endl<<“Invalid choice”<<endl;
ok=‘n’;
} //End of switch block
}while (ok==‘n’);
return 0;
}
12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, 52
Deptt of IT & Computer Sciences, UPESDDN
The difference….
 The initialization, ok=‘n’, is required for the
control to enter a while loop, whereas this step
is not required in the function that uses the
do…while construct.
 This is a better loop construct to use when
the body of the loop has to be executed at
least once before the loop condition is
evaluated.

12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, 53
Deptt of IT & Computer Sciences, UPESDDN
for loop…
 The for loop construct provides a compact way of specifying
the statements that control the repetition of the steps
within the loop.
 In the for construct, the loop control statements are not
written within the loop; instead, they are written at the top.
 This makes the program more readable and easily
understandable.
 The for loop consists of the keyword, for, followed by
parentheses containing 3 expressions, each separated by a
semicolon.
 These are initialization expression, the test expression,
and the increment/decrement expression.

12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, 54
Deptt of IT & Computer Sciences, UPESDDN
Example…
 #include<iostream.h>
#include<iomanip.h>
int main()
{
int var;
for( var=1; var <=10; var++)
{
cout<<setw(5) << (var * var);
}
cout<<endl;
return 0;
}

12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, 55
Deptt of IT & Computer Sciences, UPESDDN
Knowing prefix & postfix…
 Eg: Prefix= ++ivar; • Eg: Postfix= ivar++;

int var1=10; • int var1=10;


var1=++var1; • var1=var1++;

This will be translated as: • This will be translated as:

int var1=10; • int var1=10;


var1= var1 + 1; • var2=var1;
var2=var1; • var1= var1 + 1;

Result is both var1 & var2 • Result is var1 is set to 11,


are set to 11. & var2 is set to 10.
12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, 56
Deptt of IT & Computer Sciences, UPESDDN
Array
 An array is a data structure which allows a collective
name to be given to a group of elements which all have
the same type.
 An individual element of an array is identified by its
own unique index (or subscript).
 An array can be thought of as a collection of numbered
boxes each containing one data item.
 The number associated with the box is the index of the
item.
 To access a particular item the index of the box
associated with the item is used to access the appropriate
box.
 The index must be an integer and indicates the position of
the element in the array.
 Thus the elements of an array are ordered by the index.
Array Declaration…
 An array declaration is very similar to a variable
declaration.
 First a type is given for the elements of the array, then
an identifier for the array and, within square brackets,
the number of elements in the array.
 The number of elements must be an integer.
 For example data on the average temperature over the
year in Britain for each of the last 100 years could be
stored in an array declared as follows:

 float annual_temp[100]
Using an array…example….reversing the string
 #include<iostream.h>
int main()
{
char source[101], dest[101];
int pos=0, j=0;
cout<<“Enter string to be reversed” <<endl;
cin>>source;
while (source[pos]!=‘\0’)
{
pos=pos+1;
}
for(--pos; pos>=0;dest[j++]=source[pos--]);
dest[j]=0;
cout<<endl<<“The reversed string is :”<<endl<<dest<<endl;
return 0;
}

12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, 59
Deptt of IT & Computer Sciences, UPESDDN
Use of Functions….
 A function is a named part of a program that can be invoked from other parts
of a program as often as needed.
 Advantages are:
(1). Reusability
(2). Modularity
(3). Overall programming simplicity.
Functions also provide programmers a convenient way of designing
programs in which complex computations can be built into the functions.
Once a function is properly designed or coded, a programmer does not have
to bother about how the calculations are done in it.
It is sufficient that the programmer knows what the function does and
simply ensures that the required parameters are passed to it.
The use of functions saves a programmer, the problem of debugging a
program that does not function properly.

12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, 60
Deptt of IT & Computer Sciences, UPESDDN
Function prototypes, parameters,
Call & Definition…
 #include<iostream.h>
void sum (int, int); //function prototype
int main()
{
sum(5, 7); //function call; sending parameters; constants
return 0;
}
void sum(int x, int y) //function definition (function body)
{
int tot;
tot= x+y;
cout<<“sum is “<<tot;
return;
}

12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, 61
Deptt of IT & Computer Sciences, UPESDDN
Visualizing the flow….

in()
ma
l to k
 main() { }

c
con rn ba
tro
retu
 sum() {1 } 2

 Further explaining the 2flow of the above program,


main(), calls the sum function, which after its
execution returns the control back to the
calling function, i.e, main().
 Hence Step 1 happens first and then step 2.

12/09/2021 Authored & Designed by: Mrs. Neelu J Ahuja, Sr. Lecturer, 62
Deptt of IT & Computer Sciences, UPESDDN
Pointers
 We can define a variable in C++ to store a memory address.
 A pointer in C++ is said to "point to" the memory address that is
stored in it.
 Also, when defining a C++ pointer variable, we must specify the
type of variable to which it is pointing.

 For example, to define a pointer, which will store a memory


address at which exists an int, we can do the following:  //Sample
program for c++ pointer

signed main()
{
    int* p;
    //Right now, p contains no particular myval in this C++ code.
}
  The asterisk in the above specifies that we have a pointer variable.  

You might also like