Programming With C++ Enhanced Lecture Notes GC University Faisalabad. Resource Person: S. M. Alay-e-Abbas
Programming With C++ Enhanced Lecture Notes GC University Faisalabad. Resource Person: S. M. Alay-e-Abbas
Alay-e-Abbas
Contents
INTRODUCTION: ............................................................................................................. 3 How a Program is written in Turbo C++: ....................................................................... 4 Structure of C++: ............................................................................................................ 4 Preprocessor Directives: ................................................................................................. 4 Header File:..................................................................................................................... 6 The main( ) Function: ..................................................................................................... 6 C++ Statements:.............................................................................................................. 6 Keywords and Tokens: ................................................................................................... 7 Variables: ........................................................................................................................ 7 Variable name: ................................................................................................................ 7 Data Type in C++: .......................................................................................................... 7 Declaration of Variables: ................................................................................................ 9 Constants:........................................................................................................................ 9 Arithmetic operators: .................................................................................................... 10 Assignment Statement: ................................................................................................. 11 Order of precedence:..................................................................................................... 11 Cout object:................................................................................................................... 12 Cin object:..................................................................................................................... 12 Escape Sequences: ........................................................................................................ 13 Manipulators: ................................................................................................................ 14 Increment Operator (++ ) :............................................................................................ 17 Decrement Operator( - -): ............................................................................................. 17 Comment Statement:..................................................................................................... 18 Exercise:........................................................................................................................ 19 Functions:.......................................................................................................................... 21 Built-in function:........................................................................................................... 21 Conio.h Console input output functions: ...................................................................... 22 math.h Function: ........................................................................................................... 23 complex.h Function: ..................................................................................................... 27 Some other Function:.................................................................................................... 28 Conditional Statements: .................................................................................................... 32 The Nested if statement: ............................................................................................... 36 if-else-if statement:.................................................................................................... 37 Switch statement: .......................................................................................................... 38 Conditional Operators:.................................................................................................. 39 Logical Operators: ........................................................................................................ 39 goto control transfer statement:................................................................................. 41 Loops: ........................................................................................................................... 42 while Loop:................................................................................................................ 45 do-while Loop: .......................................................................................................... 46 The Nested Loops: ........................................................................................................ 48 The break and continue statements:.............................................................................. 50 Arrays:............................................................................................................................... 51
Programming with C++ Enhanced Lecture Notes GC University Faisalabad. Resource Person: S. M. Alay-e-Abbas
1-D array: ...................................................................................................................... 51 Multi-dimensional Arrays:............................................................................................ 54 Pointers: ............................................................................................................................ 58 Reference operator &: ................................................................................................ 58 Dereference operator *:.............................................................................................. 59 Declaring variables of pointer type:.............................................................................. 60 Pointers and arrays:....................................................................................................... 61 Pointer initialization...................................................................................................... 62 Pointer arithmetics ........................................................................................................ 63 Pointers to functions ..................................................................................................... 65 User Defined Functions: ................................................................................................... 67 The function declaration: .............................................................................................. 67 Calling the function: ..................................................................................................... 68 Function definition:....................................................................................................... 68 Passing Arguments to a function: ................................................................................. 69 Constants as argument: ................................................................................................. 70 Variables as argument:.................................................................................................. 71 Arrays as Arguments: ................................................................................................... 73 Returning values from function: ................................................................................... 74 Overloaded function: .................................................................................................... 75 Inline Function:............................................................................................................. 77 (C programmers should note that inline functions largely take the place of #define macros in C.)................................................................................................................. 79 Local variables:............................................................................................................. 79 Global variables: ........................................................................................................... 79 Static variables:............................................................................................................. 80 Local and Global Functions:......................................................................................... 80 File System in C++: .......................................................................................................... 80 Streams and files:.......................................................................................................... 80 Opening files:................................................................................................................ 81 Testing file open operation: .......................................................................................... 82 Formatted input/output: ................................................................................................ 83 End-of-file:.................................................................................................................... 85 Output to printer:........................................................................................................... 86
Programming with C++ Enhanced Lecture Notes GC University Faisalabad. Resource Person: S. M. Alay-e-Abbas
INTRODUCTION:
C++ program pronounced as see plus plus is an advanced version of C which was a procedural or non object oriented language, while C++ is. Ken Thompson developed B Language which was used to develop UNIX system B was developed at Bell Labs. After B,C was developed at Bell Labs by Dannis Ritche which replaced B language in 1980`s. C was extended to C++ by Bjarne Stnoustuup .Which had improved quality and was object-oriented .The C++ compilers available are Turbo C++ (ver 3.0 by Borlad) works in MS-Dos environment whereas the Microsoft visual C++ compiler works in GUI environment. We will use Turbo C++. The executable file is located at C:\TC\BIN\Tc.exe In C drive, this will open the source code editor. The editor has following menu File: It is used to Open, Quit, Save or produce new files for writing programs. To change some directory of C++ where it is located. To print the program and to go back to DosPrompt. Edit: It contains undo, redo, copy, cut, paste, clear and show copied items Search: To find or replaced words in the written program and locate errors or go to specified lines Run: To run a program, go to cursor position, etc. Compile: All programs need to be compiled or collected together before running. The built in checking system of the software compiles the source code which is written in English to machine language. After making a program always compile it and then run to avoid errors. Compile also links the written code to libraries and builds the object code or machine code Debug: It has options to inspect errors, faults in the code, not needed always because compile can also detect errors in the source code Project: Has options for projects, which are often used in Object-Oriented-programming. Options: It has the preferences of the program also information on properties of libraries, compilers, etc. Windows: To change shape size and other options of the tc.exe window
Programming with C++ Enhanced Lecture Notes GC University Faisalabad. Resource Person: S. M. Alay-e-Abbas Help: Provides help on all menu items we have discussed
in a file with extension CPP. It is a text file. The edition is used to write C++ source code. After writing source code we compile it, it is translated into object code or machine code which is in machine language (consisting of symbols rather than characters) and is stored in file with extension .obj. This file is linked to libraries which contain info about the functions or tokens used in the program. Afterwards an executable file with extension .exe is created which is used to run or use the program. It is an MS-Dos command prompt type environment which works on the basis of our source code or program.
Programming with C++ Enhanced Lecture Notes GC University Faisalabad. Resource Person: S. M. Alay-e-Abbas Instruction given to compiler before beginning a program are called preprocessor directives also called compiler directives e.g. to include a file that contains info about mathematical operations we write. SYNTAX #include<header file name> before the main function so that computer or the program knows how to calculate tan, cos etc. of a given value The preprocessor directives starts with a # sign and keywords include or define. Ex:#include<iostream.h> #include<conio.h> main( ) { cout <<My First Program; all statements end with ; getch( ); return 0; } Will give output when compiled and run My First Program
The SYNTAX of define directive is #define identifier value e.g #define pi 3.1417 Defines the value of identifier pi as 3.1417 that can be used in program where needed Also the syntax can be #define FNFH(X,Y) Y*sin(X) // Which defines function FNFH of two variables X and Y as Y*sin(X). Using FNFH(2,1) in a program will yield the result of 1*sin(2). There is also using identifier not supported in Turbo C++.
Programming with C++ Enhanced Lecture Notes GC University Faisalabad. Resource Person: S. M. Alay-e-Abbas
Header File:
It is source file containing definition of library functions to be used in a program The syntax to include header file is #include<File Name> where filename is iostrean.h, conio.h etc and is written inside angle brackets < >
C++ Statements:
These are written under the main( ) inside the curly brackets { }.These constitute the body of the program each statement ends with a semicolon i.e. ; Almost all statements are written in lower case e.g. main( ) { statements come here }
Programming with C++ Enhanced Lecture Notes GC University Faisalabad. Resource Person: S. M. Alay-e-Abbas
Variables:
A quantity whose values may change during the execution of the program (actually it is input during execution) is called a variable. It represents a storage location in memory of computer and is reserved so that when needed it may be used e.g. main( ) { int a,b; } a and b are variables and are input during execution of program
Variable name:
first character must be alphabetic underscore can be used first blank space are not allowed #,<,>,^ are not allowed in variables names keywords not allowed no two variables can have same name
Programming with C++ Enhanced Lecture Notes GC University Faisalabad. Resource Person: S. M. Alay-e-Abbas 5-boolean bool
Int:
It is integer type data with no decimal points e.g 304,1,502,98 int can have value between -32768_____32767 Other classes are short int: long int: unsigned int: it is between -32768 to 32767 it is between-2147483648 to 2147483647 it is between 0 to 65,535
Float:
It is a real number like 0.56, 23.00 and 41.94 The range is between 3.4*10-32 to 3.4*1032 Long float: Its capacity in bytes stones double the data as of float.
Double:
Range
(8 bytes )
1.7*10-308 to1.7*10308
Long double:
Even larger
3.4*10-4932 to 3.4*104932
Bool:
Stands for Boolean for logical type data true, false. Not available in the Turbo compiler. Works only in visual C++. Only stores 1 on 0
Programming with C++ Enhanced Lecture Notes GC University Faisalabad. Resource Person: S. M. Alay-e-Abbas
Declaration of Variables:
Assigning name and type of variable in program is called declaration of variables SYNTAX is type list of variables; int a, b; float xyz, temp, avg; A variable can also be given a value during declaration which is called initialing a variable, example below declares, initializes and then prints the variable value on screen Ex: # include<iostneam.h> # include<conio.h> main( ) { int abc=4, b=1997; cout<< Ali is in class << abc<<endl; cout<< He was born in<<b; getch( ); } Ali is in class 4 He was born in 1997 variable type e.g. int, float etc. Names of variables of same data type are separated by commas. e.g.
Constants:
Constants types are 1) 2) 3) Integer constants: These can be positive or negative. e.g. cout<<254 and cout<<-60 Floating constants: these can be positive or negative. e.g. cout<<-5.9 and cout<< 485.98e2. Character constants: e.g. cout<< a and cout<< +
Programming with C++ Enhanced Lecture Notes GC University Faisalabad. Resource Person: S. M. Alay-e-Abbas 4) String constants or Literals: e.g. cout << Pakistan; etc const type expression; e.g. const float pi=3.1417;
10
Arithmetic operators:
To add, sub, etc numerical values following can be used in C++ + Ex: #include<iostream.h> #include<conio.h> main( ) { int a, b, p, s, m, r; float d; cout<< Enter first value:; cin>> a; cout<< Enter second value:; cin>> b; p = a + b; s = a - b; m = a * b; d = a / b; r = a % b; //remainder only for int data cout<< addition, subtraction, multiplication, division and remainder are<<p<<s<<m<<d and<<r << respectively; getch( ); return 0; } addition, subtraction, multiplication, division and remainder are 7 3 10 2 and 1 respectively add sub * / multiply devide % remainder
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
11
Assignment Statement:
To input formulas or equations SYNTAX is var=expression; Ex: #include<lostream.h> #include<conio.h> void main( ) { int a,b,c; cin>>b>>c; a=b*c; cout<<a; getch( ); } Furthermore, the compound assignments are a = b = 2+c; and also a = a + 2; is equivalent to a + = 2; is the assignment statement 2 4 8
Order of precedence:
The order or rule how arithmetic is done is called order of precedence one must use correct order of precedence in an assignment statement for getting correct answers the rules are 1.multiplications and divisions are done first 2.addition and subtraction afterwards 3.expression in parenthesis are evaluated first if used 4.compunted parenthesis starts evaluating from the inner most parenthesis
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
12
Cout object:
Stands for console output and is used to display or print the output of a program. Console being the monitor SYNTAX is cout<<[const or var or statement]; Cout = output stream, object << = put to operator or insertion operation cont or var or statement is the output for multiple outputs of different type the example is cout<< one killo=<<1000<< grams; Ex: #include<iostream.h> #include<conio.h> main( ) { clrscr( ); cout<< C++ is a powerful language; cout<<endl<< OK; getch( ); return 0; }
Cin object:
Stands for console input used to enter the data into the program SYNTAX is cin>> var or char; cin = input stream, object >> = get from or extraction operation
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas var or char is the input type For multiple inputs example is: cin>>a>>b>>c;. Press enter after giving values of each Ex: #include<iostream.h> #include<conio.h> void main() { clrscr(); int a, b; cout<< Enter two values \n; cin>> a >> b; cout<< \n Your entered values are a =<<a<< b=<<b; getch(); }
13
Escape Sequences:
\n
When used in output shifts the cursor to next line e.g cout<< I \n am\n Pakistani; gives I am Pakistani
\a
produces a beep in the computer speaker
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
14
\t
to give tabs between output cout<< A\t B \t C \t D; gives output as A B C D
\
to print double quotation mark cout<< \PAK; PAK some other escape sequences are: \t \v \b \f \\ \? \' Horizontal Tab Vertical Tab Backspace Form feed Backslash Question mark Single quote
Manipulators:
There are numerous manipulators available in C++ we discuss a few important ones only. end l: To end line and print something in the next line The SYNTAX is endl cout<< I am<<end l<< Pakistani; setw(x): This manipulator sets the minimum field width on output. The SYNTAX is: setw(x) gives I am Pakistani
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas Here setw causes the number or string that follows it to be printed within a field of x characters wide and x is the argument set in setw(x) manipulator. The header file that must be included while using setwmanipulator is <iomanip.h> #include <iostream.h> #include <iomanip.h> void main( ) { int x1=12345; cout << setw(8) << Exforsys << setw(20) << Values << endl << setw(8) << E1234567 << setw(20)<< x1 << endl; } The output is: Exforsys E1234567 setfill(x): This is used after setw manipulator. If a value does not entirely fill a field, then the character specified in the setfill(x) argument of the manipulator is used for filling the fields. #include <iostream.h> #include <iomanip.h> void main( ) { cout << setw(10) << setfill('$') << 50 << 33 << endl; } The output of the above program is $$$$$$$$5033 setprecision(x): Values 12345
15
The setprecision(x) Manipulator is used with floating point numbers. It is used to set the number of digits printed to the right of the decimal point. Te following example explains the use of setprecision manipulator.
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas #include <iostream.h> #include <iomanip.h> #include <conio.h> void main( ) { clrscr(); float x = 0.123456789; cout<<x<<endl; cout<<setiosflags(ios::fixed)<<setprecision(8)<<x << endl; cout<<setiosflags(ios::scientific)<<setprecision(8)<<x << endl; getch(); } Output is: 0.123457 0.12345679 1.23456791 e-01
16
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
17
Ex: #include<iostream.h> #include<conio.h> main( ) { int a,b,c;sum; a=1; b=1; c=3; sum=a+b+( ++c); cout<< sum=<<sum; cout<< c=<<c; getch( ); return 0; } for ++c Sum = 6 c=4 for c++ Sum = 5 c=4
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas It is used to subtract 1 from the value of an integer if used before variable it is called prefix decrement and if after then postfix decrement Ex: xy=xy-1 can be replace by xy--; or by --xy; Ex: #include<conio.h> #include<iostream.h> main( ) { int a, b, c, sum; a=1; b=1; c=3; sum=a+b+( --c); cout<< sum=<<sum; cout<< c=<<c; getch( ); return 0; } for c-Sum=5 c=2 for --c Sum=4 c=2
18
Comment Statement:
For our references we can use the comment statement which is never executed Syntax is // [comments] Theres a second comment style available in C++: /* this is an old-style comment */
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
19
Exercise:
#include<conio.h> #include<iostream.h> main( ) { float c, f; clrscr( ); cout<< Enter temp in Fahrenheit; cin>>f; c=(f-32)*5.0/9.0; cout Temp in Celsius=<<c; getch( ); return 0; } #include<conio.h> #include<iostream.h> main( ) { float r, h, v cluscn( ); cout<< Enter Radius; cin>> r; cout<< Enter Height; cin>> h; v=3.14*r*r*h cout<< Value of cylinder=<<v; getch( ); return 0;
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas } #include<iostream.h> #include<conio.h> main( ) { int a, b, c, avg cout<< Enter Three Numbers; cin>>a>>b>>c; avg=(a+b+c )/3 cout<< Average is=<<avg; getch( ); return 0; }
20
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
21
Functions:
A function is a set of instructions that is designed to perform a specific task. In C++ there are two basic types of functions 1. Built-in ( defined in the header files) 2. User defined user defined is declared in C++ by declaring it separately inside the body of main( ) and defining outside Ex. #include<iostream.h> #include<conio.h> main( ) { int kg,gm; int grams(int ); clrscr( ); cout<< Enter value of Kg; cin>>kg; gm=gram( kg); cout<< Answer is<<gm; getch( ); } Int grams(int val ) { return val*1000; } The function already declared catches the value of the output and returns it using formula val*1000. Where val is the output of the program under body of the main( ) Function definition assigning gm to function. Function calling function declared
Built-in function:
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
22
Are accessed through the header files each function is defined in its header file, so to use a function we must include its header file in the program
goto() function:
function positions the cursor on the screen at location (x,y ) syntax is gotoxy( x,y) where x=0 to 79 i.e 80 columns of the screen y=0 to 24 i.e 25 rows in screen
getch() function:
it is usually used to pause the program un till a key on the keyboard is pressed. The pressed key is not displayed where paused and the control goes to the next statement syntax is getch( )
getche() function:
is the same but key pressed is shown on the screen syntax is getche( ) Ex:
#include<iostream.h> #include<conio.h>
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
main( ) { cout<<To clear Screen Press Any Key; getch( ); clrscr( ); cout<<To End Program Press Any Key; getch( ); return 0; }
23
math.h Function:
Used for mathematical calculations defined in the math.h
pow(x,y) function:
used to calculate the power of a given integer syntax is pow(x,y ) e.g . pow(2, 3) means 23
sqrt(x) function:
used to calculate square root of a number syntax is sqrt(x ) e.g. sqrt(9.0) means9=3
floor(x) function:
To round off the real number to its largest integer its value is smaller than the real number syntax is
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas floor(x ) e.g. floor(9.6 ) floor(-9.6) means 9 means -10
24
ceil(x) function:
to round off real number to its greatest integer,greater than its actual value syntax is ceil(x) e.g. ceil(9.6 ); ceil(-9.6 ); means 10 means -9
cos(x) function:
to calculate cosine of a single value syntax is cos(x ) e.g cos(0.0) =1
sin(x) function:
to calculate sine of a single value syntax is sin(x ) e.g sin(0.0) =0
tan(x) function:
to calculate tangent of a single value syntax is
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas tan(x ) e.g tan(0.0) =0
25
log(x) function:
to calculate natural logrithem of a single value syntax is log(x ) e.g log(0.0) =1
log10(x) function:
to calculate log of a single value with base 10 syntax is log10(x ) e.g log10(0.0) =1
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas return 0; }
26
exp(x)
returns the exponential of a variable or constant.
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas cout<<cosh(.5); return 0; }
27
fmod()
Prototype: double fmod(double numone, double numtwo); Explanation: This function is the same as the modulus operator. It returns the remainder of the division numone/numtwo. I include it to avoid it being confused with modf, a previous function of the day. //Example will output remainder of 12/5 (2) #include <math.h> #include <iostream.h> int main() { cout<<"The remainder of 12/5: "<<fmod(12/5); return 0; }
complex.h Function:
The example explains the use of complex numbers in C++: #include <stdlib.h> #include <iostream.h> #include <conio.h> #include <complex.h> main() { complex xx; //declares a complex number xx complex yy = complex(1,2.718); //declares yy and assigns a complex value 1+ i 2.718 to yy
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas xx = (yy); //assigns the value of yy to xx
28
cout << complex(1,1)+xx; //adds 1 to real and imaginary parts of xx and prints getch(); return 0; } Initializes yy as a complex number of the form (real+imag*i), evaluates the expressions and prints the result: (0.96476,1.21825). This facility for complex arithmetic provides the arithmetic operators +, /, , and , the assignment operators =, +=, =, =, and /=, and the comparison operators == and != for complex numbers. Expressions such as(xx+1) log(yy log(3.2)) that involve a mixture of real and complex numbers are handled correctly. The simplest complex operations, for example + and +=, are implemented without function call overhead. Input and output can be done using the operators >> (get from) and << (put to). The initialization functions and >> accept a Cartesian representation of a complex. The functions real() and imag() return the real and imaginary part of a complex, respectively, and << prints a complex as (real, imaginary). Polar coordinates can also be used. The function polar(double mag, double angle) creates a complex given its polar representation, and abs(xx) and arg(xx) return the polar magnitude and angle, respectively, of a complex. The function norm(xx) returns the square of the magnitude of a complex. The following complex functions are also provided: sqrt(), exp(), log(), sin(), cos(), sinh(), cosh(), pow(), and conj(). No complex type is defined for float or long double types.
clock()
Prototype: clock_t clock(void);
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas Header File: time.h Explanation: This function returns the number of clock ticks (the CPU time taken) the
29
program has taken. To convert to the number of seconds, divide by CLOCKS_PER_SEC, which is defined in time.h //Example will run a loop, and then print the number of clock ticks and //number of seconds used #include <time.h> #include <iostream.h> int main() { for(int x=0; x<1000; x++) cout<<endl; cout<<"Clock ticks: "<<clock()<<" Seconds: "<<clock()/CLOCKS_PER_SEC; return 0; }
exit(x)
Prototype: void exit(int ExitCode); Header File: stdlib.h and process.h Explanation: Exit ends the program. The ExitCode is returned to the operating system, similar to returning a value to int main. //Program exits itself //Note that the example would terminate anyway #include <stdlib.h> #include <iostream.h> int main() { cout<<"Program will exit"; exit(0) //Return 0 is not needed, this takes its place }
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
30
rand()
Prototype: void rand(void); Header File: stdlib.h Explanation: rand generates random numbers. #include <stdlib.h> #include <iostream.h> int main() { int d=rand()%1000; //Should be between 0 and 1000 cout<<d; return 0; }
srand()
Prototype: void srand(unsigned int seed); Header File: stdlib.h Explanation: Srand will seed the random number generator to prevent random numbers from being the same every time the program is executed and to allow more pseudorandomness. //Program uses time function to seed random number generator //and then generates random number #include <stdlib.h> #include <time.h> #include <iostream.h> int main() { srand((unsigned)time(NULL)); //Casts time's return to unsigned int d=rand()%12; //Should be more random now cout<<d; return 0;
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas }
31
time()
Prototype: time_t time(time_t* timer); Header File: time.h ANSI: C and C++ Explanation: Returns and sets the passed in variable to the number of seconds that have passed since 00:00:00 GMT January 1, 1970. If NULL is passed in, it will work as if it accepted nothing and return the same value. Example: //Program will use time_t to store number of seconds since 00:00:00 GMT Jan. //1, 1970 #include <time.h> #include <iostream.h> int main() { time_t hold_time; hold_time=time(NULL); cout<<"The number of elapsed seconds since Jan. 1, 1970 is "<<hold_time; return 0; } }
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
32
Conditional Statements:
The statements of a program are executed one after another, this is called sequential execution. To change or alter the sequence of execution we can use conditional statements which execute or neglect the statements coming after a statement depending upon the results of their condition .for doing this we need to test a relation .The relational expression usually contains two variables or constants to be compared and a relational operator e.g < , > if we require that the next statement executes after testing this condition and finding it true and said will happen otherwise if the execution is not performed. The relational operator in C++ are <, >=, <= , > , = = and !=
The if statement:
It is used to execute or ignore a single statement or a set of statements after testing a condition. It evaluates a condition if condition is true the statement in the body of if is executed if not the control shifts to the next statement ignoring statements after the if its SYNTAX is if (condition) statement1; statement2; the condition is tested only for statement1 not for statement2 to execute a set of statements after testing a condition the set is enclosed in the curly brackets i.e. {} called body of if. its SYNTAX is if (condition) { set of conditions; } statement-n; in above 1 to m statements are executed if if condition is satisfied otherwise only the nth statement is executed (from 1 to m) here ; is not required
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
33
Flow Chart
condition false true Set of statements Statement after if Ex: #include<iostream.h> #include<conio.h> main( ) { int a,b; cout<< enter values of a and b; cin>>a>>b; if(a>b) cout<< a is greater<<endl; if(b>a) cout<< b is greater<<endl; cout<< ok ; getch( ); return 0; } enter values of a and b 2 5 b is greater ok enter values of a and b 5 2 a is greater ok
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas Ex: Quadratic equation #include<iostream.h> #include<conio.h> main( ) { float a, b, c, r1, r2, disc, real, imag; cout<< enter value of a, b and c<<endl; cin>>a>>b>>c; disc=b*b-4.0*a*c; if(disc<0 ) { real=-b/(2.0*a ); imag=sqrt(-disc ) / (2.0*a ); cout<< roots are imagenry<<endl; cout<< root1=<<real<< +i<<imag<<endl; cout<< root2=<<real<< -i<<imag<<endl; } if(disc==0 ) { r1=r2=-b/(2.0*a ); cout << roots are real and equal<<endl; cout<< root1=<<r1<<endl; cout<< root2=<<r2<<endl; } if(disc>0 ) { r1=-b/(2.0*a)+sqrt(disc)/ (2.0)*a r2=-b/(2.0*a)-sqrt(disc)/ (2.0)*a cout<< roots are real and different<<endl; cout<< root1=<<r1<<endl;
34
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas cout<< root2=<<r2<<endl; } getch ( ); }
35
Flow Chart if
else false Block 2 true Block 1 condition
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas Ex: #include<iostream.h> #include<conio.h> main( ) { int n; cout<< enter an integer; cin>>n; if(n>100) cout<< number is greater than 100; else cout<< number if is less than 100; getch( ); }
36
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
37
if first condition is satisfied and second not statement-1 is not executed it is only executed if both conditions are satisfied 1 and 2 are both executed. If neither is satisfied non is executed
Flow Chart
if Condition-1 False True if
if-else-if statement:
If and if-else structure is placed in another if-else structure we get a nested if-else structure SYNTAX is if (condition-1) statement-1; else if (condition-2) statement-2;
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas else statement-n;
38
Flow Chart
true Condition-1 false Condition-2 false Next statement true Block 2 Block 1
Switch statement:
It is an alternate of the if-lese-if statement and is used because the if-else-if statements becomes complex. It has one variable or expression whose values are compared with different cases for selection as shown in the SYNTAX below Switch (expression / variable) //value returned as used for selection { case const-1: //may be numeric or character state-1; break; // if const-1 is selected the next statements will not execute case const-2: state-2; break; dafault: //if not match is selected this is run state-3; } it has the same flow chart as that of the if-else-if statement
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
39
Conditional Operators:
It is an alternate of if-else structure. SYNTAX is (condition)?exp-1:exp2; examples explain its usage int a = 5, b = 10. res; res = (a>b)?a:b; cout<< res; will give output 10
Logical Operators:
These are used to combine relational expressions on conditions. It is a compound condition There are three operators 1. 2. 3. && || ! AND operator. all conditions must be satisfied for the execution OR operator. One or more must be satisfied for the execution NOT operator. The results of condition is inverted
Ex. #include<iostream.h> #include<conio.h> main( ) { int a, b, c; cin>> a>>b>>c; if( (a>b) &&(a>c) ) cout<< a is largest; elseif ( (b>a) &&(b>c) ) cout<< b is largest; else
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas cout<< c is largest; getch( ); return 0; } Ex. #include<iostream.h> #include<conio.h> main( ) { int c, b; cin>> a>>b; if( (a>100) ||(b>100) ) cout<< one or more values are greater than 100; else cout<< no value is greater than 100; getch( ); } Ex. #include<iostream.h> #include<conio.h> main( ) { int a,b; cout<< enter two values; cin>>a>>b; if(!(a>b)) cout<< 2nd value is largest; else cout<< 1st value is larges; getch( );
40
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas return 0; }
41
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
42
Loops:
A statement on a set of statements that is executed repeatedly is called a loop. The statements under a loop are executed for a specified number of times until some given condition remain true In C++ there are three kind of loops 1. 2. 3. for loop while loop do-while loop
for loop:
It is used to execute a set of statements for a fixed number of times it is also called counts loop SYNTAX is for(initialization; condition; increment or decrement) In initialization an initial value is assigned to the variable being used in condition e.g. for(a=6;a<10;a++) The variable may be declared here or earlier under main( ) if the variable has already being declared and initialized then we may write for( ;a<10;a++) The condition part carries a condition which returns true or false depending upon the results of condition. Increment or decrement is used to increase or decrease the value of variable to make a true condition false during execution of the statement for specific period. The statement or set of statements dependent on for are written inside the body of for loop e.g.
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas for(a=6;a<10;a++) { cout<<a<<endl; } note: this example executed 4 times
43
6 7 8 9
Flow Chart
Initialized variable false condition true Body of loop Statements after for body
Increment decrement
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas Ex. To print table
#include<iostream.h> #include<conio.h> main( ) { int table, c, r; clrscr ( ); cout<< enter a number; cin>>table; for( c=1;c<=10;c++) { r=table*c; cout<<table<< x<<c<< =<<r<<endl; } getch( ); return 0; }
44
Ex. Factorial
#include<iostream.h> #include<conio.h> main( ) { int n; long int fact; clscr ( ); cout << enter any number; cin>>n; fact=1; for( ;n>=1;n--) { fact=fact*n } cout <<the factorial of is<<fact; getch( ); return 0; } [ note that n has already been declared through the input]
4 the factorial of 4 is 24
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
45
while Loop:
It is conditional loop statement used to execute a statement or set as long as a condition is true SYNTAX is while( condition) { . }
Body of While
The computer evaluates the condition of while if it is true the body of while is executed otherwise it is not. The body must always contain a statement that can make the condition false otherwise the loop will become infinite Ex: #include<iostream.h> main( ) { int c; c=1; while(c<=5 ) { cout<< GCUF; c=c+1; } cout<< EndOK; getch( ); return 0; } Statement after while condition True Body of loop False GCUF GCUF GCUF GCUF GCUF End.OK
Flow Chart
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas Ex. Program for series 1+1/2+1/3+1/4+. #include<iostream.h> #include<conio.h> main( ) { float s, c; clrscr ( ); s=0.0; c=1.0 while( c<=45) { s=s+1.0/c c++; } cout<< sum of series is=<<s; getch( ); return 0; }
46
do-while Loop:
It is also a conditional loop in which condition is tested after the body of the loop has been executed. So a loop that returns false in first execution of while and the body is not executed will be executed once using do-while SYNTAX is do { statements; } while (condition)
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas Ex: #include<iostream.h> #include<conio.h> main( ) { int n; n=1; do { cout<< n<<endl; c++; } while( n<=10) cout<<endl<<OK getch( ); return 0; } 1 2 3 4 5 6 7 8 9 10 OK
47
Flow Chart
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
48
Ex: Convert decimal num to binary num #include<iostream.h> #include<conio.h> main( ) { int n, r; clrscr( ); cout<< enter some integer; cin>>n; do { r=n%2; n=n/2; cout<<r<<endl } while(n>=1); cout<<endl<< ok; getch( ); return 0; } 10 0 1 0 1
10 13
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas #include<iostream.h> #include<conio.h> main( ) { int u, i, n; u=1; while( u<=3) { i=1 n=1 while(i<=5 ) { cout<<n<< \t; n=n+u; i=i+1; } cout<<endl; u=u+1 } getch( ); return 0; } Ex. Using nested for loop print on screen 1 1 1 1 1 2 2 2 2 3 3 3 4 4 5 1 2 3 4 5 1 3 5 7 9 1 4 7 10 13
49
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas #include<iostream.h> #include<conio.h> main( ) { int u, i; for (u=1;u<=5;u++ ) { for( i=1;i<=u;i++) { cout<<i<< \t; cout<<endl; } } getch( ); return 0; }
50
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
51
Arrays:
Arrays is a sequence of objects of same data type. The objects are also called the elements of the arrays. An array is the set of consecutive storage locations each referenced by a name and its position. Position is referenced by index, for n elements the index values are 0,1,2,3..,n-1 where 0 is the index value of the first element and n-1 is for the last element. And element when entered or retrieved is accessed by its index value in C++, index value is written inside [] brackets. Arrays are used to process large amount of data of same type Storage Row vector matrix Location 2 1 4 1 5 3 2
Value
1-D array:
Also known as list or linear arrays consist of 1 column or row, for example to declare the temperature of 24 hours during a day we need to define the temperature data set, its type and also the locations of temperature w.r.t time so that memory locations are reserved in the computer for the said collection of data. The general SYNTAX for declaring 1-D array is type array name[n] For example temperature of 24 hours in decimal form we may write double temp[24]
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas Ex: How to access and retrieve data #include<iostream.h> #include<conio.h> main( ) { float a[5]; int i; a[0]=9.9 a[1]=12.9 a[2]=13.1 a[3]=8.9 a[4]=10.6 for(i=0;i<=4;i++ ) { cout<< value in a[ <<i<<]=<<a[i]<<endl; } getch( ); return 0; } Ex. To input and print the same data in reverse #include<iostream.h> #include<conio.h> main( ) { int abc[5], i; for( i=0;i<=4;i++) { cout<< Enter value in a[<<i<<]=<<endl; cin>>abc[i]; }
52
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas cout<< output in reverse is<<endl; for( i=4;i<=0;i--) { cout<< value ina[<<i<<]=<<abc[i]<<endl; } getch( ); return 0; } Ex. Averaging array elements #include <iostream.h> #include<conio.h> void main() { const int SIZE = 6; //size of array double sales[SIZE]; //array of 6 variables cout << Enter sales for 6 days\n; for(int j=0; j<SIZE; j++) //put figures in array cin >> sales[j]; double total = 0; for(j=0; j<SIZE; j++) //read figures from array total += sales[j]; //to find total double average = total / SIZE; // find average cout << Average = << average << endl; return 0; } Ex. Initializing Arrays #include <iostream.h> #include<conio.h> void main() { int month, day, total_days;
53
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas int days_per_month[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; cout << \nEnter month (1 to 12): ; //get date cin >> month; cout << Enter day (1 to 31): ; cin >> day; total_days = day; //separate days for(int j=0; j<month-1; j++) //add days each month total_days += days_per_month[j]; cout << Total days from start of year is: << total_days << endl; return 0; }
54
Multi-dimensional Arrays:
In array of more than one array is called multi-dimensional array. Also known as table or matrix. The index value for 2-D array are two, one represents the row number and other the column number, for example a 2-D array temp with seven rows and three columns is represented by temp[7][3] whose first element is temp[0][0] and last is temp[6][2] the declaration SYNTAX for a 2-D array is type name [r][c] Where r= # of rows c= # of columns e.g. an array of integer values with 12 rows and 3 columns will be represented by int abc[12][3]; where total # of elements is given by 12x3=36. The 1st index value for row is 0 and last is 11, similarly 1st index value for column is 0 and last is 2. To enter or retrieve data of an array the elements are referenced by their index value usually nested loops are used to access or retrieve elements of 2-D array. Examples
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
55
illustrate a 2-D array whose values are entered and then retrieved in tabular form on the screen Ex: Input data into array and output the same
#include<iostream.h> #include<conio.h> main( ) { int abc[2][3], r, c; cout<< Input data into table<<endl; r=0; while(r<=1 ) { c=0; while( c<=0) { cout<< enter value in row =<<r<<column=<<c; cin>>abc[r][c]; c=c+1; } r=r+1; } cout<< printing table<<endl; r=0; while( r<=1) { c=0; while( c<=2) { cout<<abc[r][c]<< \t; c=c+1; } cout<<endl;
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
r=r+1; getch ( ); return 0; }
56
Ex: Entering values in table and printing maximum values #include<iostream.h> #include<conio.h> main( ) { int r, c, m, aa[5][4]; clscr( ); for( c=0;c<4;c++) for( r=0;r<4;r++) { cout<< Enter value in [<<c<<, <<r<<]=; cin>>aa[r][c]; } m=aa[0][0]; for(c=0;c<4;c++ ) for( r=0;r<4;r++) { if( m<aa[r][c]) m==aa[r][c] } cout<< max value =<<m; cout<<endl<< ok<<endl; getch( ); return 0; } Ex: Initializing 2-D Array
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas #include<iostream.h> #include<conio.h> const int DISTRICTS = 4; //array dimensions const int MONTHS = 3; int main() { int d, m; //initialize array elements double sales[DISTRICTS][MONTHS]; = { { 1432.07, 234.50, 654.01 }, { 322.00, 13838.32, 17589.88 }, { 9328.34, 934.00, 4492.30 }, { 12838.29, 2332.63, 32.93 } }; cout << \n\n; cout << Month\n; cout << 1 2 3; for(d=0; d<DISTRICTS; d++) { cout <<\nDistrict << d+1; for(m=0; m<MONTHS; m++) cout << setw(10) << setiosflags(ios::fixed) << setiosflags(ios::showpoint) << setprecision(2) << sales[d][m]; //access array element } cout << endl; return 0; }
57
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
58
Pointers:
The memory of your computer can be imagined as a succession of memory cells, each one of the minimal size that computers manage (one byte). These single-byte memory cells are numbered in a consecutive way, so as, within any block of memory, every cell has the same number as the previous one plus one. Thus, each cell can be easily located in the memory because it has a unique address and all the memory cells follow a successive pattern.
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
59
First, we have assigned the value 25 to andy (a variable whose address in memory we have assumed to be 1776). The second statement copied to fred the content of variable andy (which is 25). Finally, the third statement copies to ted not the value contained in andy but a reference to it (i.e., its address, which we have assumed to be 1776). The variable that stores the reference to another variable (like ted in the previous example) is what we call a pointer. Pointers are a very powerful feature of the C++ language that has many uses in advanced programming.
Dereference operator *:
Using a pointer we can directly access the value stored in the variable that it points to. To do this, we simply have to precede the pointer's identifier with an asterisk (*), which acts as dereference operator (offset operator) and that can be literally translated to "value pointed Therefore, following with the values of the previous example, if we write: beth = *ted; ("beth equal to value pointed by ted") beth would take the value 25, since ted is 1776, and the value pointed by 1776 is 25. by".
The expression ted refers to the value 1776, while *ted (with an asterisk * preceding the identifier) refers to the value stored at address 1776, which in this case is 25. Notice the difference between the reference and dereference operators: & is the reference operator and can be read as "address of"
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas * is the dereference operator and can be read as "value pointed by"
60
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
61
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas *p = 20; p = numbers + 3; *p = 30; p = &numbers[3]; *p = 40; p = numbers; *(p+4) = 50; for (int n=0; n<5; n++) cout << numbers[n] << ", "; getch(); return 0; } Output will be: 10, 20, 30, 40, 50,
62
The good thing about pointers is that we do not need to use [] several times. For example a[5] = 0; *(a+5) = 0; // a [offset of 5] = 0 // pointed by (a+5) = 0
These two expressions are equivalent and valid both if a is a pointer or if a is an array.
Pointer initialization
When declaring pointers we may want to explicitly specify which variable we want them to point to: int number; int *tommy = &number; When a pointer initialization takes place we are always assigning the reference value to where the pointer points (tommy), never the value being pointed (*tommy).
As in the case of arrays, the compiler allows the special case that we want to initialize the
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
63
content at which the pointer points with constants at the same moment the pointer is declared: char * terry = "hello" In this case, memory space is reserved to contain "hello" and then a pointer to the first character of this memory block is assigned to terry. If we imagine that "hello" is stored at the memory locations that start at addresses 1702, we can represent the previous declaration as:
It is important to indicate that terry contains the value 1702, and not 'h' nor "hello", although 1702 indeed is the address of both of these. The pointer terry points to a sequence of characters and can be read as if it was an array (remember that an array is just like a constant pointer). For example, we can access the fifth element of the array with any of these two expression: *(terry+4) terry[4] Both expressions have a value of 'o' (the fifth element of the array).
Pointer arithmetics
To conduct arithmetical operations on pointers is a little different than to conduct them on regular integer data types. To begin with, only addition and subtraction operations are allowed to be conducted with them. But both addition and subtraction have a different behavior with pointers according to the size of the data type to which they point. Suppose that we define three pointers:
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas char *mychar; short *myshort; long *mylong;
64
and that we know that they point to memory locations 1000, 2000 and 3000 respectively. So if we write: mychar++; myshort++; mylong++; mychar, as you may expect, would contain the value 1001. But not so obviously, myshort would contain the value 2002, and mylong would contain 3004, even though they have each been increased only once. Both the increase (++) and decrease (--) operators have greater operator precedence than the dereference operator (*), but both have a special behavior when used as suffix (the expression is evaluated with the value it had before being increased). Therefore, the following expression may lead to confusion: *p++ Because ++ has greater precedence than *, this expression is equivalent to *(p++). Notice the difference with: (*p)++ Here, the expression would have been evaluated as the value pointed by p increased by one. The value of p (the pointer itself) would not be modified (what is being modified is what it is being pointed to by this pointer). It is recommended to use parentheses () in order to avoid unexpected results and to give more legibility to the code.
void pointers
The void type of pointer is a special type of pointer. In C++, void represents the absence of type, so void pointers are pointers that point to a value that has no type (and thus also an undetermined length and undetermined dereference properties).
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
65
This allows void pointers to point to any data type, from an integer value or a float to a string of characters. But in exchange they have a great limitation: the data pointed by them cannot be directly dereferenced (which is logical, since we have no type to dereference to), and for that reason we will always have to cast the address in the void pointer to some other pointer type that points to a concrete data type before dereferencing it.
Null pointer
A null pointer is a regular pointer of any pointer type which has a special value that indicates that it is not pointing to any valid reference or memory address. This value is the result of type-casting the integer value zero to any pointer type. int * p; p = 0; // p has a null pointer value Do not confuse null pointers with void pointers. A null pointer is a value that any pointer may take to represent that it is pointing to "nowhere", while a void pointer is a special type of pointer that can point to somewhere without a specific type. One refers to the value stored in the pointer itself and the other to the type of data it points to.
Pointers to functions
C++ allows operations with pointers to functions. The typical use of this is for passing a function as an argument to another function, since these cannot be passed dereferenced. In order to declare a pointer to a function we have to declare it like the prototype of the function except that the name of the function is enclosed between parentheses () and an asterisk (*) is inserted before the name: Ex: Pointer to a function #include <iostream.h> #include <conio.h> int addition (int a, int b) {
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas return (a+b); } int subtraction (int a, int b) { return (a-b); } int operation (int x, int y, int (*functocall)(int,int)) { int g; g = (*functocall)(x,y); return g; } int main () { clrscr(); int m,n; int (*minus)(int,int) = subtraction; m = operation (7, 5, addition); n = operation (20, m, minus); cout <<n; getch(); return 0; } Output is: 8
66
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
67
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
68
Just as you cant use a variable without first telling the compiler what it is, you also cant use a function without telling the compiler about it. There are two ways to do this. The approach we show here is to declare the function before it is called. (The other approach is to define it before its called). The declaration tells the compiler that at some later point we plan to present a function called starline. The keyword void specifies that the function has no return value, and the empty parentheses indicate that it takes no arguments. Notice that the function declaration is terminated with a semicolon. Function declarations are also called prototypes, since they provide a model or blueprint for the function. The information in the declaration (the return type and the number and types of any arguments) is also sometimes referred to as the function signature.
Function definition:
Finally we come to the function itself, which is referred to as the function definition. The definition contains the actual code for the function. void starline() //declarator { for(int j=0; j<45; j++) //function body cout << *; cout << endl;
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas }
69
The definition consists of a line called the declarator, followed by the function body. The function body is composed of the statements that make up the function, delimited by braces. The declarator must agree with the declaration: It must use the same function name, have the same argument types in the same order, and have the same return type. When the function is called, control is transferred to the first statement in the function body. The other statements in the function body are then executed, and when the closing brace is encountered, control returns to the calling program.
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
70
void cal(int x, char aop, int y) { switch(aop) { case +: cout<<x+y; break; case -: cout<<x-y; break; case *: cout<<x*y; break; case /: cout<<x/y; break; default: cout<<Invalid operator; } }
Constants as argument:
Instead of a function that always prints 45 asterisks, we want a function that will print any character any number of times. Ex: #include <iostream.h> #include <conio.h> void repchar(char, int); //function declaration
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas int main() { repchar(-, 43); //call to function cout << Data type Range << endl; repchar(=, 23); //call to function
71
cout << char -128 to 127 << endl << short -32,768 to 32,767 << endl << int System dependent << endl << double -2,147,483,648 to 2,147,483,647 << endl; repchar(-, 43); //call to function return 0; } //-------------------------------------------------------------// repchar() // function definition void repchar(char ch, int n) //function declarator { for(int j=0; j<n; j++) //function body cout << ch; cout << endl; } The new function is called repchar(). Its declaration looks like this: void repchar (char, int); specifies data types. The items in the parentheses are the data types of the arguments that will be sent to repchar(): char and int. repchar(-, 43); // function call specifies actual values This statement instructs repchar() to print a line of 43 dashes. The values supplied in the call must be of the types specified in the declaration: the first argument, the - character, must be of type char; and the second argument, the number 43, must be of type int. The types in the declaration and the definition must also agree.
Variables as argument:
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas In above example the arguments were constants: , 43, and so on. Lets look at an example where variables, instead of constants, are passed as arguments. Ex: #include <iostream.h> #include <conio.h> void repchar(char, int); //function declaration int main() { char chin; int in; cout<< enter the character to print; cin>>chin; cout<< how many time to print it?; cin>>in; repchar(chin, in); //call to function cout << Data type Range << endl; repchar(chin, in); //call to function
72
cout << char -128 to 127 << endl << short -32,768 to 32,767 << endl << int System dependent << endl << double -2,147,483,648 to 2,147,483,647 << endl; repchar(chin, in); //call to function return 0; } //-------------------------------------------------------------// repchar() // function definition void repchar(char ch, int n) //function declarator { for(int j=0; j<n; j++) //function body cout << ch; cout << endl;
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas }
73
The data types of variables used as arguments must match those specified in the function declaration and definition, just as they must for constants. That is, chin must be a char, and in must be an int.
Arrays as Arguments:
An array can also be passed on to a function but only its starting address is passed to the function. The same array locations are used by the function to perform operations or change values of the arrays. To use an array in a function it should be declared in the function along with its types. For example to use two arrays of float and int type in a function max the following declaration can be sued. void max(float [3], int [3]); similarly for two dimensional arrays void max(float [3][3], int [3][3]); In the function definition, however, a name is also assigned to the array. For example if we want to define a function with 2-D float and int type arrays then void max(float xy[3][3], int ab[3][3]); the size of array can be given in both the declaration and definition but it is optional. To pass arrays as the arguments of an array only the array name is passed through the function calling. Ex: #include<iostream.h> #include<conio.h> main() { clrscr(); int c, aa[5];
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas void max (int []); for (c=0; c<4:c++) { cout<<Enter data in the aa[<<c<<]:; cin>>arr[c]; } max(aa); getch(); } void max(int x[]) { int m,co; m=x[0]; for(co=0;co<4;co++) if(m<x[co]) m=x[co]; cout<<Maximum value is:<<m<<endl; } The memory of your computer can be imagined as a succession of memory cells, each one of the minimal size that computers manage (one byte). These single-byte memory cells are numbered
74
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas Ex: #include <iostream.h> float lbstokg(float); //declaration int main() { float lbs, kgs; cout << \nEnter your weight in pounds: ; cin >> lbs; kgs = lbstokg(lbs); cout << Your weight in kilograms is << kgs << endl; return 0; } //-------------------------------------------------------------// lbstokg() // converts pounds to kilograms float lbstokg(float pounds) { float kilograms = 0.453592 * pounds; return kilograms; } When a function returns a value, the data type of this value must be specified. The function declaration does this by placing the data type, float in this case, before the function name in the declaration and the definition. Functions in earlier program examples returned no value, so the return type was void.
75
Overloaded function:
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
76
An overloaded function appears to perform different activities depending on the kind of data sent to it. It performs one operation on one kind of data but another operation on a different kind. Here we online examine function overloading due to different kind of arguments.
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas cout << endl; } void repchar(char ch) { for(int j=0; j<45; j++) // always loops 45 times cout << ch; // prints specified character cout << endl; } void repchar(char ch, int n) { for(int j=0; j<n; j++) // loops n times cout << ch; // prints specified character cout << endl; }
77
The program contains three functions with the same name. There are three declarations, three function calls, and three function definitions. What keeps the compiler from becoming hopelessly confused? It uses the function signature the number of arguments, and their data types to distinguish one function from another. The compiler, seeing several functions with the same name but different numbers of arguments, could decide the programmer had made a mistake (which is what it would do in C). Instead, it very tolerantly sets up a separate function for every such definition. Which one of these functions will be called depends on the number of arguments supplied in the call.
Inline Function:
When the compiler sees a function call, it normally generates a jump to the function. At the end of the function it jumps back to the instruction following the call. While this sequence of events may save memory space, it takes some extra time.
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas To save execution time in short functions, you may elect to put the code in the function body directly inline with the code in the calling program. That is, each time theres a
78
function call in the source file, the actual code from the function is inserted, instead of a jump to the function. Long sections of repeated code are generally better off as normal functions: The savings in memory space is worth the comparatively small sacrifice in execution speed. But making a short section of code into an ordinary function may result in little savings in memory space, while imposing just as much time penalty as a larger function. In fact, if a function is very short, the instructions necessary to call it may take up as much space as the instructions within the function body, so that there is not only a time penalty but a space penalty as well. Functions that are very short, say one or two statements, are candidates to be inlined. Ex: // demonstrates inline functions #include <iostream.h> // lbstokg() // converts pounds to kilograms inline float lbstokg(float pounds) { return 0.453592 * pounds; } //-------------------------------------------------------------int main() { float lbs; cout << \nEnter your weight in pounds: ; cin >> lbs; cout << Your weight in kilograms is << lbstokg(lbs) << endl; return 0; }
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas Its easy to make a function inline: All you need is the keyword inline in the function definition: inline float lbstokg(float pounds) You should be aware that the inline keyword is actually just a request to the compiler. Sometimes the compiler will ignore the request and compile the function as a normal function. It might decide the function is too long to be inline, for instance. (C programmers should note that inline functions largely take the place of #define macros in C.)
79
Local variables:
The variables of a program can be declared in three locations. (1) inside main(), (2) outside main() and (3) inside another function. Depending upon the place of declaration of a variable it can be included into one of the two forms of ariables i.e. Local and Globl. The Local Variables are declared inside the main() function or any other user defined function. These are also called the automatic (auto) variables. The LIFETIME of a variable is the time between its creation and destruction. Thus a variable remains active only when its lifetime is not over. For Local variables, when the control is transferred to the function the Local variables get created and remain occupying the memory until the control goes out of the said function. Thus Local variables can only be accessed from within the function they are created and cannot be used outside the body of that function.
Global variables:
The variables which are declared outside the body of the main function or any other function are called global variables. These variables can be accessed through any function including the main function. These are only used when we want to access them from any function and not worry about the changes in their values. Also they occupy a large amount of memory permanently that can make the program slower.
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
80
Since the global variables are creasted and used through out the execution process of a program, their LIFETIME is from the beginning of the program till its termination.
Static variables:
Static variables are a special kind of variables which are declared with a static: key word before them. These are like the local variables since they can be declared inside a function, however, their lifetime is from the start of the program to the end of the program so that their data remains available even if the control shifts out of the function in which they are declared. Another difference between static and local variables is that the later can be initialized only once when the function is called for the first time.
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
81
The term Stream means flow of data from a source to a destination. In C++ special classes area available to handle data which are called stream classes. These classes are defined in the header files and can be used by including the header files into the program. For example the cin and cout objects are used for streaming data to various places. Following streams are available in C++ for files: ifstream: for inputting data ofstream: for outputting data fstream: for both input and output data The << operator is the member of istream class and >> operator is the member of ostream class which are apart of the ios class. All these classes are linked together as shown below. ios
ostream
ofstream
In order to use the ifstream, ofstream and fstream classes one needs to include the fstram.h file into a C++ program.
Opening files:
In order to access a file it needs to be opened. There are two ways of opening a file namely: (a) opening file in output mode and (b) opening file in input mode. To open a file in output mode an object of ofstream is created with the SYNTAX ofstream abc(filename,ios::out);
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
82
here abc is the object created using ofstream that is attached to control the file. Its function is similar to cout. filename is the name of the file which is to be opened. As it is a string constant it is given in double quotations and is associated with the object abc. The data into this file is written / read with the help of the object abc. ios::out is the mode of the file that tells that this file is opened for outputting data into it. This is optional and can be left. Thus we can also have ofstream abc(filename); The filename is also optional and can be associated with the object abc later in the program as shown below ofstream abc; abc.open(filename); To open a file in input mode an object of ifstream is created with the SYNTAX ifstream abc(filename,ios::in); it has the same characteristics as discussed for the output mode file.
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas { cerr<<file opening error<<endl; exit(1); }
83
Formatted input/output:
Formatted files are those which store data as sequential data. For example in such files the value 261.98 is saved as a sequence of 6 bytes. Data from such files can be accessed in the same order as they are stored. Formatted files are also known as sequential access files. To read a particular data from this file we need to read the file from the beginning till the required data is reached. The data in such files can not be added, updated or deleted individually.
Writing data:
The insertion operator can << can be used to send data to a formatted file using the output object created through the ofstream class. When a program containing this object ends the object gets destroyed and the files is closed with data saved in it. Following program explains the output into the formatted file. Ex: #include <iostream.h> #include <fstream.h> #include <conio.h> main() { ofstream data(record.dat); char name[15]; int age, i; i= 1; data<< Name\tAge<<endl; while(i < 10)
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas { clrscr(); cout<< Enter record number<<I<<endl; cout<< Enter name; cin>> name; cout<< Enter age; cin>>age; data<<name<<\t<<age<<endl; i++; } getch(); return 0; }
84
The object data is associated with the records.dat file and saves data into the file when the object data is used with the insertion operator. Note that the syntax of cout and data are the same.
Reading data:
The extraction operator can >> can be used to receive data from a formatted file using the input object created through the ifstream class. When a program containing this object ends the object gets destroyed and the files from which data is being taken gets closed. Following program explains the output into the formatted file. Suppose the earlier created file records.dat is being read into the program. Ex: #include <iostream.h> #include <fstream.h> #include <conio.h> main()
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas { ifstream rec(record.dat); char name[15]; int age, i = 1; clrscr(); if(!rec) { cerr<< File opening error<<endl; exit(1); } while(i < 10) { cout<< Record #:<<i<< :\t;rec; rec>>name>>age; cout<<name<< \t<<age<<endl; } getch(); return 0; }
85
End-of-file:
The end-of-file eof specifies the end of record of a file. It is a member function of object of ifstream class and it is used to detect enf-of-file. This function returns value true (1) if the end of file has been reached or false (0) if not reached. Normally the end of file is detected using the eof member function in a loop statement. For example, if abc is an object of the ifstream class the while statement can be written as while (!abc.eof()); Another way to this is by using the simple version of above statement as while(abc);
Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas
86
if the end of file has been reached the above condition will return 0 and the loop will terminate.
Output to printer:
The output of a program can also be sent to the printer attached with the computer. Usually the printer is connected to the first parallel port. The first parallel prot is called PRN or LPT1. To send output to the printer an output object of ofstream is created which is accosiated with printer port, e.g. ofstream pout(PRN); Where PRN is the port of the printer. It may be LPT1 or LPT2 or so on. The pout object is associated with the PRN object and all the output through this object is sent to the port when used. Following example explains its use. Ex: #include <iostream.h> #include <fstream.h> #include <stdlib.h> main() { ofstream ppp(PRN); ppp<< I love Pakistan<<endl; ppp<< GCUF<<endl; ppp.put(\x0C); // This ensures that page comes out of the printer. Gets ejected i.e. getch(); return 0; }