You are on page 1of 86

Programming Language Generations Programming Language Generations are used to represent the major steps or generations in the evolution

of programming languages. Generations of programming languages are categorized into 5 categories and are: First Generation of Programming Language or 1GL Machine language is considered to be the first generation of programming language. In machine language the level of instructions and data that the processor is actually given to work on conventional computers is a string of 0s and 1s. So, the language of 0s and 1s, i.e. machine language is known to be the first generation of programming languages. Second Generation of Programming Language or 2GL 2GL or second generation language is Assembler (sometimes called Assembly language). A typical 2GL instruction looks like this: ADD 12, 8 An assembler converts the assembly language statements into machine language. Third Generation of Programming Language or 3GL Third generation languages are called High-Level programming languages such as C/C++, Pascal or Java etc. A sample Java language statement looks like this: public static void main(String args[]) { System.out.println(Hello Everyone); } High-level languages are near to English and the program created in a high-level language is called source program. Compiled type languages i.e. C/C++, Pascal, COBOL and Fortran etc and Interpreter based languages i.e. QBasic, GW-Basic and Visual Basic etc are 3GL. Fourth Generation of Programming Language or 4GL Fourth generation programming language or 4GL is designed to be closer to natural language than a 3GL. Language for accessing databases are often described as 4GLs. A 3GL language statement might look like this: SELECT NAME FROM EMPLOYEES WHERE SALARY > $7000 Fifth Generation of Programming Language or 5GL In fifth generation of programming languages, we use a visual or graphical development interface to create source language that is usually compiled with a 3GL or 4GL compiler. IBM, Microsoft, Borland and other companies make 5GL programming products. Page 1 of 86

ITCP / Programming Techniques / Programming Fundamentals

Introduction to C-Language C was created by Dennis Ritchie at Bell Labs in 1972, while working to develop Unix Operating System. It came from Ken Thompsons B-Language written in 1970. Levels of Programming Languages There are 3 levels of programming languages i) ii) iii) i) High-Level Language Middle-Level Language Low-Level Language High-Level Language High-Level Language is designed to try to give programmers everything they could possible want already built into the language. Following are the high-level languages: ii) ADA BASIC COBOL FORTRAN Pascal

Middle-Level Language Middle-Level Language gives programmers a minimal set of control to define high-level constructs. Following are the middle-level languages: C/C++ FORTH

iii)

Low-Level Language Low-Level Language forces programmers to define all program functions directly because nothing is built in the language. Following are the low-level languages: Assembly

C is one of a smallest programming language. It has almost 33 reserve words but doesnt restrict the programming style. C is often called a middle-level language.

ITCP / Programming Techniques / Programming Fundamentals

Page 2 of 86

Advantages of using C-Language Following are the advantages of using C-Language i) ii) Structured Format C offers top-down structured programming approach. C also allows separately compiled sub-routines to be used without being the part of the program. Flexibility Being a general-purpose programming language it can be used for solving engineering problems or for writing database systems etc Portability Programs written on one system can be run on another system with little or very minor modifications. Compactness & Efficiency Programs written in C-Language generate fast and compact code. Programs compiled by C compilers can run about as fast as those written in Assembler. Personalization In addition to the built-in functions, C-Language allows the user to add his own functions to the language. So it can be personalized to fit one needs.

iii)

iv)

v)

Uses of C/C++ Programming Language C is meant for designing Operating Systems. 90% of the Unix code is written in C. Areas other than system programming where C-Language can be used are Operating Systems Communication Packages Language Interpreters Language Compilers Text Editions Network Drivers Data Bases Utilities Spreadsheets etc etc

C/C++ Character Set C/C++ character set comprises of following characters

A,B,C,.Z A,b,c,...z 0,1,2,9 ,.;:?!/\|~ ()[]{}<> +-#%_^=&*

ITCP / Programming Techniques / Programming Fundamentals

Page 3 of 86

White Space Characters The character that produces blank space when printed is called a white space character, e.g. Spaces Tabs New Lines

Tokens A group of characters separated by white space is known as a Token. Following are the classes of tokens. i) Keywords Keywords are the words that make up the C/C++ programming language. Keywords have special meaning to the C/C++ compiler, so they can not be used for other than as a keyword. These must be entered in lower case. Identifiers Identifiers are used to describe the names of variables, constants and functions in C/C++, and are also known as Programmer Supplied Words. Constants A data object whose pre-set value does not change during the execution of the program is known as constant, i.e. pie. Variable Variable is a data object whose value may change during the execution of the program. Functions Functions are routines to perform commands or operations etc, and may return a value to the calling routine. String Literals String Literals are also called a String Constant. It is a sequence of characters surrounded by double quotes. A null byte \0 is appended to the string so that programs that scan the string can find its end. Operators Operators are symbols that define how values are manipulated. Operators describe the action that we want to take between the operands. Other Separators Other Separators are also using in C/C++.

ii)

iii)

iv)

v)

vi)

vii)

viii)

ITCP / Programming Techniques / Programming Fundamentals

Page 4 of 86

Naming Rules in C/C++ Following are the naming rules in C/C++ Can contain letters, digits and underscores. Digit can not be the first character. Spaces are not allowed. May not be same as keyword or function name etc. First 40 characters are significant, i.e. Length can be of max. 40 characters, but varies from compiler to compiler. Can not consist of an underscore alone. Data types and Sizes There are three main data types in C/C++ i) ii) iii) i) Character Integer Floating Point char int float

Character data type Character data type is represented by char and is used for storing a character, digit or special character. A character constant must be enclosed in single quotations i.e. A, 1 or * etc. A variable declared as character uses/occupies one byte of memory. A character constant can be signed or unsigned. The range of binary numbers in signed char is from -128 to +127 The range for binary numbers in unsigned char is from 0 to 255

So, there are 3 types of character data type, i.e. char, signed char and unsigned char. e.g. ii) char age means signed char signed char code means signed char unsigned char value means unsigned char

Integer data type Integer data type is represented by int and is used for storing Integers, i.e. numeric values without decimal portions. Integer variable can store a value ranging from -32,768 to + 32,767 Integer data type uses 2 bytes of memory Integer data type is also represented as short Another integer type to store larger values is long that can store a value ranging from -2,147,483,648 to 2,147,483,647 long takes 4 bytes of memory Page 5 of 86

ITCP / Programming Techniques / Programming Fundamentals

Another int type is signed int which is used to store sign too along with the numeric value. Another int type is unsigned int which is used to store values without sign

So, there are 9 types of Integer data types, i.e. int, short, signed int, unsigned int, signed short, unsigned short, long, signed long and unsigned long e.g. iii) int a signed int b unsigned int c short d signed short e unsigned short f long g signed long h unsigned long i means signed int means signed int means unsigned int means signed short means signed short means unsigned short means signed long means signed long means unsigned long

Float data type Float data type is represented by float and is used for storing numeric values along with fraction or decimal portion. Float data type takes 4 bytes of memory. A floating point number is expressed in scientific notation. The reason of storing float values in scientific notation is that they can be very large or extremely small, i.e. 2000000000000000 = 2e+15 0.00000000000023 = 2.3e-13 A value written as 47e3 means 47 x 103 47e3 = 47 x 103

mantissa

exponent

Exponent value ranges from -38 to +38, i.e. 47x10-38 to 47x10+38 Another float type is double that takes 8 bytes of memory. Exponent values in double ranges from -308 to + 308, i.e. 47x10-308 to 47x10+308

ITCP / Programming Techniques / Programming Fundamentals

Page 6 of 86

Types of C/C++ Instructions There are 4 types of C/C++ Instructions. i) ii) iii) iv) Type declaration Instructions Variable types and definitions etc. Input/Output Instructions Data Input, Data Display, Data Write etc Control Instructions Controls the sequence of execution of the program instructions. Arithmetic Instructions Arithmetic Operations etc

ITCP / Programming Techniques / Programming Fundamentals

Page 7 of 86

First Program in C
Preprocessor Directive and is the only thing that should be present in the first column
<stdio.h> search function in the directory in which C in installed. stdio.h search function in the directory which is presently in use.

#include <stdio.h> void main(void) { printf(Welcome to C); }


Function body

Statement Terminator

First Program in C++


Preprocessor Directive and is the only thing that should be present in the first column

#include <iostream.h> void main(void) { cout<<Welcome to C++; }


Function body

Statement Terminator

Preprocessor Directive # is called Preprocessor Directive. The # line tells the compiler to use a file <iostream.h> or <stdio.h> or whatever written in <angle brackets>. Files having .h extension in C/C++ are called header files. They are also sometimes called include files. The iostream.h file is included in the program as it contains the information about the cout identifier and the << operator. Normally all the header files of C/C++ are present in the INCLUDE directory. Main Function A C/C++ program may consist of many functions, classes and other program elements, but on startup, control always goes to main() function. The first statement executed by the C/C++ compiler will be the one that is the first statement in function void main(void) or void(main) or main(). In C/C++ all the statements of a function, either it is main() or any other should be in blocks. A block starts with { (starting brace), then we write statements in the function, and at the end we put } (closing brace), in order to tell the compiler that the above written statements within the block are the statements of a function. The body of a function starts from { and ends at }. Every starting brace should have a closing brace. The statement cout<<Welcome to C++; displays the string constant Welcome to C++ on the screen. We can have one or more statements inside a function. Statements tell the computer to do something. C/C++ statements are always terminated by semicolon. ITCP / Programming Techniques / Programming Fundamentals Page 8 of 86

Using Comments in the Program


// It is a C++ Program #include <iostream.h> void main(void) //main function { /* These lines are the part of comments and will not execute */ cout<<"We are studying C++"; }

There are two ways of specifying comments in C++. i) ii) Using // /* and */

All the lines between /* and */ are treated as comments and are normally used when we want to specify many lines as comments. So if we want the C++ compiler to treat some continuous lines as comments then instead of using // at the start of all those lines, it is better to use /* from starting line and */ after the last line and all the lines between starting and ending comments will be treated as comments and will not execute.
Defining and using Integer Variables 1.cpp #include <iostream.h> void main(void) { int a; int b; a = 10; b = a + 5; cout<<"A is "<<a <<endl; cout<<"B is "<<b <<endl; } Output A is 10 B is 15

ITCP / Programming Techniques / Programming Fundamentals

Page 9 of 86

2.cpp #include <iostream.h> #include <conio.h> void main(void) { int a,b; a = 10; b = a + 5; clrscr(); cout<<"A is "<<a <<" and B is "<<b<<endl; cout<<"Press any key to finish"; getch(); } Output A is 10 and B is 15 Press any key to finish

Variable Definition and Declaration 3.cpp #include <iostream.h> #include <conio.h> void main(void) { clrscr(); char first=65; int second=964; float third=5.543; cout<<first<<endl<<second<<endl<<third; getch(); } Output A 964 5.543 Using Escape Sequences in the Program 4.cpp #include <iostream.h> #include <conio.h> void main(void) { clrscr(); cout<<"Hello\nHow\nAre\nYou\n"; cout<<Hello\n\tHow\n\t\tAre\n\t\t\tYou\n; getch(); } Output Hello How Are You Hello How Are You

ITCP / Programming Techniques / Programming Fundamentals

Page 10 of 86

Escape Sequences \ is considered an escape sequence character that causes and escape from the normal interpretation of a string so that the next character is recognized as having a special meaning. Following are the escape sequence characters along with their usage. Escape Sequence \a \b \f \n \r \t \\ \ \ \xDD i.e. \xDB Character Audible Alert Backspace Form feed New Line (Carriage Return + Line Feed) Return Tab Backslash Single quotation Double quotation Hexadecimal Representation

Taking Input in the Program 5.cpp #include <iostream.h> #include <conio.h> void main(void) { clrscr(); int a, b; cout<<"Enter first value "; cin>>a; cout<<"Enter second value "; cin>>b; cout<<a<<" + "<<b<<" = "<<a+b; getch(); } Output Enter first value 4 Enter second value 3 4+3=7

ITCP / Programming Techniques / Programming Fundamentals

Page 11 of 86

Temperature Conversion Program 6.cpp #include <iostream.h> #include <conio.h> void main(void) { clrscr(); int fah; cout<<"Enter Temperature in Fahrenheit "; cin>>fah; int cel = (fah - 32) * 5/9; cout<<"Equivalent temperare in Celcius is "<<cel; getch(); } Output Enter Temperature in Fahrenheit 32 Equivalent temperare in Celcius is 0

The const Qualifier The keyword const (for constant) precedes the data type of a variable. It specifies that the value of a variable will not change throughout the program.
Calculating the Area of a Circle 7.cpp #include <iostream.h> #include <conio.h> void main(void) { clrscr(); float radius; const float PIE = 3.14; cout<<"Enter radius of circle "; cin>>radius; float area = PIE * radius * radius; cout<<"Area of the circle is "<<area; getch(); } Output Enter radius of circle 0.5 Area of the circle is 0.785 Type Conversion 8.cpp #include <iostream.h> #include <conio.h> void main(void) { clrscr(); int count=7; float weight=200.5; double totalweight = count * weight; cout<<"Total weight calculated is "<<totalweight; getch(); } Output Total weight calculated is 1403.5

So, if we try to perform some Arithmetic operation on different data types, i.e. int, float and double etc then C/C++ calculates the result of such type of Arithmetic expression without giving any error.

ITCP / Programming Techniques / Programming Fundamentals

Page 12 of 86

Casts Cast is a way through which we change the type of the variable during the execution of the program for a limited time, because variables previously defined type can not calculate the values correctly due to its low range.
9.cpp #include <iostream.h> #include <conio.h> void main(void) { clrscr(); int test=25000; //range is -32,768 to +32,767 test = (test * 10)/10; cout<<"Result is "<<test<<endl; test = 25000; test = (long(test)*10)/10; cout<<"Result now is "<<test; getch(); } Output Result is -1214 Result now is 25000

Arithmetic Operators Following are the basic Arithmetic operators used in C/C++: i) ii) iii) iv)

+ * /

(Addition) (Subtraction) (Multiplication) (Division)

Apart from the specified basic operators, there are some other operators used in C/C++, and are v) vi) vii) viii) ix) x) xi) xii)

% ++ -+= -= *= /= %=

(Remainder or Modulus) (Increment) (Decrement) (Increment Assignment) (Decrement Assignment) (Multiplication Assignment) (Division Assignment) (Remainder Assignment)

Increment and Decrement operators can be used in two ways, i.e. i) ii) Prefix Postfix

ITCP / Programming Techniques / Programming Fundamentals

Page 13 of 86

10.cpp #include <iostream.h> #include <conio.h> void main(void) { clrscr(); int a=5,b=2; cout<<"A = 5 and B = 2"<<endl<<endl; cout<<"A B"<<endl<<endl; cout<<a<<" + "<<b<<" = "<<a+b<<endl; cout<<a<<" - "<<b<<" = "<<a-b<<endl; cout<<a<<" x "<<b<<" = "<<a*b<<endl; cout<<a<<" / "<<b<<" = "<<a/b<<endl; cout<<a<<" % "<<b<<" = "<<a%b<<endl<<endl; a=5; cout<<"Value of A now is "<<a<<endl<<endl; cout<<"Prefix operator ++a gives "<<++a<<endl; cout<<"Value of a after Prefix is "<<a<<endl<<endl; cout<<"Postfix operator a++ gives "<<a++<<endl; cout<<"Value of a after Postfix "<<a<<endl<<endl; cout<<"Now for A = 5 and B = 2"<<endl; a=5,b=2; a+=b; cout<<"a += b means value of a is "<<a<<endl; a=5,b=2; a-=b; cout<<"a -= b means value of a is "<<a<<endl; a=5,b=2; a*=b; cout<<"a *= b means value of a is "<<a<<endl; a=5,b=2; a/=b; cout<<"a /= b means value of a is "<<a<<endl; a=5,b=2; a%=b; cout<<"a %= b means value of a is "<<a<<endl; getch(); } Output A = 5 and B = 2 A B 5+2=7 5-2=3 5 x 2 = 10 5/2=2 5%2=1 Value of A now is 5

ITCP / Programming Techniques / Programming Fundamentals

Page 14 of 86

Prefix operator ++a gives 6 Value of a after Prefix is 6 Postfix operator a++ gives 6 Value of a after Postfix 7 Now for A = 5 and B = 2 a += b means value of a is 7 a -= b means value of a is 3 a *= b means value of a is 10 a /= b means value of a is 2 a %= b means value of a is 1

Relational Operators A relational operator compares two values. Comparisons involved in relation operators can be i) ii) iii) iv) v) vi)

< > == != <= >=

Less than Greater than Equals to Not equals Less than or equals Greater than or equals

The result of comparison is either True or False. If a comparison provides 1, it means True and if it provides 0, it means False.
11.cpp #include <iostream.h> #include <conio.h> void main(void) { clrscr(); int number; cout<<"Enter a Number "; cin>>number; cout<<"number < 10 = "<<(number<10)<<endl; cout<<"number > 10 = "<<(number>10)<<endl; cout<<"number == 10 = "<<(number==10)<<endl; getch(); } Output Enter a Number 10 number < 10 = 0 number > 10 = 0 number == 10 = 1

ITCP / Programming Techniques / Programming Fundamentals

Page 15 of 86

Using Library Functions 12.cpp #include <iostream.h> #include <conio.h> #include <math.h> void main(void) { clrscr(); int a; cout<<"Enter a value "; cin>>a; cout<<"Square Root of "<<a<<" is "<<sqrt(a); getch(); } Output Enter a value 64 Square Root of 64 is 8 13.cpp #include <iostream.h> #include <conio.h> #include <math.h> void main(void) { clrscr(); float a; cout<<"Enter a value "; cin>>a; cout<<"Sine of "<<a<<" is "<<sin(a)<<endl; cout<<"Cosine of "<<a<<" is "<<cos(a)<<endl; cout<<"Tangent of "<<a<<" is "<<tan(a)<<endl; getch(); } Output Enter a value 10 Sine of 10 is -0.544021 Cosine of 10 is -0.839072 Tangent of 10 is 0.648361

ITCP / Programming Techniques / Programming Fundamentals

Page 16 of 86

Loops Loops cause a section of program to be repeated certain number of times. As long as condition remains true, the repetition continues, when the condition becomes false, the loop ends and the control passes to the statement following the loop. There are three kinds of loops in C/C++. i) ii) iii) for loop while loop do while loop

The for loop The for loop executes a section of code a fixed number of times. for loop is used normally when we know, before entering the loop, that how many times we want to execute the code.
Initialization Expression

Test expression

False

Exit

True

Body of the loop

Increment /decrement expression

Operation of for loop


for ( initialization expression ; test expression ; increment/decrement expression ) statement; //single statement in loop body for ( initialization expression ; test expression ; increment/decrement expression ) { statement 1; statement 2; . Multiple statements in loop body . . statement n; }

syntax of for loop ITCP / Programming Techniques / Programming Fundamentals Page 17 of 86

14.cpp #include <iostream.h> #include <conio.h> void main(void) { clrscr(); int sum=0; for(int a=1;a<=10;a++) { cout<<a<<"\t"<<(11-a)<<endl; sum += a; } cout<<"Sum is "<<sum; getch(); } 15.cpp #include <iostream.h> #include <conio.h> void main(void) { clrscr(); int t; cout<<"Enter Table value ";cin>>t; for(int a=1;a<=10;a++) cout<<t<<" x "<<a<<" = "<<(t*a)<<endl; getch(); } 16.cpp #include <iostream.h> #include <conio.h> void main(void) { clrscr(); int num, fact=1; cout<<"Enter a number ";cin>>num; for(int a=num;a>0;a--) fact *= a; cout<<"Factorial of "<<num<<" is "<<fact; getch(); }

Output 1 10 2 9 3 8 4 7 5 6 6 5 7 4 8 3 9 2 10 1 Sum is 55 Output Enter Table value 7 7x1=7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 7 x 6 = 42 7 x 7 = 49 7 x 8 = 56 7 x 9 = 63 7 x 10 = 70 Output Enter a number 4 Factorial of 4 is 24

Nested for loop 17.cpp #include <iostream.h> #include <conio.h> void main(void) { clrscr(); for(int a=1;a<=2;a++) for(int b=1;b<=3;b++) cout<<"A is "<<a<<" & B is "<<b<<endl; getch(); }

Output A is 1 & B is 1 A is 1 & B is 2 A is 1 & B is 3 A is 2 & B is 1 A is 2 & B is 2 A is 2 & B is 3

ITCP / Programming Techniques / Programming Fundamentals

Page 18 of 86

The while loop Normally in for loop we have an idea that how many times we want to execute a section of code but while loop is used when even before starting the loop we have no idea that how many times a section of code will be executed. Like for loop, while loop contains a test expression but there is no initialization or increment/decrement expression etc.

Test expression

False

Exit

True

Body of the loop

Operation of while loop


while ( test expression ) statement; //single statement in loop body while ( test expression ) { statement 1; statement 2; . . . statement n; }

Multiple statements in loop body

syntax of while loop


18.cpp #include <iostream.h> #include <conio.h> void main(void) { clrscr(); int a=1; while(a<=10) { cout<<a<<"\t"<<(11-a)<<endl; a++; } getch(); } Output 1 10 2 9 3 8 4 7 5 6 6 5 7 4 8 3 9 2 10 1

ITCP / Programming Techniques / Programming Fundamentals

Page 19 of 86

19.cpp #include <iostream.h> #include <conio.h> void main(void) { clrscr(); char ch='y'; int t, a; while(ch!='n') { clrscr(); cout<<"Enter Table value ";cin>>t; a=1; while(a<=10) { cout<<t<<" x "<<a<<" = "<<t*a<<endl; a++; } cout<<"Continue ";ch=getche(); } cout<<"\nProgram Finished"; getch(); } 20.cpp #include<iostream.h> #include<conio.h> void main(void) { clrscr(); int a=15; while(a<1 || a>10) { cout<<"Enter a value (1-10) "; cin>>a; } cout<<"Value entered is between 1 - 10"; getch(); }

Output Enter Table value 5 5x1=5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25 5 x 6 = 30 5 x 7 = 35 5 x 8 = 40 5 x 9 = 45 5 x 10 = 50 Continue n Program Finished

Output Enter a value (1-10) 12 Enter a value (1-10) 31 Enter a value (1-10) -5 Enter a value (1-10) 4 Value entered is between 1 - 10

ITCP / Programming Techniques / Programming Fundamentals

Page 20 of 86

The do while loop The do while loop is used when we want to guarantee that the loop body should execute at least once, whatever the initial state of the test expression contains. In do while loop, the test expression is placed at the end of the loop.

Body of the loop

Test expression

False

Exit

True

Operation of do while loop


do statement; //single statement in loop body while ( test expression ) ; do { statement 1; statement 2; . . . statement n;

Multiple statements in loop body

} while ( test expression );

syntax of do while loop


21.cpp #include<iostream.h> #include<conio.h> void main(void) { clrscr(); int a=1; cout<<"Value\tSquare\tCube"<<endl; do { cout<<a<<"\t"<<a*a<<"\t"<<a*a*a<<endl; a++; }while(a<=10); getch(); } Output Value Square Cube 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000

ITCP / Programming Techniques / Programming Fundamentals

Page 21 of 86

22.cpp #include<iostream.h> #include<conio.h> void main(void) { char ch; int t; do { clrscr(); cout<<"Enter Table value "; cin>>t; for(int a=1;a<=10;a++) cout<<t<<" x "<<a<<" = "<<t*a<<endl; cout<<"Continue "; ch=getche(); }while(ch=='Y' || ch=='y'); cout<<"\nThanks for using program"; getch(); }

Output Enter Table value 4 4x1=4 4x2=8 4 x 3 = 12 4 x 4 = 16 4 x 5 = 20 4 x 6 = 24 4 x 7 = 28 4 x 8 = 32 4 x 9 = 36 4 x 10 = 40 Continue n Thanks for using program

ITCP / Programming Techniques / Programming Fundamentals

Page 22 of 86

Decision Making Statements if statement if statement is the simplest of the decision making statements. if statement executes a set of commands when a specified condition is true. If specified condition is false then simply the commands associated with if condition will not execute.

Test expression

False

True

statement 1; statement 2; . .

Exit

Operation of if statement
if ( test expression ) statement ; //single statement in if body if (test expression) { statement 1; statement 2; . . . statement n; }

Multiple statements in if body

syntax of if statement

ITCP / Programming Techniques / Programming Fundamentals

Page 23 of 86

23.cpp #include<iostream.h> #include<conio.h> void main(void) { clrscr(); int a; cout<<"Enter a value "; cin>>a; if(a==10) cout<<"Value entered is 10"; if(a<10) cout<<"Value entered is less than 10"; if(a>10) cout<<"Value entered is greater than 10"; getch(); } 24.cpp #include<iostream.h> #include<conio.h> #include<process.h> void main(void) { clrscr(); long n, j; cout<<"Enter a number ";cin>>n; for(j=2;j<n/2;j++) if(n%j==0) { cout<<"It's not prime, Divisible by "<<j<<endl; getch(); exit(0); } cout<<"It's Prime\n"; getch(); }

Output Enter a value 7 Value entered is less than 10 Enter a value 10 Value entered is 10 Enter a value 13 Value entered is greater than 10

Output Enter a number 3 It's Prime Enter a number 17 It's Prime Enter a number 15 It's not prime, Divisible by 3 Enter a number 13 It's Prime Enter a number 49 It's not prime, Divisible by 7

// The exit() function causes the program to terminate, and value 0 is used here for successful // termination.

ITCP / Programming Techniques / Programming Fundamentals

Page 24 of 86

The if else statement The if else statement executes one or more commands when a condition is true. If condition is false then those commands are ignored and are not executed. if else is used when we want some commands to be executed when a condition is true and if condition is false then another set of commands should be executed.

Test expression

False

True

Body of if statement 1; statement 2;

Body of else statement 1; statement 2;

Exit

Operation of if else statement


if ( test expression ) statement ; //single statement in if body else statement ; //single statement in else body if (test expression) { statement 1; statement 2; . . statement n; } else { statement 1; statement 2; . . statement n; }

Multiple statements in if body

Multiple statements in else body

syntax of if else statement

ITCP / Programming Techniques / Programming Fundamentals

Page 25 of 86

Counting words and characters in a C/C++ program 25.cpp #include<iostream.h> #include<conio.h> void main(void) { int chcount=0; int wdcount=1; char ch='a'; clrscr(); while(ch!='\r') { ch=getche(); if(ch==' ') wdcount++; else chcount++; } cout<<"\nWords = "<<wdcount; cout<<"\nCharacters = "<<(chcount-1); getch(); } Counting words and characters with different technique 26.cpp #include<iostream.h> #include<conio.h> void main(void) { int chcount=0; int wdcount=1; char ch; clrscr(); while((ch=getche()) !='\r') { if(ch==' ') wdcount++; else chcount++; } cout<<"\nWords = "<<wdcount; cout<<"\nCharacters = "<<chcount; getch(); }

Output hello how are you Words =4 Characters = 14

Output hello how are you Words =4 Characters = 14

ITCP / Programming Techniques / Programming Fundamentals

Page 26 of 86

27.cpp #include<iostream.h> #include<conio.h> void main(void) { clrscr(); int a, b, c; cout<<"Enter values for A, B and C "; cin>>a>>b>>c; if(a==b) if(b==c) cout<<"A. B and C are Equal"; else cout<<"B and C are not Equal"; else cout<<"A and B are not Equal"; getch(); }

Output Enter values for A, B and C 5 5 8 B and C are not Equal Enter values for A, B and C 5 3 3 A and B are not Equal Enter values for A, B and C 4 4 4 A. B and C are Equal Enter values for A, B and C 8 6 8 A and B are not Equal

Defining Label and use of switch, break and goto statements


28.cpp #include<iostream.h> #include<conio.h> void main(void) { clrscr(); int a, b; char ch; cout<<"Enter 1st value ";cin>>a; cout<<"Enter 2nd value ";cin>>b; again:

Output Enter 1st value 5 Enter 2nd value 3 +, -, x, / ? Wrong Choice +, -, x, / @ Wrong Choice +, -, x, / % Wrong Choice +, -, x, / & Wrong Choice +, -, x, / + 5+3=8

cout<<"+, -, x, / "; ch=getche(); cout<<endl; switch(ch) { case '+': cout<<a<<" + "<<b<<" = "<<a+b<<endl; break; case '-': cout<<a<<" - "<<b<<" = "<<a-b<<endl; break; case 'x': cout<<a<<" x "<<b<<" = "<<a*b<<endl; break; case '/': cout<<a<<" / "<<b<<" = "<<a/b<<endl; break; default: cout<<"Wrong Choice\n"; goto again; } getch(); }

ITCP / Programming Techniques / Programming Fundamentals

Page 27 of 86

The switch statement The switch statement is similar to the if else or else if construct but is more flexible. If decision tree is large, and all the decisions depend on the value of the same variable, then it is better to use switch statement instead of series of if else or else if statements.
Integer or character variable

switch variable equals first case body False switch variable equals second case body False switch variable equals third case body False switch variable equals fourth case body False

True

First case body

switch(n) Integer or character { constant case 1: first Statement; causes exit case from switch Statement; body Break;
Integer or character constant case 2: causes exit Statement; from switch Statement; Break; second case body

True

Second case body

True

Third case body

case 3: Statement; Statement; Break; case 4: Statement; Statement; Break; default: Statement; Statement; }
Exit
default body and no break statement

True

Fourth case body

Default body

Operation of switch statement

Syntax of switch statement

The break statement The break keyword causes the entire switch statement to exit. Control goes to the first statement following the end of the switch statement. If break statement is not used then the control passes down to the next case statement and the statements that we do not want to execute, starts executing. If the value of the switch variable doesnt match any of the case constants then control passes to the end of the switch without doing anything.

ITCP / Programming Techniques / Programming Fundamentals

Page 28 of 86

Using multiple cases in switch statement 29.cpp #include<iostream.h> #include<conio.h> void main(void) { clrscr(); int a, b; char ch; cout<<"Enter 1st value ";cin>>a; cout<<"Enter 2nd value ";cin>>b; cout<<"1. Add\n"; cout<<"2. Subtract\n"; cout<<"3. Multiply\n"; cout<<"4. Divide\n"; again:

Output Enter 1st value 5 Enter 2nd value 3 1. Add 2. Subtract 3. Multiply 4. Divide Enter your choice (1-4) 7 Wrong Choice Enter your choice (1-4) k Wrong Choice Enter your choice (1-4) S 5-3=2

cout<<"Enter your choice (1-4) "; ch=getche(); cout<<endl; switch(ch) { case '1': case 'A': case 'a': cout<<a<<" + "<<b<<" = "<<a+b<<endl; break; case '2': case 'S': case 's': cout<<a<<" - "<<b<<" = "<<a-b<<endl; break; case '3': case 'M': case 'm': cout<<a<<" x "<<b<<" = "<<a*b<<endl; break; case '4': case 'D': case 'd': cout<<a<<" / "<<b<<" = "<<a/b<<endl; break; default: cout<<"Wrong Choice\n"; goto again; } getch(); }

ITCP / Programming Techniques / Programming Fundamentals

Page 29 of 86

The Conditional Operator There is a compressed way of expressing the if else statement and is called the conditional operator.

test expression

False

True

Statement 1;

Statement 2;

Exit

Operation of conditional operator

Test-expression ? statement1 : statement2 ;


Conditional operator Syntax of conditional operator
30.cpp #include<iostream.h> #include<conio.h> void main(void) { clrscr(); int a, b; cout<<"Enter 1st value ";cin>>a; cout<<"Enter 2nd value ";cin>>b; Output Enter 1st value 5 Enter 2nd value 3 1st value is greater Enter 1st value 3 Enter 2nd value 5 2nd value is greater

(a > b) ? cout<<"1st value is greater" : cout<<"2nd value is greater"; getch(); }

ITCP / Programming Techniques / Programming Fundamentals

Page 30 of 86

31.cpp #include<iostream.h> #include<conio.h> void main(void) { clrscr(); for(int i=1;i<=8;i++) { for(int j=0;j<20;j++) { char ch=(j%4) ? ' ' : 'x'; cout<<ch; } cout<<endl; } getch(); }

x x x x x x x x

x x x x x x x x

x x x x x x x x

x x x x x x x x

Output x x x x x x x x

ITCP / Programming Techniques / Programming Fundamentals

Page 31 of 86

Logical Operators Other than Arithmetic operators, i.e. +, -, *, /, % etc and Relational Operators, i.e. <, >, <=, >= etc, there is another family of operators called the Logical operators. Logical operators allow the programmer to combine Boolean (True/False) values. Operator && || ! Effect Logical AND Logical OR Logical NOT

Example of the use of Logical Operators is in program 22.cpp in which Logical OR is used.
32.cpp #include<iostream.h> #include<conio.h> void main(void) { clrscr(); int p; do { cout<<"Enter your percentage (0-100) "; cin>>p; } while(p<0 || p>100); if(p>=90) cout<<p<<"% = A+ Grade"; else if(p>=80 && p<90) cout<<p<<"% = A Grade"; else if(p>=70 && p<80) cout<<p<<"% = B Grade"; else if(p>=60 && p<70) cout<<p<<"% = C Grade"; else if(p>=50 && p<60) cout<<p<<"% = D Grade"; else cout<<p<<"% = F Grade"; getch(); } 33.cpp #include<iostream.h> #include<conio.h> void main(void) { clrscr(); char ch='y'; while(!(ch=='n')) { cout<<"\nHello\n"; cout<<"continue ";ch=getche(); } cout<<"\nEnd";getch(); } Output Enter your percentage (0-100) -5 Enter your percentage (0-100) 121 Enter your percentage (0-100) 78 78% = B Grade Enter your percentage (0-100) 92 92% = A+ Grade Enter your percentage (0-100) 84 84% = A Grade Enter your percentage (0-100) 71 71% = B Grade Enter your percentage (0-100) 62 62% = C Grade Enter your percentage (0-100) 57 57% = D Grade Enter your percentage (0-100) 49 49% = F Grade

Output Hello continue a Hello continue y Hello continue k Hello continue n End Keeps on displaying Hello until n is pressed

ITCP / Programming Techniques / Programming Fundamentals

Page 32 of 86

34.cpp #include<iostream.h> #include<conio.h> void main(void) { clrscr(); char ch='y'; while(ch!='n') { cout<<"\nHello\n"; cout<<"continue ";ch=getche(); } cout<<"\nEnd";getch(); }

Output Same program with same output as 33.cpp but written in different style

ITCP / Programming Techniques / Programming Fundamentals

Page 33 of 86

Operators Precedence Operators precedence in C/C++ is Operator Type Unary Arithmetic Relational Logical Conditional Assignment Operators !, ++, --, *, /, % +, <, >, <=, >= ==, != and && or || ?: =, +=, -=, *=, /=, %=

If we want an expression to be evaluated first even its operators precedence is not on the top then it can be done by placing parenthesis around it.

ITCP / Programming Techniques / Programming Fundamentals

Page 34 of 86

The continue statement If we want to come out of the loop we use break statement, similarly if we want to go back to the top of the loop, we use continue statement.

Condition

true continue

Operation of the continue statement


35.cpp #include <iostream.h> #include <conio.h> void main(void) { long divident, divisor; char ch; do { clrscr(); cout<<"Enter Divident ";cin>>divident; cout<<"Enter Divisor ";cin>>divisor; if(divident==0 || divisor==0) { cout<<"Divident or Divisor can not be 0"; getch(); continue; } cout<<divident<<" / "<<divisor<<" = "<<divident / divisor<<endl; cout<<divident<<" % "<<divisor<<" = "<<divident % divisor<<endl; cout<<"Continue "; ch=getche(); }while(ch!='n'); cout<<"\nProgram Finished"; getch(); } Output Enter Divident 15 Enter Divisor 0 Divident or Divisor can not be 0 Enter Divident 70 Enter Divisor 5 70 / 5 = 14 70 % 5 = 0 Continue y Enter Divident 12 Enter Divisor 2 12 / 2 = 6 12 % 2 = 0 Continue n Program Finished

ITCP / Programming Techniques / Programming Fundamentals

Page 35 of 86

The goto Statement goto statement is mostly used in structured programming. In order to use goto statement, we insert a label in our program code at the desired location. Label is a user defined name terminated by a colon sign. The keyword goto is followed by the label name that takes the control to the specified label, i.e. statement; statement; goto again; statement; statement; again: statements in label again; statements in label again;

ITCP / Programming Techniques / Programming Fundamentals

Page 36 of 86

Structures Structure is a collection of variables that can be of the same or different data types. The data items in a structure are called the members of the structure. A user can define its own data types using structures. A structure in C/C++ is like a record of other languages, i.e. Pascal etc.

keyword

name of the structure or tag

struct structure-name { data-type variable-name; data-type variable-name; . . . };


Terminating the structure specifier

Structure members

struct part { int modelnumber; int partnumber; float cost; };

A structure is defined with the name of part that consists of three members. The structure specifier doesnt set aside any space in memory. The structure part is like a new data type but we have not yet created any variables of type part.

S1.cpp #include<iostream.h> #include<conio.h> struct Part { int mn; int pn; float cost; }; void main(void) { clrscr(); Part p1; p1.mn=6244; p1.pn=373; p1.cost-217.5; cout<<"Model Number "<<p1.mn<<endl; cout<<"Part Number "<<p1.pn<<endl; cout<<"Cost is Rs. "<<p1.cost<<endl; getch(); }

Output Model Number 6244 Part Number 373 Cost is Rs. 8.697043e-12

ITCP / Programming Techniques / Programming Fundamentals

Page 37 of 86

Defining Structure Variables A structure variable is defined the same way as a variable of any built-in data type i.e. int age; // age is a variable of built-in data type Integer part p1; //p1 is a variable of structure type part Accessing Structure Members The members of a structure variable are accessed by a dot operator, i.e. p1.mn = 6244; p1.pn = 373; Combining Structure Specifier and Definition Structure specifer and defining structure variables can be combined into a single statement, i.e. Can be done without structure or tag
name, but its variables can not be defined any where else in the program

struct { int mn; int pn; float cost; } p1, p2, p3;
Defined three variables, i.e. p1, p2 and p3

Initializing Structure Members Structure members can be initialized when a structure variable is defined just as variables can be initialized when it is defined, i.e. int a=13; Similarly, Part p1={6244, 373, 217.5};
mn pn cost

Part p2; p2 = p1;


Assigns p1 to p2. The value of each member of p1 is assigned to the corresponding member of p2.

An important point to remember is that structure variables can be assigned to one another when they are of the same structure type. ITCP / Programming Techniques / Programming Fundamentals Page 38 of 86

S2.cpp #include<iostream.h> #include<conio.h> struct Distance { int feet; float inches; }; void main(void) { clrscr(); Distance d1, d2, d3; cout<<"Enter feet for 1st Distance "; cin>>d1.feet; cout<<"Enter inches for 1st Distance "; cin>>d1.inches; cout<<"Enter feet for 2nd Distance "; cin>>d2.feet; cout<<"Enter inches for 2nd Distance "; cin>>d2.inches; d3.inches = d1.inches + d2.inches; d3.feet = 0; if(d3.inches >= 12.0) { d3.inches -= 12.0; d3.feet++; } d3.feet += d1.feet+ d2.feet; cout<<"Total Distance is "<<d3.feet<<"\'-"<<d3.inches<<"\""; getch(); }

Output Enter feet for 1st Distance 5 Enter inches for 1st Distance 7.5 Enter feet for 2nd Distance 6 Enter inches for 2nd Distance 8.5 Total Distance is 12'-4" Note d3 = d1 + d2; is not allowed as Arithmetic Operators, i.e. +, - etc can not be used with the data types that are defined by the user.

ITCP / Programming Techniques / Programming Fundamentals

Page 39 of 86

Structures within Structures Structures can be used inside a structure. Structures within structures are crated when we need a structure to be used in another structure. The following program is an example of the implementation of structures within structures.
S3.cpp #include<iostream.h> #include<conio.h> struct Distance { int feet; float inches; }; struct Room { Distance length; Distance width; }; void main(void) { clrscr(); Room dining; dining.length.feet = 13; dining.length.inches = 6.5; dining.width.feet = 10; dining.width.inches = 5.0; float length = dining.length.feet + dining.length.inches / 12; float width = dining.width.feet + dining.width.inches / 12; cout<<"Dining Room Area is "<< length*width <<" Square Feet"; getch(); } length feet inches Output Dining Room Area is 141.059036 Square Feet

feet inches

width

Initializing Nested Structures Nested structures can be initialized, the way non-nested structures are initialized. The following example shows how the nested structures created in s3.spp is initialized.

Room dining =

13, 6.5

10, 5.0

;
Page 40 of 86

ITCP / Programming Techniques / Programming Fundamentals

Enumerated Data Types Structures can be looked as a way of providing user-defined data types. Another way of defining our own data types is enumerated data type. Enumerated data type is used when a user knows before a list of values that a data type can use.
terminator

enum variable-name { constant1, constant2, . . . . . };


List of constants separated by commas S4.cpp #include <iostream.h> #include <conio.h> enum dow{friday, saturday, sunday, monday, tuesday, wednesday, thursday}; void main(void) { clrscr(); dow d1, d2; d1 = monday; d2 = thursday; int difference = d2 - d1; cout<<"Day between Monday through Thursday are "<<difference<<endl; if(d1<d2) cout<<"Monday comes before Thursday"; getch(); } Output Day between Monday through Thursday are 3 Monday comes before Thursday

In enum, every possible value should have a name, i.e. saturday, sunday etc Variable of enumerated data type, i.e. d1 and d2 can be given any of the value listed in the enum specifier. A value that is not listed in enum specifier can not be assigned to an enum variable. Arithmetic operators can be used with enum types, i.e. +, -, / etc Enumerated data types are treated internally as integers. Normally the first name in the list is given value 0, 1 to second and so on.

ITCP / Programming Techniques / Programming Fundamentals

Page 41 of 86

S5.cpp #include <iostream.h> #include <conio.h> enum boolean{false, true}; void main(void) { clrscr(); char ch; boolean muslim = false; cout<<"Are you Muslim "; ch=getche(); if(ch=='y' || ch=='Y') muslim = true; if(muslim) cout<<"\nYou are Muslim"; else cout<<"\nYou are not Muslim"; getch(); }

Output Are you Muslim y You are Muslim Are you Muslim n You are not Muslim

Specifying Integer Values In enum specifier first member name gets a value 0, second gets 1 and so on. But the order can be changed, i.e. instead of starting from 0, if user wants to start from 5, then 6 and so on, then it can be done the following way. enum dow{friday=5, saturday, sunday, monday, tuesday, wednesday, thursday};

ITCP / Programming Techniques / Programming Fundamentals

Page 42 of 86

Functions A group of statements that perform a specified operation is called a function. In a function we group several program statements into a unit and give that unit a name that is called function name. That function can be invoked any where in the program. Program statements that appear in the program more than once are suitable for creating a function. Function code is stored in only one place in the memory. Another reason for creating functions is that a complex or bigger program code is divided into different functions due to which it becomes easy to manage the program. There are 3 things important related to a function. i) ii) iii) i) Function Declaration Function Calling Function Definition Function Declaration Function Declaration is also called prototyping. Function declaration tells the compiler that at some later point in the program a function will be called. i.e. void line(void); The void line(void); is a function declaration. The first void represents that the return type of the function, void means no return type. The name of the function is line. The void in the parenthesis indicates that line function doesnt take any arguments. Function declaration is terminated with a semicolon. ii) Function Calling Executing or invoking the function is called function calling, i.e. line(); A function is called or executed by its name followed by the parenthesis. The call is terminated by a semicolon. When the function is called or invoked, then the control goes to the area of the program where the function is defined, i.e. control starts executing the statement that are part of the function. After executing the function, control returns to statement following the function call. iii) Function Definition Function definition contains that actual code for the function. The first line of function definition is called the function declarator, that is followed by the function body. Function body is enclosed in braces. Function body contains statements that makeup the function. Function declarator should have the same name as specified in function prototyping and should have the same number of arguments and return type as a function prototype, i.e.

ITCP / Programming Techniques / Programming Fundamentals

Page 43 of 86

void line(void) { for(int a=1;a<=20;a++) cout<<*; cout<<endl; }


F-1.cpp #include<iostream.h> #include<conio.h> void line(void); //Function Declaration void main(void) { clrscr(); line(); //Function Calling cout<<"Hello"<<endl; line(); cout<<"We are studying functions"<<endl; line(); getch(); } void line(void) //Function Declarator { for(int a=1;a<=20;a++) cout<<"*"; cout<<endl; } Output ******************** Hello ******************** We are studying functions ********************

ITCP / Programming Techniques / Programming Fundamentals

Page 44 of 86

Eliminating the Declaration Function declaration can be eliminated in the program if the function definition is specified before the first function call. Although this approach is simpler but is not flexible.
Output Hello void line(void) //Function Definition without Declaration We are studying functions { for(int a=1;a<=20;a++) cout<<"\xCD"; cout<<endl; } F-2.cpp #include<iostream.h> #include<conio.h> void main(void) { clrscr(); line(); cout<<"Hello"<<endl; line(); cout<<"We are studying functions"<<endl; line(); getch(); }

Passing Arguments to Functions ITCP / Programming Techniques / Programming Fundamentals Page 45 of 86

Passing by Value An argument is a piece of data, i.e. a value passes from program to function, and these passed values etc can be used by the function according to the requirements. There are two ways in Passing by Value, through which arguments can be passed to the functions, i.e. i) ii) i) Passing Constants to functions Passing Variables to functions Passing Constants to functions As the name represents, In passing constants to functions, a character, integer or float constant is actually passed as argument to the function, i.e. line(*); square(5);
F-3.cpp #include<iostream.h> #include<conio.h> void chline(char, int); void main(void) { clrscr(); chline('=',10); //Character and Integer constants passed cout<<"Hello"<<endl; chline('*',20); cout<<"We are studying functions"<<endl; chline('-',10); getch(); } void chline(char ch, int n) { for(int a=1;a<=n;a++) cout<<ch; cout<<endl; } Output ========== Hello ******************** We are studying functions ----------

ITCP / Programming Techniques / Programming Fundamentals

Page 46 of 86

ii)

Passing Variables to functions In passing variables to functions, instead of passing a constant, the value that needs to be passes as arguments is placed/stored in a variable, and that variable is used as arguments, i.e. line(a); square(n);
F-4.cpp

#include<iostream.h> #include<conio.h> void chline(char, int); void main(void) { clrscr(); char ch; int n; cout<<"Enter a character "; cin>>ch; cout<<"Enter a value "; cin>>n; chline(ch, n); //Character and Integer variables passed cout<<"Hello"<<endl; chline(ch, n); cout<<"We are studying functions"<<endl; chline(ch, n); getch(); }

Output Enter a character + Enter a value 10 ++++++++++ Hello ++++++++++ We are studying functions ++++++++++

void chline(char ch, int n) { for(int a=1;a<=n;a++) cout<<ch; Passing Structure Variables to functions cout<<endl; The way we pass constants or variables as arguments to functions of the default data }

types, we have the capability of passing constants or variables of the structure types. When passing constants of the structure type, the sequence of the members should be the same as defined in the structures.

Passing Structure Variable to Functions ITCP / Programming Techniques / Programming Fundamentals Page 47 of 86

The way we pass variables of default data types to functions, we can pass variables of structure types. Structures should be defined before the function declaration where variables of that structure type is used.
F-5.cpp #include<iostream.h> #include<conio.h> struct Distance { int feet; float inches; }; void showDistance(Distance); void main(void) { clrscr(); Distance d1, d2; cout<<"Enter feet for 1st Distance "; cin>>d1.feet; cout<<"Enter inches for 1st Distance "; cin>>d1.inches; cout<<"Enter feet for 2nd Distance "; cin>>d2.feet; cout<<"Enter inches for 2nd Distance "; cin>>d2.inches; cout<<"\nFirst Distance is "; showDistance(d1); cout<<"\nSecond Distance is "; showDistance(d2); getch(); } void showDistance(Distance dd) { cout<<dd.feet<<"\'-"<<dd.inches<<"\""; } Output Enter feet for 1st Distance 5 Enter inches for 1st Distance 6.5 Enter feet for 2nd Distance 7 Enter inches for 2nd Distance 8.5 First Distance is 5'-6.5" Second Distance is 7'-8.5"

Returning values from Functions ITCP / Programming Techniques / Programming Fundamentals Page 48 of 86

When a function completes its execution, it can return a single value to the calling program. An important thing to note is that functions can return only a single value. If we want our function to return more than one value, then we can use some other techniques, i.e. If our function returns the value back to a structure variable, an if our structure is a combination of many members of the same or different data types, then it means that one structure variable will be containing more than one members and like this our return values were more than once.
F-6.cpp #include<iostream.h> #include<conio.h> float p2k(float);
Function will return a float type of value void main(void) { clrscr(); float pounds, kilograms; cout<<"Enter weight in Pounds "; cin>>pounds; Returned value will be stored in kilograms variable kilograms = p2k(pounds); cout<<pounds<<" Pounds = "<<kilograms<<" Kilograms"; getch(); } return 0.453592 * pounds ;

Output Enter weight in Pounds 200 200 Pounds = 90.718399 Kilograms

float p2k(float pounds) { float kilograms = 0.453592 * pounds; return kilograms; }

or return (0.453592 * pounds) ;

The return statement ITCP / Programming Techniques / Programming Fundamentals Page 49 of 86

When we call a function than one or more arguments can be sent to a function, but a function can only return one argument. Multiple arguments can not be returned from a function using return statement, but can be made to do so if our return variable is of structure type. Functions return type should always be included in the function declaration. If function doesnt return anything then we use void to indicate that function will not return a value. If a functions return type is not specified in the function declaration then the compiler assumes that functions return type is int. So, if a function is declared as, i.e. test(); then it means that the function will return an integer type of value on completion, as in its declaration, no return type was specified. It is better that we always specify the return type even if it is int. This habit makes the program listing consistent and readable.

ITCP / Programming Techniques / Programming Fundamentals

Page 50 of 86

Returning Structure Variables The way functions return the values of default data types, we can create functions that return variables of structure type.
F-7.cpp #include<iostream.h> #include<conio.h> struct Distance { int feet; float inches; }; Distance sumDistance(Distance, Distance); Sum of Distance is 14'-4" void showDistance(Distance); void main(void) { clrscr(); Distance d1, d2, d3; cout<<"Enter feet for 1st Distance "; cin>>d1.feet; cout<<"Enter inches for 1st Distance "; cin>>d1.inches; cout<<"Enter feet for 2nd Distance "; cin>>d2.feet; cout<<"Enter inches for 2nd Distance "; cin>>d2.inches; d3 = sumDistance(d1, d2); cout<<"\nFirst Distance is "; showDistance(d1); cout<<"\nSecond Distance is "; showDistance(d2); cout<<"\nSum of Distance is "; showDistance(d3); getch(); } Distance sumDistance(Distance dd1, Distance dd2) { Distance dd3; dd3.inches = dd1.inches + dd2.inches; dd3.feet = 0; if(dd3.inches >= 12.0) { dd3.inches -=12.0; dd3.feet++; } dd3.feet += dd1.feet + dd2.feet; return dd3; } void showDistance(Distance dd) { cout<<dd.feet<<"'-"<<dd.inches<<"\""; cout<<endl; } Output Enter feet for 1st Distance 5 Enter inches for 1st Distance 6.5 Enter feet for 2nd Distance 8 Enter inches for 2nd Distance 9.5 First Distance is 5'-6.5" Second Distance is 8'-9.5"

ITCP / Programming Techniques / Programming Fundamentals

Page 51 of 86

Passing by Reference In passing arguments by reference, instead of passing a value to the function, its reference that is the address of that variable is passed. Passing by reference has two main advantages, i.e. i) ii) Function can access the actual variables of the calling function. Provides a mechanism for returning more than one value from the called function to its calling function. A reference provides an alias (different name or second name) for a variable.
F-8.cpp #include<iostream.h> #include<conio.h> void swap(int&, int&); Passing default data types by reference Output Enter value for a 10 Enter value for b 20 Before Swapping A is 10 and B is 20 After Swapping A is 20 and B is 10

void main(void) { clrscr(); int a, b; cout<<"Enter value for a "; cin>>a; cout<<"Enter value for b "; cin>>b; cout<<"\nBefore Swapping"<<endl; cout<<"A is "<<a<<" and B is "<<b<<endl; swap(a, b); cout<<"\nAfter Swapping"<<endl; cout<<"A is "<<a<<" and B is "<<b<<endl; getch(); } void swap(int& aa, int& bb) { int t = aa; aa = bb; bb = t; }

Function has not returned any value but even then the variables in the main function have changed value

ITCP / Programming Techniques / Programming Fundamentals

Page 52 of 86

Passing Structures by Reference


F-9.cpp #include<iostream.h> #include<conio.h> struct Distance { int feet; float inches; }; void scale(Distance&, float); void show(Distance); void main(void) { clrscr(); Distance d1; cout<<"Enter feet for distance "; cin>>d1.feet; cout<<"Enter inches for distance "; cin>>d1.inches; cout<<"Distance is "; show(d1); scale(d1,0.5); cout<<"Distance now is "; show(d1); getch(); } void scale(Distance& d, float factor) { float inches = (d.feet*12 + d.inches ) * factor; d.feet = inches / 12; d.inches = inches - d.feet * 12; } void show(Distance d) { cout<<d.feet<<"\'-"<<d.inches<<"\""; cout<<endl; } Output Enter feet for distance 10 Enter inches for distance 6.6 Distance is 10'-6.6" Distance now is 5'-3.299999"

ITCP / Programming Techniques / Programming Fundamentals

Page 53 of 86

Overloaded Functions Or Function Overloading Overloaded functions perform different activities depending on the kind of data send to it.
F-10.cpp #include<iostream.h> #include<conio.h> void line(void); void line(int); void line(char); void line(int, char); void line(char, int); void main(void) { clrscr(); line(10); line(); line('=',15); line('*'); line(20,'-'); getch(); } void line(void) { for(int a=1;a<=10;a++) cout<<"*"; cout<<endl; } void line(int n) { for(int a=1;a<=n;a++) cout<<"*"; cout<<endl; } void line(char c) { for(int a=1;a<=10;a++) cout<<c; cout<<endl; } void line(int n, char c) { for(int a=1;a<=n;a++) cout<<c; cout<<endl; } void line(char c, int n) { for(int a=1;a<=n;a++) cout<<c; cout<<endl; } Output ********** ********** =============== ********** --------------------

ITCP / Programming Techniques / Programming Fundamentals

Page 54 of 86

Overloaded function or Function overloading means that more than one function with the same name exists in the program. Same function name would be declared and defined in the program more than once, differing in the number of arguments. When the function will be called, then number of arguments will decide that which function will be actually called, i.e. void line(); void line(int); void line(char); void line(int, char); void line(char, int); We can see the above mentioned declarations that all five functions have the same name, i.e. line, but every functions prototype is different from one another, and similarly, when well call the function line than its number of arguments will decide, which function to execute. Function definition doesnt need to be in sequence the way functions are declared, but only requirement is that the number of function definitions should be equal to the number of function declarations.

ITCP / Programming Techniques / Programming Fundamentals

Page 55 of 86

Different types of Arguments in Overloaded Functions or Arguments of different data types in Overloaded Functions In overloaded functions, the compiler can distinguish even if we provide different types of arguments in the functions. The following program has overloaded function with the name of show that has two different types of arguments, i.e. one is of float type and other is of structure type. On calling the function, the arguments decide that will function we want to overload. So, if we send arguments of float type than the function having float type arguments is overload or if we send structure type arguments, then function having structure type arguments is overloaded.
F-11.cpp #include<iostream.h> #include<conio.h> struct Distance { int feet; float inches; }; void show(Distance); void show(float); void main(void) { clrscr(); Distance d1; float allinches; cout<<"Enter feet for distance "; cin>>d1.feet; cout<<"Enter inches for distance "; cin>>d1.inches; cout<<"Enter complete distance in inches "; cin>>allinches; cout<<<"\nFirst distance is "; show(d1); cout<<<"\nSecond distance is "; show(allinches); getch(); } void show(Distance d1) { cout<<d1.feet<<"\'-"<<d1.inches<<"\""<<endl; } void show(float ai) { int feet = ai / 12; float inches = ai - feet * 12; cout<<feet<<"\'-"<<inches<<"\""<<endl; } Output Enter feet for distance 5 Enter inches for distance 5.5 Enter complete distance in inches 95 First distance is 5'-5.5" Second distance is 7'-11"

ITCP / Programming Techniques / Programming Fundamentals

Page 56 of 86

Default Arguments in Function Declaration and Calling A function can be called without specifying all its arguments, if in function declaration we provide default values for the arguments that are not specified. When the function is called, the missing argument is assumed to be the last argument. Missing arguments should always be the trailing arguments.
F-12.cpp #include<iostream.h> #include<conio.h> void line(char='*', int=20); void main(void) { clrscr(); line(); line('='); line('-',10); getch(); } void line(char ch, int n) { for(int a=1;a<=n;a++) cout<<ch; cout<<endl; } Output ******************** ==================== ----------

ITCP / Programming Techniques / Programming Fundamentals

Page 57 of 86

Inline Functions In order to prevent repeating some statement again and again in a program we create function of those statements. Function reduces program code and program seems to be well organized. Whenever a function is called, the control jumps from main program code to the function code and this process requires saving the information of main program and then loading the information of called function that reduces or wastes sometime. If a function that has long code then it is only a small time but if a function is small, i.e. only one or two statements than it is better to repeat it in the program instead of creating its function as it will be wasting more time. Although in this way the program code will become lengthier and program organization will not be as clear as it become in the case of functions, but the benefit in this way will be reduced execution time. Program will run faster but program listing will be longer and more complex A solution to this problem is inline functions. Inline functions are written like normal functions but compiles into inline code instead of into a function. The program remains well organized as function is shown as a separate entity but when the program is compiled, the function body is inserted into the program whenever a function call occurs. Very small functions, i.e. which have one or two statements are candidates to be inlined. For inline functions, the compiler must have seen the function definition (not only the declaration), because it inserts the actual code into the program. So, for inline function, function declaration can be eliminated. Inline keyword is used before that function prototyping to tell the compiler that a function is inline, i.e. inline float ps2kg(float pounds) { return 0.453592 * pounds; }
F-13.cpp #include<iostream.h> #include<conio.h> inline float p2k(float pounds) //inline function { return 0.453592 * pounds; } void main(void) { clrscr(); int pounds; cout<<"Enter weight in pounds "; cin>>pounds; cout<<pounds<<" Pounds = "<<p2k(pounds); cout<<" Kilograms"; getch(); } Output Enter weight in pounds 180 180 Pounds = 81.646561 Kilograms

ITCP / Programming Techniques / Programming Fundamentals

Page 58 of 86

Storage Classes of Variables There are three storage classes of variables i) ii) iii) i) Automatic Variables External Variables Static Variables Automatic Variables Variables defined within function body are called automatic variables. Keyword auto can be used to specify an automatic variable, i.e. void main(void) { auto int age; Auto char grade; . . . } void ps2kg(void) { auto float pounds; . . } As auto is default, i.e. a variable created within a function is always automatic, even if it is not specified, so it is very rarely used. Automatic variable is also called local variable as it is visible only locally in the function where it was created. Local or Automatic variables are stored on the stack, that grows downward in the memory. Automatic variable or Local variable has two important characteristics, i.e. Lifetime and Visibility. Lifetime An automatic variable is not created until the function in which it is defined is called. A variable created in a function will occupy memory for storing values only when the function in which it is defined will execute. The variable will be destroyed and its value will be lost and the memory it has occupied will be released as soon the control transfers from the function in which it was defined. The time period between the creation and destruction of a variable is called lifetime or duration. The lifetime of an automatic variable depends upon the execution of the function in which it is defined. Limiting the lifetime of automatic variables saves memory. If a function is not executing then the variables it uses during execution are only needed when that function executes so removing them when function is not executing frees up memory that can be used by other functions. ITCP / Programming Techniques / Programming Fundamentals Page 59 of 86

Visibility Variables visibility describes where within a program it can be accessed. Automatic variables are only visible and can be accessed within the function in which they are defined. So, the scope of automatic variable is the part of the program where the variable is visible. A programmer can be confident by limiting the visibility of the variables that no function can accidentally change the values of variables defined in other functions. Limiting the visibility is an important feature of Object-Oriented Programming. An automatic variable that is created but not initialized contains garbage values. ii) External Variables External variables are defined outside of (external to) any function. An external variable is visible to all the functions in a program. External variables are also called Global Variables, as they are known by all the functions in a program. External variables normally are defined at the beginning of the listing so they are visible to all the functions. #include <iostream.h> #include <conio.h> char ch=a; void getchar(); void putchar(); void main(void) { clrscr(); while(ch!=\r) { getchar(); Putchar(); } } void getchar() { ch=getch(); } void putchar() { cout<<ch; } An external variable is used when we want to access a variable in more than one function. In OOP, external variables are not used frequently.

ITCP / Programming Techniques / Programming Fundamentals

Page 60 of 86

External or global variables are stored on the heap that grows upward in the memory. Lifetime External variables exist for the life of the program. Memory space is set for them when the program starts and continues in existence until the program ends. Visibility An external variable defined at the start of the program listing will be visible to all the functions defined after the external variable. An external variable that is created but not initialized contains 0. iii) Static Variables There are two types of static variables, i.e. Static Automatic Variables and Static External Variables. A static automatic variable has the visibility of a local variable but the lifetime of an external variable. A static automatic variable is visible only inside the function in which it is defined but remains in existence for the life of the program. Static automatic variables are used when we want a function to remember a value. static keyword is used to create a static automatic variable. A static automatic variable that is created but not initialized contains 0. The initialization of static automatic variables takes place only once, and that is when the first time their function is called.
F-14.cpp #include<iostream.h> #include<conio.h> float getAverage(float); void main(void) { clrscr(); float data=1, average; while(data!=0) { cout<<"Enter a number "; cin>>data; average = getAverage(data); cout<<"New Average is "<<average<<endl; } getch(); } float getAverage(float newdata) { static float total = 0; static int count = 0; count++; total += newdata; return total / count; } Output Enter a number 5 New Average is 5 Enter a number 15 New Average is 10 Enter a number 25 New Average is 15 Enter a number 35 New Average is 20 Enter a number 10 New Average is 18 Enter a number 20 New Average is 18.333334 Enter a number 30 New Average is 20 Enter a number 0 New Average is 17.5

ITCP / Programming Techniques / Programming Fundamentals

Page 61 of 86

Returning by Reference As values can be passed by reference, similarly values can be returned by reference. Returning by reference allows us to use a function call on the left side of equal sign, i.e. A function declaration showing returning by reference is: int& set(void);

ITCP / Programming Techniques / Programming Fundamentals

Page 62 of 86

Creating a Header File


//save this file "line.h" in INCLUDE directory #include<iostream.h> #include<conio.h> void line(void) { for(int a=1;a<=20;a++) cout<<"*"; cout<<endl; } void hello(void) { cout<<"\nHello Hello Hello\n"; } //save this file header.cpp #include<iostream.h> #include<conio.h> #include<line.h> void main(void) { clrscr(); line(); hello(); line(); getch(); } Output ******************** Hello Hello Hello ********************

ITCP / Programming Techniques / Programming Fundamentals

Page 63 of 86

Arrays Array is a collection of variables of the same data type placed contiguously in memory. The items or elements of array are accessed by index number. Arrays can be used to store basic data types, i.e. int, char and float etc. Arrays can also be used as data members in classes. Array can also be used to hold objects. Arrays can also by used in structures, i.e. we can create an array of variable of structure types and we can use array even inside the structures for defining its members etc.
ARR-1.cpp #include<iostream.h> #include<conio.h> void main(void) { clrscr(); int t[7], sum=0; for(int a=0;a<=6;a++) { cout<<"Enter Temperature for day "<<a+1<<" "; cin>>t[a]; sum += t[a]; } for(a=0;a<=6;a++) cout<<"Temperature of day "<<a+1<<" is "<<t[a]<<endl; cout<<"\nAverage temperature is "<<sum/7; getch(); } Output Enter Temperature for day 1 34 Enter Temperature for day 2 32 Enter Temperature for day 3 33 Enter Temperature for day 4 35 Enter Temperature for day 5 36 Enter Temperature for day 6 41 Enter Temperature for day 7 32 Temperature of day 1 is 34 Temperature of day 2 is 32 Temperature of day 3 is 33 Temperature of day 4 is 35 Temperature of day 5 is 36 Temperature of day 6 is 41 Temperature of day 7 is 32 Average temperature is 34

ARR-2.cpp #include<iostream.h> #include<conio.h> void main(void) { clrscr(); int a[5], b[5]; for(int n=0;n<=4;n++) { cout<<"Enter value in element no. "<<n+1<<" "; cin>>a[n]; b[n] = a[n] * a[n]; } cout<<"Array A\tArray B"<<endl; for(n=0;n<=4;n++) cout<<a[n]<<"\t"<<b[n]<<endl; getch(); }

Output Enter value in element no. 1 3 Enter value in element no. 2 4 Enter value in element no. 3 5 Enter value in element no. 4 6 Enter value in element no. 5 7 Array A Array B 3 9 4 16 5 25 6 36 7 49

ITCP / Programming Techniques / Programming Fundamentals

Page 64 of 86

Defining Arrays Like other variables in C/C++, an Array must be defined before it can be used to store information etc. Array definition is:
Bracket delimit Array size

int age[5];
Data type of Array Name of Array Size of the Array

Array Elements The items in an Array are called elements. (Items of a structure are called members). The first element of array starts from 0, so an array of 5 elements has index numbers 0 4.
Age[0] Age[1] Age[2] Age[3] Age[4]

Array elements in Memory Initializing Arrays Arrays can be initialized just as a variable can be initialized at the time of creation. Following example shows an int type of array having 5 elements is initialized.

int age[5] = { 27, 13, 31, 25, 37 };

ITCP / Programming Techniques / Programming Fundamentals

Page 65 of 86

Multidimensional Arrays Arrays can be multidimensional. A two dimensional array consists of Rows and Columns as we have them in a matrix. Following example shows multidimensional array created as having 4 Rows and 3 Columns.

int matrix[4][3];
ARR-3.cpp #include<iostream.h> #include<conio.h> const int ROW = 4; const int COLUMN = 3; void main(void) { clrscr(); int matrix[ROW][COLUMN]; for(int a=0;a<ROW;a++) for(int b=0;b<COLUMN;b++) { cout<<"Enter ROW "<<a+1<<" COLUMN "<<b+1<<" "; cin>>matrix[a][b]; } for(a=0;a<ROW;a++) { for(b=0;b<COLUMN;b++) cout<<matrix[a][b]<<"\t"; cout<<endl; } getch(); } Output Enter ROW 1 COLUMN 1 1 Enter ROW 1 COLUMN 2 2 Enter ROW 1 COLUMN 3 3 Enter ROW 2 COLUMN 1 4 Enter ROW 2 COLUMN 2 5 Enter ROW 2 COLUMN 3 6 Enter ROW 3 COLUMN 1 7 Enter ROW 3 COLUMN 2 8 Enter ROW 3 COLUMN 3 9 Enter ROW 4 COLUMN 1 10 Enter ROW 4 COLUMN 2 11 Enter ROW 4 COLUMN 3 12 1 2 3 4 5 6 7 8 9 10 11 12

ITCP / Programming Techniques / Programming Fundamentals

Page 66 of 86

Passing Arrays to Functions


Passing Arrays to Functions ARR-4.cpp #include<iostream.h> #include<conio.h> const int LENGTH=7; void show(int[LENGTH]); void main(void) { clrscr(); int t[LENGTH]; for(int a=0;a<LENGTH;a++) { cout<<"Enter Temperature for day "<<a+1<<" "; cin>>t[a]; } show(t); getch(); } void show(int temperature[LENGTH]) { int s=0; for(int a=0;a<LENGTH;a++) { cout<<"\nTemperature for day "<<a+1<<" is "; cout<<temperature[a]; s += temperature[a]; } cout<<"\nSum of Temperatures is "<<s; cout<<"\nAverage of Temperature is "<<s/LENGTH; } Output Enter Temperature for day 1 23 Enter Temperature for day 2 24 Enter Temperature for day 3 25 Enter Temperature for day 4 26 Enter Temperature for day 5 27 Enter Temperature for day 6 28 Enter Temperature for day 7 29 Temperature for day 1 is 23 Temperature for day 2 is 24 Temperature for day 3 is 25 Temperature for day 4 is 26 Temperature for day 5 is 27 Temperature for day 6 is 28 Temperature for day 7 is 29 Sum of Temperatures is 182 Average of Temperature is 26

ITCP / Programming Techniques / Programming Fundamentals

Page 67 of 86

Array of Structures
ARR-5.cpp #include<iostream.h> #include<conio.h> const int LENGTH = 3; struct part { int mn; int pn; float cost; }; void main(void) { clrscr(); part p[LENGTH]; for(int a=0;a<LENGTH;a++) { cout<<"\nItem Number "<<a+1<<endl; cout<<"Enter Model Number ";cin>>p[a].mn; cout<<"Enter Part Number ";cin>>p[a].pn; cout<<"Enter Cost ";cin>>p[a].cost; } clrscr(); for(a=0;a<LENGTH;a++) { cout<<"\nItem Number "<<a+1<<endl; cout<<"\nModel Number "<<p[a].mn; cout<<"\nPart Number "<<p[a].pn; cout<<"\nCost is "<<p[a].cost<<" Rs. "<<endl; } getch(); } Output Item Number 1 Enter Model Number 10 Enter Part Number 100 Enter Cost 1000 Item Number 2 Enter Model Number 11 Enter Part Number 110 Enter Cost 2000 Item Number 3 Enter Model Number 12 Enter Part Number 120 Enter Cost 3000 Item Number 1 Model Number 10 Part Number 100 Cost is 1000 Rs. Item Number 2 Model Number 11 Part Number 110 Cost is 2000 Rs. Item Number 3 Model Number 12 Part Number 120 Cost is 3000 Rs.

ITCP / Programming Techniques / Programming Fundamentals

Page 68 of 86

Passing Array into another Array


ARR-6.cpp #include<iostream.h> #include<conio.h> void main(void) { clrscr(); int a[5], b[5]; for(int x=0;x<5;x++) { cout<<"Enter element no. "<<x+1<<" "; cin>>a[x]; b[x] = a[x]; } cout<<"\nA\tB\n"; for(x=0;x<5;x++) cout<<a[x]<<"\t"<<b[4-x]<<endl; getch(); } Output Enter element no. 1 1 Enter element no. 2 2 Enter element no. 3 3 Enter element no. 4 4 Enter element no. 5 5 A 1 2 3 4 5 B 5 4 3 2 1

ARR-7.cpp #include<iostream.h> #include<conio.h> void main(void) { clrscr(); int a[5], l, h; for(int x=0;x<5;x++) { cout<<"Enter element no. "<<x+1<<" "; cin>>a[x]; } l = a[0], h=a[0]; for(x=0;x<5;x++) { if(a[x]<l) l = a[x]; if(a[x]>h) h = a[x]; } for(x=0;x<5;x++) cout<<a[x]<<endl; cout<<"Highest Value entered is "<<h<<endl; cout<<"Lowest value entered is "<<l<<endl; getch(); }

Output Enter element no. 1 5 Enter element no. 2 78 Enter element no. 3 3 Enter element no. 4 256 Enter element no. 5 17 5 78 3 256 17 Highest Value entered is 256 Lowest value entered is 3

ITCP / Programming Techniques / Programming Fundamentals

Page 69 of 86

Objects containing Arrays


ARR-8.cpp #include<iostream.h> #include<conio.h> const int MAX=50; class Stack { private: int st[MAX]; int top; public: Stack() { top = -1; } void push(int var) { st[++top] = var; } int pop() { return st[top--]; } }; void main(void) { clrscr(); Stack s1; s1.push(11); s1.push(22); s1.push(33); s1.push(44); s1.push(55); cout<<"1. "<<s1.pop()<<endl; cout<<"2. "<<s1.pop()<<endl; cout<<"3. "<<s1.pop()<<endl; cout<<"4. "<<s1.pop()<<endl; cout<<"5. "<<s1.pop()<<endl; getch(); } 1. 55 2. 44 3. 33 4. 22 5. 11 Output

ITCP / Programming Techniques / Programming Fundamentals

Page 70 of 86

Array of Objects
ARR-9.cpp #include<iostream.h> #include<conio.h> const int MAX=10; class Distance { private: int feet; float inches; public: void getDist() { cout<<"\nEnter feet ";cin>>feet; cout<<"\nEnter inches ";cin>>inches; } void showDist() { cout<<feet<<"\'-"<<inches<<"\""; } }; void main(void) { clrscr(); Distance dist[MAX]; int n=0; char ch; cout<<endl; do { cout<<"\nEnter distance number "<<n+1; dist[n++].getDist(); cout<<"Enter another ";cin>>ch; }while(ch!='n'); for(int j=0;j<n;j++) { cout<<"\nDistance number "<<j+1<<" is "; dist[j].showDist(); } getch(); } Output Enter distance number 1 Enter feet 4 Enter inches 5.5 Enter another y Enter distance number 2 Enter feet 3 Enter inches 5.9 Enter another y Enter distance number 3 Enter feet 6 Enter inches 6.5 Enter another n Distance number 1 is 4'-5.5" Distance number 2 is 3'-5.9" Distance number 3 is 6'-6.5"

ITCP / Programming Techniques / Programming Fundamentals

Page 71 of 86

Arrays of Characters (Strings)


ARR-10.cpp #include<iostream.h> #include<conio.h> void main(void) { clrscr(); char str[50]; cout<<"Enter a String "; cin>>str; cout<<"You Entered "<<str; getch(); } Output Enter a String Hello You Entered Hello Enter a String Hello Everyone You Entered Hello Enter a String NationalUniversityOfModern LanguagesH9IslamabadPakistan You Entered NationalUniversityOfModern LanguagesH9IslamabadPakistan

String

H e l l o
\0

Characters in String

String Buffer str


Unused part of the buffer

Terminating 0 or null byte . . . . .

ITCP / Programming Techniques / Programming Fundamentals

Page 72 of 86

Reading Embedded Blanks


ARR-11.cpp #include<iostream.h> #include<conio.h> void main(void) { clrscr(); char str[10]; cout<<"Enter a String "; cin.get(str,10); cout<<"You Entered "<<str; getch(); } Output Enter a String How Are You You Entered How Are Y

//get is a member function of // the stream class of which // cin is an object

Avoiding Buffer Overflows


ARR-12.cpp #include<iostream.h> #include<iomanip.h> #include<conio.h> const int MAX=10; void main(void) { clrscr(); char str[MAX]; cout<<"Enter a String "; cin>>setw(MAX)>>str; cout<<"You Entered "<<str; getch(); } Output Enter a String abcdefghijklmnop You Entered abcdefghi

ITCP / Programming Techniques / Programming Fundamentals

Page 73 of 86

String Constants
ARR-13.cpp #include<iostream.h> #include<conio.h> void main(void) { clrscr(); char str[] = "National University of Modern Languages"; // or // char str[] = {'N','a','t', . . . . .}; cout<<str; getch(); } Output National University of Modern Languages

Reading Multiple Lines


ARR-14.cpp #include<iostream.h> #include<conio.h> const int MAX=200; void main(void) { clrscr(); char str[MAX]; cout<<"Enter a String "; cin.get(str,MAX,'!'); cout<<"You Entered "<<str; getch(); } Output Enter a String National University of Modern Languages ! You Entered National University of Modern Languages

ITCP / Programming Techniques / Programming Fundamentals

Page 74 of 86

Copying a String
ARR-15.cpp #include<iostream.h> #include<conio.h> #include<string.h> const int MAX=10; void main(void) { clrscr(); char name1[MAX], name2[MAX]; cout<<"Enter a String "; cin.get(name1, MAX); strcpy(name2, name1); cout<<"Name 1 = "<<name1<<endl; cout<<"Name 2 = "<<name2<<endl; getch(); } Output Enter a String NUML Name 1 = NUML Name 2 = NUML

ITCP / Programming Techniques / Programming Fundamentals

Page 75 of 86

Arrays of Strings
ARR-16.cpp #include<iostream.h> #include<conio.h> const int DAYS = 7; const int LENGTH = 10; void main(void) { clrscr(); char weekdays[DAYS][LENGTH] = {"Friday","Saturday","Sunday","Monday", "Tuesday","Wednesday","Thursday"}; for(int a=0;a<DAYS;a++) cout<<weekdays[a]<<endl; getch(); } Output Friday Saturday Sunday Monday Tuesday Wednesday Thursday

10 0
0 1 2

1 r a u u h

2 i t n n e d u

3 d u d d s n r

3 a r a a d e s

5 y d y y a s d

9
weekday[0] weekday[1] weekday[2] weekday[3]

F S S T T

3 4 5 6

M o W e

y d a a y y a a

weekday[4] weekday[5] weekday[6]

ITCP / Programming Techniques / Programming Fundamentals

Page 76 of 86

Pointers A variable that holds an address value is called a pointer variable or pointer. Pointers are used for Accessing Array elements Passing arguments to a function when the function needs to modify the original argument Passing arrays and strings to functions Obtaining memory from the system

The address stored in a pointer should be of the same type as the pointer, i.e. address of a float variable can not be assigned to a pointer of integer. There is a general purpose pointer that can point to any data type and is called pointer to void
P-1.cpp #include<iostream.h> #include<conio.h> Address of operator void main(void) { clrscr(); int v1=11, v2=22,v3=33; cout<<"Value of v1 is "<<v1<<" and address is "<<&v1<<endl; cout<<"Value of v2 is "<<v2<<" and address is "<<&v2<<endl; cout<<"Value of v3 is "<<v3<<" and address is "<<&v3<<endl; getch(); } Output Value of v1 is 11 and address is 0x8fc3fff4 Value of v2 is 22 and address is 0x8fc3fff2 Value of v3 is 33 and address is 0x8fc3fff0

P-2.cpp #include<iostream.h> #include<conio.h> void main(void) { clrscr(); int v1=11, v2=22; cout<<"Value of v1 is "<<v1<<endl; cout<<"Value of v2 is "<<v2<<endl; cout<<"Address of v1 is "<<&v1<<endl; cout<<"Address of v2 is "<<&v2<<endl; int* p1; //Pointer to Integer p1 = &v1; // Store address of v1 in pointer p1 cout<<"Value of p1 is "<<p1<<endl; p1 = &v2; cout<<"Value of p1 is "<<p1<<endl; getch(); }

Output Value of v1 is 11 Value of v2 is 22 Address of v1 is 0x8fc6fff4 Address of v2 is 0x8fc6fff2 Value of p1 is 0x8fc6fff4 Value of p1 is 0x8fc6fff2

ITCP / Programming Techniques / Programming Fundamentals

Page 77 of 86

P-3.cpp #include<iostream.h> #include<conio.h> void main(void) { clrscr(); int v1=11, v2=22; int* p1; p1 = &v1; // Store address of v1 in pointer p1 cout<<"Value of v1 is "<<*p1<<endl; p1 = &v2; cout<<"Value of v2 is "<<*p1<<endl; getch(); } P-4.cpp #include<iostream.h> #include<conio.h> void main(void) { clrscr(); int v1, v2; int* p1; p1 = &v1; *p1 = 10; cout<<"v1 = "<<v1<<endl; v2 = *p1 + *p1 + 5; cout<<"v2 = "<<v2<<endl; getch(); }

Output Value of v1 is 11 Value of v2 is 22 When an asterisk is used before a variable name, i.e. *p1, then it is called Indirection Operator, i.e. the value of the variable pointed to by. So *p1 represents the value of the variable pointed to by p1.

Output v1 = 10 v2 = 25

P-5.cpp #include<iostream.h> #include<conio.h> void main(void) { clrscr(); int i=10; float f=15.27; int* pi; float* pf; void* gp; //pointer to void, i.e. general purpose pointer pi = &i; //correct pf = &f; //correct cout<<"\nValue of i is "<<i<<endl; cout<<"address of i is "<<pi<<endl; cout<<"\nvalue of f is "<<f<<endl; cout<<"address of f is "<<pf<<endl; // pi = &f; //incorrect // pf = &i; //incorrect gp = &i; //correct // *gp = *gp * *gp; //incorrect // cout<<"value of gp is "<<*gp<<endl; //incorrect cout<<"\naddress of gp is "<<gp<<endl; gp = &f; //correct // *gp = *gp * *gp; //incorrect // cout<<"value of gp is "<<*gp<<endl; //incorrect cout<<"\naddress of gp is "<<gp<<endl; getch(); }

Output Value of i is 10 address of i is 0x8f7efff4 value of f is 15.27 address of f is 0x8f7efff0 address of gp is 0x8f7efff4 address of gp is 0x8f7efff0

ITCP / Programming Techniques / Programming Fundamentals

Page 78 of 86

Pointer to Arrays
P-6.cpp #include<iostream.h> #include<conio.h> void main(void) { clrscr(); int a[5] = {15,35,24,87,42}; for(int b=0;b<5;b++) cout<<*(a+b)<<endl; getch(); }
a a[0] a1] *(a+2) a[2] a[3] a[4]

Output 15 35 24 87 42

*(a+b) is equivalent to a[b]

P-7.cpp This program sends the address of array to a function that displays the array elements #include<iostream.h> #include<conio.h> void show(int*); void main(void) { clrscr(); int a[5] = {13,21,78,32,64}; show(a); getch(); } void show(int* c) { cout<<"Press any key to display array"<<endl; getch(); for(int b=0;b<5;b++) cout<<*(c+b)<<endl; }

Output Press any key to display array 13 21 78 32 64

ITCP / Programming Techniques / Programming Fundamentals

Page 79 of 86

Pointer constants and pointer variables


P-8.cpp #include<iostream.h> #include<conio.h> void main(void) { clrscr(); int a[5] = {13,21,78,32,64}; int* p; p = a; //points to a for(int b=0;b<5;b++) cout<<*(p++)<<endl; getch(); } P-9.cpp Passing Reference as Arguments #include<iostream.h> #include<conio.h> void square(int&); void main(void) { clrscr(); int v = 5; cout<<"Value is "<<v<<endl; square(v); cout<<"Square is "<<v<<endl; getch(); } void square(int& n) { n*=n; } P-10.cpp Passing Pointer as Arguments #include<iostream.h> #include<conio.h> void square(int*); void main(void) { clrscr(); int v = 5; cout<<"Value is "<<v<<endl; square(&v); cout<<"Square is "<<v<<endl; getch(); } void square(int* n) { *n = *n * *n; } Output Value is 5 Square is 25 Output 13 21 78 32 64

Output Value is 5 Square is 25

Passing variable by reference

Passing pointer as arguments

ITCP / Programming Techniques / Programming Fundamentals

Page 80 of 86

Pointers and Functions


P-11.cpp #include<iostream.h> #include<conio.h> void cube(int*); void main(void) { clrscr(); int a; cout<<"Enter a Value "; cin>>a; cout<<"Cube of "<<a<<" is "; cube(&a); getch(); } void cube(int* n) { *n = *n * *n * *n; cout<<*n; } Output Enter a Value 3 Cube of 3 is 27

ITCP / Programming Techniques / Programming Fundamentals

Page 81 of 86

New and Delete Operator


P-12.cpp #include<iostream.h> #include<conio.h> #include<string.h> Output p = National University of Modern Languages

void main(void) { clrscr(); char* name="National University of Modern Languages"; int l = strlen(name); char* p; p = new char[l]; Returns a pointer that points to a section of memory capable of storing string name strcpy(p,name); cout<<"p = "<<p; delete[] p; Returns memory to the Operating System that was taken using getch(); new operator }

ITCP / Programming Techniques / Programming Fundamentals

Page 82 of 86

Pointers to Objects
P-13.cpp #include<iostream.h> #include<conio.h> class Distance { private: int feet; float inches; public: void getDist() { cout<<"\nEnter feet ";cin>>feet; cout<<"Enter inches ";cin>>inches; } void showDist() { cout<<endl<<feet<<"\'-"<<inches<<"\""<<endl; } }; void main(void) { clrscr(); Distance d1; d1.getDist(); d1.showDist(); Distance* dp; dp = new Distance; dp -> getDist(); // or (*dp).getDist(); dp -> showDist(); getch(); } Output Enter feet 5 Enter inches 5.5 5'-5.5" Enter feet 6 Enter inches 6.5 6'-6.5"

ITCP / Programming Techniques / Programming Fundamentals

Page 83 of 86

Passing Array to Functions using Pointer notation


P-14.cpp #include<iostream.h> #include<conio.h> void square(int*); void main(void) { clrscr(); int a[5]={0}; for(int n=0;n<5;n++) { cout<<"Enter element no. "<<n+1<<" "; cin>>a[n]; } square(a); for(n=0;n<5;n++) cout<<a[n]<<endl; getch(); } void square(int* v) { for(int i=0;i<5;i++) *v++ *= *v; } Swapping Through Pointers P-15.cpp #include<iostream.h> #include<conio.h> void change(int*, int*); void main(void) { clrscr(); int n1=99, n2=11; int n3=22, n4=88; cout<<"Befor Swapping"<<endl; cout<<"n1 = "<<n1<<" n2 = "<<n2<<endl; cout<<"n3 = "<<n3<<" n4 = "<<n4<<endl; change(&n1,&n2); change(&n3,&n4); cout<<"After Swapping"<<endl; cout<<"n1 = "<<n1<<" n2 = "<<n2<<endl; cout<<"n3 = "<<n3<<" n4 = "<<n4<<endl; getch(); } void change(int* s1,int* s2) { int t = *s1; *s1 = *s2; *s2 = t; } Output Befor Swapping n1 = 99 n2 = 11 n3 = 22 n4 = 88 After Swapping n1 = 11 n2 = 99 n3 = 88 n4 = 22 Output Enter element no. 1 3 Enter element no. 2 12 Enter element no. 3 9 Enter element no. 4 3 Enter element no. 5 7 9 144 81 9 49

Strings as Function Arguments ITCP / Programming Techniques / Programming Fundamentals Page 84 of 86

Pointers and Strings Pointers to String Constants


P-16.cpp #include<iostream.h> #include<conio.h> void main(void) { clrscr(); char s1[]="NUML"; //Defined as Array char* s2 ="NUML"; //Defined as Pointer cout<<s1<<endl; cout<<s2<<endl; s2++; //Starts pointing to U instead of N in NUML cout<<s2<<endl; getch(); } Output NUML NUML UML

ITCP / Programming Techniques / Programming Fundamentals

Page 85 of 86

Strings as Function Arguments


P-17.cpp #include<iostream.h> #include<conio.h> void dispString(char*); void main(void) { clrscr(); char name[]="National University of Modern Languages"; dispString(name); getch(); } void dispString(char* s) { while(*s) //until null character cout<<*s++; //print characters } Output National University of Modern Languages

ITCP / Programming Techniques / Programming Fundamentals

Page 86 of 86

You might also like