You are on page 1of 77

1st

#include<iostream.h>
main(){
cout <<"Wel come to virtual university of pakistan";
}

2st
#include<iostream.h>
main(){
int x, y, z;
x = 10;
y = 20;
z = 30;
cout <<x;
cout <<y;
cout <<z;
cout << "x = x + x";
cout << x;

3rd

#include<iostream.h>
main(){
short x, y, z;
x = 33456;
y = 20;
z = 10;
x = x+z;
cout<< x;
}

Float data
/*This program store real number in float data type
This take 4 (32 bits for windows operating system) bytes into the memory*/
#include <iostream.h>
main(){
float x, y, z;
x = 1.33;
y = 1.44;
z = 1.55;
x = x + y + z;
cout << x;

Double
/*

this program store double data type


and
size of double data type double is 8 byte (64 bits windows operating system)
*/
#include<iostream.h>
main(){
double x, y, z;
x = 231465.5646;
y = 239084.2342;
z = 234234.2342;
x = x + y + z;
cout<< x;
}

Char
/*this program store char data type*/
#include<iostream.h>
main(){
char a, b;
a = 'The';
b = ' Good';
cout << a ;
cout << b;
}

//only last character will be printed.

SperationInput
/*this program take 4-digit integer form user and show the digit on the screen
speratly i.e. if user enter 2342, it display 2,4,3,2 speratly*/
#include<iostream.h>
main(){
int userInput, digit;
cout<<"Please enter 4-digit input: ";
cin>>userInput;

//1st one
digit = userInput%10;
cout<< "The digits are: ";
cout<<digit<<", ";

//2nd number
userInput = userInput/10;
digit = userInput%10;
cout<<digit<<", ";

//3rd number
userInput = userInput/10;
digit = userInput%10;
cout<<digit<<", ";

//4th
userInput = userInput/10;
digit = userInput%10;
cout<<digit;
}

ifCheck
#include<iostream.h>
main(){
if(1==1)
cout<<"good";
}

testWhileLoop
/* This program will test the while loop withOut curly braces */
#include<iostream.h>
main(){
int number = 0;
cout << "Please enter the number"<<"\n";

while(number<100)
number++;
cout<<"Number is"<<number<<"\n";

gessingGame
/* This is a game, where user has to gess the hidden kep
and total try should less then 5;
*/
#include<iostream.h>
main(){
int tryNum ;
char character;

do{
cout << "Please enter a charactar: ";
cin >> character;
if(character == 'z'){
cout << "contradulation, You have Won the Game.";
tryNum = 6;
}else{
cout << "Wrong answer, Try again.\n"<<endl;
tryNum = tryNum + 1;
}
}while ( tryNum < 6 );
}

grade_check
/*
program gets a grade from user and provide results accordingly
*/
#include<iostream.h>
main(){
char grade;
cout<< "Please enter a Grade to checOut level: ";
cin >> grade;

//start of switch
switch(grade) {
case 'A':
case 'a':
cout << "Excelent";
break;
case 'B':
case 'b':
cout << "Very good";
break;
case 'C':
case 'c':
cout << "Good";
break;
case 'D':
case 'd':

cout << "Poor";


break;
default:
cout <<"Please enter a grade: ";
cin >> grade;
}
}

switch_statement
/* checking condition with switch statement */
#include<iostream.h>
main(){
int grade;
cout << "Please enter a grade to check level of student: ";
cin >> grade;

switch(grade){

case 'A':
case 'a':
cout << "Excellent.";
break;

case 'B':
case 'b':

cout << "Good";


break;

case 'c':
case 'C':
cout << "nice";
break;

case 'D':
case 'd':
cout << "poor";
break;

default:
cout << "Please enter a grade: ";
cin >> grade;
}
}

student_ages
/*calculate student ages*/
#include<iostream.h>
main(){
int age1, age2, age3, age4, age5, age6, age7, age8, age9, age10;

cout<< "Please enter age of 1st student: ";


cin >> age1;
cout<< "Please enter age of 2nd student: ";
cin>> age2;
cout<< "Please enter age of 3rd student: ";
cin>> age3;
cout<< "Please enter age of 4th student: ";
cin>> age4;
cout<< "Please enter age of 5th student: ";
cin>> age5;
cout<< "Please enter age of 6th student: ";
cin>> age6;
cout<< "Please enter age of 7th student: ";
cin>> age7;
cout<< "Please enter age of 8th student: ";
cin>> age8;
cout<< "Please enter age of 9th student: ";
cin>> age9;
cout<< "Please enter age of 10th student: ";
cin>> age10;

int totalAges;
float avarageAge;
totalAges = age1 + age2 ;//+ age3 + age4 + age5 + age6 + age7 + age8 +
age9 + age10;
avarageAge = totalAges/2;

cout <<"Total ages of the studends are: "<<totalAges;


cout <<"Avarage ages of the studends are: "<<avarageAge;
}

External-link
#include<iostream.h>
#include<evenOdd.h>
int EvenOdd(int x);
signature

// own defined header file

//function decleration, also known as funtion prototype or

main(){
int number;
cout << "Please enter a number: ";
cin >> number;

if(EvenOdd(number)){
cout << "Given number is even."<<endl;
}else{
cout << "Given number is odd."<<endl;
}

cout <<endl<< "********************* Thank You *********************"<<endl;

Lec 09
CircleAreaFunction
double circleArea( double radius ){
//value of pi is 3.1415926
return ( 3.1415926 * radius * radius);
}

#include<iostream.h>
main(){
double radius1, radius2, ringArea;
cout << "Please enter radius of outer ring: ";
cin >> radius1;
cout << "Please enter radisu of inner ring: ";
cin >> radius2;

ringArea = circleArea (radius1) - circleArea (radius2);


cout << "Area of the Ring is: "<<ringArea;
}

evenOdd
/*
This program takes a number as input and check weather number is even or odd
throug function.
and then provide output
*/

int EvenOdd(int x);


signature

//function decleration, also known as funtion prototype or

#include<iostream.h>

main(){
int number;
cout << "Please enter a number: ";
cin >> number;

if(EvenOdd(number)){
cout << "Given number is even."<<endl;
}else{
cout << "Given number is odd."<<endl;
}

cout <<endl<< "********************* Thank You *********************"<<endl;

int EvenOdd(int x){


if( 2 * ( x / 2) == x){
return true;
}else{
return false;
}

functionCalculPow
double returnPowerNum(double a, int b){
double result = 1.0;
int i;

for( i = 1; i<=b; i++ ){


result *= a;
}
return result;
}

#include<iostream.h>
main(){
double number;
int

power;

cout << "Please enter a number: ";


cin >> number;
cout << "Please enter power of number: ";
cin >> power;

//Now, we will pass number, and power variable to function returnPowerNum


cout << "Power of "<< number << " is " << returnPowerNum(number, power);
/*

In actual fact nothing happend with number, and power variables. These are
unchanged.
A value of both of these variables are passed to function and the value in
calling program
are unchanaged.
Such function calls are also known as "Call-By-Value"
*/
}

squareThroughFunction
/*
Making square of an number through usage of the function

functions always have two parts,


(i) declaration(prototype), also known as signature of function
(ii)and defination.
*/

int makeSquare(int number){


//int result = 0;

//from here it start defination of funtion

//result = number * number;


return (number * number);
}

#include<iostream.h>

//this is prototype of this function

main(){
int input, result;
cout << "\nPlease enter a number: ";
cin >> input;

//calling square function


result = makeSquare(input);
cout << "\nSquare of "<< input <<" is "<<result<<endl;

//
result = 10 + makeSquare(input);
cout << "\nSquare + 10: "<<result;

//makeSquare get number and add 3 into them and then calculate square of
that
result = makeSquare(input + 3 );
cout << "\nSqaure of "<<input<<" + 3 is equal to: "<<result;

//makeSquare get number and multiply with 3 and then calculate square of that
result = makeSquare( 2 * input);
cout << "\nSquare of "<<input<<" * 2 is equal to: "<<result;

cout << "\nSquare of " <<input<<" is: "<<makeSquare(input);

cout << "\nSquare of makeSquare(5) is: "<< makeSquare(5);


}

Lec 10
callByRefference
/*
This program change value of x from function bcoz it is calling by reference
"&" with combination of variable name could used for this propes, like &x
and in function "*" could used like, *x mean whatever x pointing to
*/
void square( double *x ) {
*x = *x * *x;
// cout << "In function x = "<< *x;
}

#include<iostream.h>
main(){
double x ;
x = 123.456;

cout << "\nIn main before calling the functin x = "<<x;

square (&x);

//address of x

cout << "\nIn main after function x =


}

"<<x;

Lec 11
array
#include<iostream.h>
main(){
int c[100];
int z, i = 0;
do{
cout << "Please enter a number (-1 to end input): "<<endl;
cin >> z;
if(z!= -1){
c[i] = z;
}
i++;
}while(z != -1 && i < 10);

cout << "Total number of positive integer intered by the user are:"<<i-1;
}

array_comparing
#include<iostream.h>
main(){
int one[10];
int i, z;

for(i=1; i<10; i++){


one[i] = i;
}

cout << "Please enter a positive integer:";


cin >> z;

int found = 0;
for(i=1; i<10; i++){
if(z == one[i]){
found = 1;
break;
}
}

if(found == 1){
cout << "We found the integer at index "<<i;
}else{
cout << "The number was not found.";
}
}

random_number
/*

random number generator


*/
#include<iostream.h>
#include<stdlib.h>
main(){
int a, i ;
int z[100];

for(i = 0; i < 10; i++){


z[i] = rand();
cout << "Initilizating : "<<z[i]<<endl;
}

cout << "Random number of rand()%6 is: "<<rand()%6 + 1 ;


}

Lec 12
string_array
#include<iostream.h>
main(){
char name[10];
cout <<endl << "Please enter a new name: ";
cin >> name;

/*for(int i=1; i<10; i++){

cout <<endl << "Please enter a new name: ";


cin >> name;
} */
for(int i=0; i<10; i++){
cout << "\n\n\nName is :"<<name <<endl;
}
}

array_reference
/*
This program demonstrate that when ever a program is called, it will be call by
referrence
*/
#include<iostream.h>
void getValue(int [], int);

main(){
int num[100], i;

getValue(num, 100);

//function calling, passing array num

cout << "\n The array is papulated with values \n";


for ( i = 0; i < 10; i++ )
cout << "num [" << i <<"] = "<< num[i] << "\n";
}

void getValue(int num[], int arraySize){

int i;
for(i = 0; i < arraySize; i++ )
num[i] = i;
}

student_array
#include<iostream.h>
void studentFunc(int[], int[]);
main(){
int student[2], num[2], i;

for( i = 0; i < 3; i++ ){


cout << "\nPlease enter student id: ";
cin >> student[i];
cout << "\nPlease enter student num: ";
cin >> num[i];
}

studentFunc(student, num);

void studentFunc(int one[], int two[]){


int i , total,;
for(i = 0; i < 3; i++){
total += one[i];

//cout << two[i]<<endl;


}
cout << "\nIn sftudentFunc function, The total students are: "<< one[2] <<endl;
cout << "The highest marks obtain by student in class are: " << two[2] ;
}

matrix
#include<iostream.h>

main(){
int matrix[2][3], rows, cols, maxrows = 2, maxcols = 3;

for(rows = 0; rows < maxrows ; rows++){


for(cols = 0; cols < maxcols; cols++){
cout << "Please enter a value for position [ "<< rows << "," <<
cols<<"] = ";
cin >> matrix[rows][cols];
}
}

//display the value of martix


cout <<endl<< "The value enter by the user for matix are: "<< endl;

//the value entered by the user are for the matrix


for(rows = 0; rows < maxrows; rows++){

for(cols = 0; cols < maxcols; cols++){


cout << "\t"<< matrix[rows][cols];
}
cout << endl; //to start a new line for the next row
}

Lec 13
fliping_matrix
#include<iostream.h>
const int maxRow = 3;
const int maxCols = 3;

void readMatrix(int arr[][maxCols]);


void displayMatrix(int arr[][maxCols]);
void displayFilpedMatrix(int arr[][maxCols]);

main(){
int a[maxRow][maxCols];

//read the matrix through comand promopt;


cout << "\n"<<"Please enter element of matrix: \n";

readMatrix(a);

//display matrix
displayMatrix(a);
cout << "\n\n";

//display filped matrix


cout << "\n"<< "The filped matrix is: \n";
displayFilpedMatrix(a);

}
//This function will take value of
void readMatrix(int arr[][maxCols]){
int row, col;
for(row = 0; row< maxRow; row++){
for(col = 0; col<maxCols; col++){
cout << "\n Please enter "<<row<< ","<<col<< " Element: ";
cin >> arr[row][col];
}
cout << endl;
}

void displayMatrix(int arr[][maxCols]){


int row, cols;
for(row = 0; row < maxRow; row++ ){
for(cols = 0; cols<maxCols; cols++){
cout << "\t" << arr[row][cols]<<"\t";
}
cout << endl;
}
}

void displayFilpedMatrix(int arr[][maxCols]){


int row, cols;
for(row = maxRow -1; row>=0; row-- ){
for(cols = 0; cols<maxCols; cols++){
cout << "\t"<< arr[row][cols]<<"\t";
}
cout << endl;
}
}

unLuckyEmployess
/*
this is first cut of problem to solve real worl problem of 'Unlucky Employess'
*/
#include<iostream.h>

void getInput(double sal[][2], int numEmps);


void calNetSal(double sal[][2], int numEmps);
void findUnluckies(double sal[][2], int numEmps, int lucky[]);
void printUnlucky(int lucky, int numEmps);
void markIfUnlucky(double sal[][2], int numEmps, int lucky[], int upperBound, int
empNbr);

main(){
const int arraySize = 100;
double sal[arraySize][2];
int lucky[arraySize] = {0};
int numEmps;

// Read the actual number of employees in the company


cout << "\nPlease enter total number of employes in the company: ";
cin >> numEmps;
cout << endl;

// Read the gross salaries of the employees into the array 'sal'
getInput(sal, numEmps);

/* Calculate net salaries of the employess and store them in the array*/
cout << "\n\n Calculating the net salaries....";
calNetSal(sal, numEmps);

//Find the unlucky employess

cout << "\n\n Printing unlucky employees...!";


//printUnlucky(lucky, numEmps);
}

void getInput(double sal[][2], int numEmps){

for(int i = 0; i < numEmps; i ++){

//this numEmps is local to this function

cout << endl << "Please enter the gross salary for employee number:
"<<i<<": ";
cin >> sal[i][0];

//gross salaray for each employee

}
}

void calNetSal(double sal[][2], int numEmps){


for(int i = 0; i< numEmps; i++){

//This numEmps is local to this

variable

if(sal[i][0] >= 0 && sal[i][0] <= 5000){

//there is no tex deduction


sal[i][1] = sal[i][0];

}else if(sal[i][0] >= 5001 && sal[i][0] <= 10000){

//Tax deduction is 5%
sal[i][1] = sal[i][0] -(0.5 * sal[i][0]);

}else if(sal[i][0] >= 10000 && sal[i][0] <= 20000){


//text deductation is 10%
sal[i][1] = sal[i][0] - (.10 * sal[i][0]);
}else if(sal[i][0] >= 20000){
//text deductation is 15%
sal[i][1] = sal[i][0] - (.15*sal[i][0]);
}else{
//No need to do any thing
}

}
}

void findUnluckies(double sal[][2], int numEmps, int lucky[]){


for(int i = 0; i < numEmps; i++){
if(sal[i][0] >= 0 && sal[i][0]<=5000){
//No need to do anything in here
;
}else if(sal[i][0] >= 5001 && sal[i][0] <= 10000){

markIfUnlucky(sal, numEmps, lucky, 5001, i);

}else if(sal[i][0] >= 10000 && sal[i][0] <= 20000){

markIfUnlucky(sal, numEmps, lucky, 10001, i);

}else if(sal[i][0] <= 20001){


markIfUnlucky (sal, numEmps, lucky, 20001, i);
}
}
}

void markIfUnlucky(double sal[][2], int numEmps, int lucky[], int upperBound,


int empNbr){
for(int i = 0; i < numEmps; i++){

/*
See the if condition below, it will mark the employee unlucky even if
an
employee in the higher tax bracket is getting the same amount of net
salary as that of a person in lower tax bracket.
*/

if(sal[i][0] < upperBound && sal[i][1] >= sal[empNbr][1] ){


lucky[empNbr] = 1;
break;
}
}
}

//employee marked as unlucky

void printUnluckies(int sal[][2], int lucky[], int numEmps){


for(int i = 0; i < numEmps; i ++){
if(lucky[i] == 1){
cout << "\Emlopyee No.: " << i+1 << "is unlucky, Gross Salary =
"<<sal[i][0]<< " Net Salary ="<<sal[i][1]<<"\n";
}
}
}

Lec 14
bubbleSort
/*
This program uses bubble sorting to sort a given array
we use swap function to interchange the values by using pointers
*/
#include<iostream.h>
#include<stdlib.h>
void (int*, int*);

//prototype of swap used to swap two values

main(){
int x[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
int i, j, tmp, swaps;

for(i = 0; i<10; i ++){

swaps = 0;
for(j = 0; j<10; j++){

if(x[j] > x[j+1]){

//compare two values enterchange if needed

swaps++;
swap(&x[j], &x[j+1]);
}
}

//display the arrays element after each comparision

for(j=0; j<10; j++){


cout << x[j]<<'\t';

if(swaps == 0)
break;
}
}
}

void swap(int *x, int *y){


int tmp;
if( *x > *y){
tmp = *x;
*x = *y;
*y = tmp;
}
}

caseCoversion
#include<iostream.h>
#include<ctype.h>
#include<stdlib.h>

void convertToUpperCase(char*);

main(){
char s[20] = "The Quick Brown Fox";
cout << "The string before conversion is: " << s <<endl;
convertToUpperCase(s);
cout << "The string after conversion is: " << s;
}

void convertToUpperCase(char *sptr){

while(*sptr != '\0'){
if(islower(*sptr)){
*sptr = toupper(*sptr);
cout << "\nin main: "<<sptr <<endl;
}
++sptr;
}
}

Lec 15
pionterSubtraction
// Program using the pointer subtraction
#include<iostream.h>
main(){
int y[10], *yptr1, *yptr2;
y[0] = 6;
y[5] = 10;

cout << "y[0] is: "<<y[0]<<endl;


cout << "y[5] is: "<<y[5]<<endl<<endl;
yptr1 = &y[0];
yptr2 = &y[5];

cout << "The difference of pointers is: "<< yptr2 - yptr1;


}

pointerCompare
/*Program using difference pointer comparison*/

#include<iostream.h>
main(){
int x, y, *xptr, *yptr;
cout << "\nPlease enter the value of x: ";
cin >> x;
cout << "\nPlease enter the value of y: ";
cin >> y;

xptr = &x;
yptr = &y;
if(*xptr > *yptr){
cout << "\n X is greater then y";
}else{
cout << "\n Y is greater then x";
}
}

charArray

// "\0" is neccessary to write in the end of string, else array continusaly print
garbage on screen
#include<iostream.h>
main(){
char name[20];
char nameTwo[10] = "Amir"; //here array autometicaly assigne "\0" in the end

name[0] = 'a';
name[1] = 'b';
name[2] = 'c';
name[3] = '\n';

for(int i = 0; i<15; i++){


cout << name[i];
}
cout <<"\n\n\n";
for(int i = 0; i<15; i++){
cout << nameTwo[i];
}
}

copyArray
/*This program copies a character array into a given array*/
#include<iostream.h>
main(){

char strA[80] = "A test for";


char strB[80];

char *ptrA; //a pointer to type character


char *ptrB; //a pointer to type character

ptrA = strA; //point ptrA at string A


ptrB = strB; //point ptrB at string B

while(*ptrA != '\0'){
*ptrB++ = *ptrA++;

//coping character by character

}
*ptrB = '\0';

cout << "String in strA: " << strA << endl;


cout << "String in strA: " << strB << endl;
}

pointerIncrement
#include<iostream.h>
main(){
int y [10] = {1, 2, 3, 4, 5, 6, 7, 8, 9 ,10};
int *yptr;

yptr = y;

cout << "The address of yptr is: " << yptr<<endl;


cout << "Content of yptr is through *yptr: " << *yptr<<endl;
cout << "Printing pointer after adding 5: "<<endl<<*(yptr+5)<<endl;

yptr ++;
cout <<"\nAs a int occupies 4 bytes in memory there after Printing pointer
afterh incrementing: "<<endl<< *yptr<<endl;
system("pause");
}

Lec 16
pointerIncrement
#include<iostream.h>
main(){
//to avoid the confusion, we have int type below.
int multi[5][10];
cout << "The value of multi is: "<<multi<<endl;
cout << "The value of *multi is: "<<*multi<<endl;
system("pause");
}

Lec 18 >> reading file

Txt file
Name Salary Department
Aamir 12000 Sales
Amara 15000 HR
dnan 13000 IT
Afzal 11500 Marketing

TxtFileR
/*
This program reads from a txt file "myfile.txt" which contains
the employee information
*/

#include<iostream.h>
#include<fstream.h>

main(){
char name[50];
char sal[10];
char dept[30];

//used to read name of employee form file


//used to read salry of employee form file
//used to read dept of employee from file

ifstream inFile; //Handle for the input file

char inputFileName[] = "myfile1.txt"; //file name, this is in the current directory

inFile.open(inputFileName);

//opening file

//checking that file is success fully opened or not


if(!inFile){
cout<< "Can't open input file named "<<inputFileName<<endl;
system("pause");
exit(1);

//if file not open return control to the operating system

//reading the complete file word by word and printing on screen


while(!inFile.eof()){
inFile>>name>>sal>>dept;
cout<< name<<"\t" <<sal << "\t" <<dept << endl;
}

inFile.close();

system("pause");
}

>> simple writing >> out mode


Output.txt
Welcome to Virtual University

fileWrite

#include<iostream.h>
#include<fstream.h>
main(){

char fileName[]= "output.txt";


char txtToWrite[] = "Welcome to Virtual University";

ofstream outputFile;
outputFile.open(fileName, ios::out);

if(!outputFile){
cout<< "Sorry. Given file "<<fileName <<" can't open";
system("pause");
exit(1);
}

outputFile << txtToWrite;


outputFile.close();
system("pause");
}

>> app mode


Output.txt
Welcome to Virtual University
Welcome to Virtual University
Welcome to Virtual University

fileWrite
#include<iostream.h>
#include<fstream.h>
main(){

char fileName[]= "output.txt";


char txtToWrite[] = "Welcome to Virtual University\n";

ofstream outputFile;
outputFile.open(fileName, ios::app);
/*
Append rather than truncate an existing file. Each insertion
(output) will be written to the end of the file
*/
if(!outputFile){
cout<< "Sorry. Given file "<<fileName <<" can't open";
system("pause");
exit(1);
}

outputFile << txtToWrite;


outputFile.close();
system("pause");
}

>> trunc mode


Output.txt
Welcome to Virtual University

fileWrite
#include<iostream.h>
#include<fstream.h>
main(){

char fileName[]= "output.txt";


char txtToWrite[] = "Welcome to Virtual University\n";

ofstream outputFile;
outputFile.open(fileName, ios::trunc);//trunc Open a file or stream for insertion
(output)

if(!outputFile){
cout<< "Sorry. Given file "<<fileName <<" can't open";
system("pause");
exit(1);
}

outputFile << txtToWrite;


outputFile.close();

system("pause");
}

>> ate mode


Output.txt
Welcome to Virtual University

fileWrite
#include<iostream.h>
#include<fstream.h>
main(){

char fileName[]= "output.txt";


char txtToWrite[] = "Welcome to Virtual University";

ofstream outputFile;
outputFile.open(fileName, ios::ate);
/*
ate rather than truncate an existing file. Each insertion
(output) will be written to the end of the file
*/
if(!outputFile){
cout<< "Sorry. Given file "<<fileName <<" can't open";
system("pause");
exit(1);

outputFile << txtToWrite;


outputFile.close();
system("pause");
}

>> get func


Output.txt
Welcome to Virtual University

fileWrite
#include<iostream.h>
#include<fstream.h>
main(){

char fileName[]= "output.txt";


char txtToWrite[] = "Welcome to Virtual University";

ofstream outputFile;
outputFile.open(fileName, ios::ate);
/*
ate rather than truncate an existing file. Each insertion
(output) will be written to the end of the file
*/
if(!outputFile){

cout<< "Sorry. Given file "<<fileName <<" can't open";


system("pause");
exit(1);
}

char c;
while ( (c = outputFile.get()) != EOF)
{
// do all the processing
outputFile.put(c);
}

// outputFile << txtToWrite;


outputFile.close();
system("pause");
}

>> getline
Test.txt
hello world
gud luck
good morning

getline

#include<iostream.h>
#include<fstream.h>
main(){
ifstream inFile;

//Handle for the input file

char inputFileName[] = "test.txt";


const int MAX_CHAR_TO_READ = 13; //maximum character to read in onr linr
direcotry
char completeLineText[MAX_CHAR_TO_READ];

inFile.open(inputFileName);

// to be used in getLine function

//opening the file

//checking that file is successfuly opened or not


if(!inFile){
cout << "Can't open input file named "<<inputFileName<<endl;
system("pause");
exit(1);
}

//reading the complete file line by line and printing on screen


while(!inFile.eof()){
inFile.getline(completeLineText, MAX_CHAR_TO_READ);
cout<< completeLineText<<endl;
}
inFile.close();
system("pause");
}

>> strtok
Salin.txt
Aamir 12000
Amara 15000
Adnan 13000
Afzal 11500

Salout.txt
The total salary = 51500

strtoken
/*
This program reads name and salary from a txt file
Calculate the salaries and write the total in an output file
*/
#include<iostream.h>
#include<fstream.h>
#include<cstring>
#include<cstdlib>
main(){
ifstream inFile;

//Handle for the input file

char inputFileName[] = "salin.txt"; //file name, this file is in the current


directory

ofstream outFile;

//handle for the output file

char outputFileName[] = "salout.txt"; //file name, this file is in the current


direcotry

const int MAX_CHAR_TO_READ = 100;

//maximum character to read in one

line
char completeLineText[MAX_CHAR_TO_READ];

//used in getLine function

char *tokenPtr;
int salary, totalSalary;

salary = 0;
totalSalary = 0;

inFile.open(inputFileName);
outFile.open(outputFileName);

//Opening the input file


//Opening the output file

//Checking that file is successfully opened or not


if(!inFile){
cout << "Can't open input file named "<< inputFileName << endl;
system("pause");
exit(1);
}
if(!outFile){
cout << "Can't open output file named "<< outputFileName<< endl;
system("pause");
exit(1);
}

//reading the complete file line by line calculating the total salary
while(!inFile.eof()){

inFile.getline(completeLineText, MAX_CHAR_TO_READ);
tokenPtr = strtok(completeLineText, " "); //first token is name
tokenPtr = strtok(NULL, " ");

salary = atoi(tokenPtr);
totalSalary += salary;
}

//writing the total into the output file


outFile << "The total salary = "<<totalSalary;

//closing the files


inFile.close();
outFile.close();
system("pause");
}

Lec 19 \1 read Write


writing
/*
Following program writes an integer, a floating-point value, and
a character to a file called test.
*/

#include<iostream.h>
#include<fstream.h>
main(){
ofstream out("test.txt");
if(!out){
cout << "Can't open file."<<endl;
system("pause");
return 1;
}

out << 1000 << " "<< 123.123 << "a";


out.close();
cout << "File has been written."<<endl;
system("pause");
return 0;
}

reading
/*
Following program reads an integer, a float and a character from
the file created by the preceding program.
*/
#include<iostream.h>
#include<fstream.h>
main(){
char ch;

int i;
float f;

ifstream in("test.txt");

if(!in){
cout << "Can't open file."<<endl;
system("pause");
return 1;
}

in >> i;
in >> f;
in >> ch;

/*
Note that white space are being ignored, you can turn this of using
unsetf(ios::skipws);
*/

cout << i << " "<< f << " " << ch << endl;

system("pause");
return 0;
}

\2 file copy
Copied.txt
Hello world

File.txt
Hello world

copyFile
/* Code snippet to copy the file thisFile to the file thatFile */
#include<iostream.h>
#include<fstream.h>
main(){
ifstream fromFile("file.txt");
if(!fromFile){
cout << "Unable to open "<<fromFile << " for input."<<endl;
system("pause");
return 1;
}
cout << "Current get posistion of file is to read: " << fromFile.tellg()<<endl;

ofstream toFile("copied.txt");

if(!toFile){
cout << "Unable to open "<<toFile << " for output.";
system("pause");
return 1;
}

cout <<endl<< "****************** Start Copying file


**********************"<<endl;
char c;
while( fromFile.get(c)){
toFile.put(c);
cout << c ;
}
cout <<"************* File is copied with above given words ********\n"<<endl;

cout << "Next position to write a character on copid file: "


<<toFile.tellp()<<endl;
system("pause");
return 0;
}

\3 tellg tellp

\4 seekg tellp
Test.txt
hello world
hello world

seekgTellp

/*
This is a sample program to determine the length of a file. The program
accepts the name of the file as a command-line argument.
*/
#include<iostream.h>
#include<fstream.h>
#include<stdlib.h>
ifstream inFile;
ofstream outFile;
main(int argc, char **argv){
inFile.open("test.txt");
if(!inFile){
cout << "Error opening file in input mode "<<endl;
system("pause");
exit(1);
}
/*
Determine file length opening it for input
*/
cout << inFile.seekg(0, ios::end)<<endl;

//Go to the end of the file

long inSize = inFile.tellg(); //Get the file pointer posistion


cout << "The length of the file (inFile) is: "<<inSize;
inFile.close();

/*
Determice file length opening it for output

*/
outFile.open("test.txt", ios::app);
if(!outFile){
cout << "Error opeing file in append mode"<<endl;
system("pause");
exit(1);
}

outFile.seekp(0, ios::end);
long outSize = outFile.tellp();
cout << "\nThe length of the file (outFile) is: "<<outSize<<endl;
outFile.close();

system("pause");
}

\5 replace word
Test.txt
hello world
This is a sample. hell samrld

repalce
/*
This program firstly writes a string into a file and then replaces
its partially. It demonstrates the use of seekp(), tellp() and write()
functions.

*/
#include<fstream.h>
#include<iostream.h>
main(){
long pos;
ofstream outfile;
outfile.open("test.txt");
// outfile.write("hello world \n This is a sample. hello world", 44);
outfile<<"hello world \n This is a sample. hello world";
pos = outfile.tellp();
outfile.seekp(pos-7);
outfile.write(" sam", 4);
outfile.close();
system("pause");
return 0;
}

\6 Efficiently Read and Write


Test.txt
hello world
This is a sample. hell samrld

outFile.txt

repalce

/*
Here, a loop will be used to process the whole file. We will see that it is
much faster due to being capable of reducing the number of calls to reading
and writing functions. Instead of 10000 getc () calls, we are making only
one read () function call. The performance is also made in physical reduced
disk access (read and write). Important part of the program code is given
below:
*/
#include<fstream.h>
#include<iostream.h>
main(){
int i= 0;
int j = 0;
char str[10000];
ifstream fi;
ofstream fo;

//open the input file


//open the output file

fi.open("test.txt", ios::in);

//open the input file

fo.open("outFile.txt", ios::out); //open the output file

fi.seekg(0, ios::end); //go the end of input file


fi.tellg();

//get the position;

fi.seekg(0, ios::beg); //go to the start of input file


for(i=0; i<j/1000; i++){
fi.read(str, 10000); //read the remaining bytes
fo.write(str, 10000); //wrote 10000 bytes

fi.read(str, j-(i*10000));

//read the remaining bytes

fo.write(str, j-(i*10000));

//wrote the remaining bytes

fi.close();
fo.close();
system("pause");
}

\7 sizeof()
Test.txt
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14

15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92

93
94
95
96
97
98
99

sizeof
#include<iostream.h>
#include<fstream.h>
main(){
int i;
char c = 'a';
long l;
double d;
float f;

//sizeof() function tell the size fo differnt type of variables


cout << "Sizeof() function\nSize of given data type is: " << sizeof(f)<<endl;

ofstream fo;
ifstream fi;
fi.open("test.txt");
fo.open("test.txt");
if(fo){
for (i = 0; i<100; i++){

//fo.write("\n", i); //to write binary


fo<<i<<endl;

//to write int

}
}
if(fi){
//fi>>i;
cout << "\nStart reading file\n";
while(!fi.eof()){
fi>>i;
cout<<i<<endl;
}
}

fo.close();
fi.close();
system("pause");
}

\8 Complicated Example
my-File.txt
hello world

seekg get
/*
This is a sample program to demonstrate the use of open(), close(), seekg(), get()
functions and streams. It expects a file named my-File.txt in the current directory
having some data strings inside it.
*/
#include<iostream.h>
#include<fstream.h>
#include<stdlib.h>

// Decalreing the stream objects


ifstream inFile;
ofstream scrn, prnt;
main(){
char inChar;
inFile.open("my-File.txt", ios::in);

//open the file for input

if(!inFile){
cout << "Error opening file"<<endl;
system("pause");
}
scrn.open("CON", ios::out);

//attach the console with the output stream

while(inFile.get(inChar)){

//read the whole file one charater at a time

scrn<<inChar;
}

scrn.close();

//close the output stream

inFile.seekg(0, ios::beg);

//Go to the beginning of the file

prnt.open("LPT1", ios::out);

//Attach the output stream with the LPT1 port

while(inFile.get(inChar)){
prnt << inChar;

//read the whole file one character at a time


//insert read character to the output stream

}
prnt.close();

//close the output stream

inFile.close();

//close the input stream

system("pause");
}

\9
my-File.txt
ABCDEFGHIJKLMNOPQRSTUVWXY

Test
/*
this sample code demostrates the use of fstream and seekg() function.
it will create a file named my-File.txt write alphabets into it, destroys the
previous contents.
*/
#include<iostream.h>
#include<fstream.h>

fstream rFile;

// Declare the stream object

main(){
char rChar;
//opened the file both input and ouput modes
rFile.open("my-File.txt", ios::in || ios::out);
if(!rFile){
cout << "error opening file" << endl;
}
//run the loop for whole alphabets
for(rChar = 'A'; rChar<'Z'; rChar++){
rFile << rChar; //insert the character in the file
}
rFile.seekg(81, ios::beg); //seek the beginning and move 8 byets forward
rFile >> rChar;

//take out the character from the file

cout << "The 8th character is: " << rChar;

rFile.seekg(-161, ios::end); //Seek the end and move 16 position backward


rFile >> rChar;

//take out the character at the current posistion

cout << "\nThe 16th character from the end is: "<< rChar<<"\n";
rFile.close(); //close the file

system("pause");
}

Lec 20

\1 strcture
Struct
/*
Simple program showing the initialization of structure.;
*/
#include<iostream.h>

//Declaring student structure


struct student{
char name[64];
char course[128];
int age;
int year;
};

main(){

//initializing the structure


student s1 = {"Ali", "Cs201-Intorduction to programming", 22, 2002};

cout << "Displaying the structure data memebers \n";


cout << "The name is " << s1.name << endl;
cout << "The course is " << s1.course << endl;
cout << "The age is" << s1.age << endl;
cout << "The year is " << s1.year << endl;
system("pause");

\2 arrow access
arrow access
/*
This program shows the access of structure data members with pointer to structure
*/
#include<iostream.h>
struct student{
char name[30];
char course[60];
int age;
int year;
};
main(){
student s1 = {"Syed Shujaat Ali", "Cs201", 20, 2002};
student *sPtr;

sPtr = &s1;
cout << "Displaying the stricture data members using pointers"<<endl;
cout << "Usnig the * operator"<<endl;

cout << "\nThe name is: "<< (*sPtr).name;


cout << "\nThe course is: "<< (*sPtr).course;

cout << "\nThe age is: "<< (*sPtr).age;


cout << "\nThe year is: "<< (*sPtr).year <<endl;
cout << endl;

cout << "\n\nUsing the -> operator"<<endl;

cout << "\nThe name is " << sPtr->name;


cout << "\nThe course is " << sPtr->course;
cout << "\nThe age is "<< sPtr->age;
cout << "\nThe year is "<< sPtr->year << endl;

system("pause");
}

\3 sizeof
Sizeof
/*
This program shows the memory size of structure
*/
#include<iostream.h>

main(){
//declaring student structure
struct student{
char name[64];

char course[128];
int age;
int year;
};
student s1 = {"Ali", "Cs201", 24, 1990};
//using sizeof() operator detemine the size

cout << "Size of s1.name: " << sizeof(s1.name)<<endl;


cout << "Size of s1.course: " << sizeof(s1.course)<<endl;
cout << "Size of s1.age: " << sizeof(s1.age)<<endl;
cout << "Size of s1.year: " << sizeof(s1.year)<<endl;
cout << "Total size structure s1 occupies: "<<sizeof(s1)<< " bytes in the
memeory" <<endl;

system("pause");
}

\4 struct averages
struct averages
/*
This program calculates the average age and average GPA of a class.
Also determine the grade of the class and the student with max GPA. we will
use a student structure and manipulate it to get the desired result.
*/
#include<iostream.h>

main(){
//declaring student structure
struct student{
char name[30];
char course[15];
int age;
float GPA;
};

int noOfStudents = 3;

//total no of students

student students[noOfStudents];

//array of student structure

int totalAge, index, averageAge;


float totalGPA, maxGPA, averageGPA;

//initializing the structure, getting the input from user


for(int i = 0; i < noOfStudents; i++){
cout << endl;
cout << "Enter data for student#: "<< i+1 << endl;
cout << "Enter the Student's Name: ";
cin >> students[i].name;

cout << "Enter the student's Course: ";


cin >> students[i].course;

cout << "Enter the Studetn's Age: ";


cin >> students[i].age;

cout << "Enter the Student's GPA: ";


cin >> students[i].GPA;
}

maxGPA = 0;
//calculating the total age, total GPA and max GPA
for(int j = 0; j < noOfStudents; j++){
totalAge = totalAge + students[j].age;
totalGPA = totalGPA + students[j].GPA;

//determining the max GPA and storing its index


if(students[j].GPA>maxGPA){
maxGPA = students[j].GPA;
index=j;
}
}
//calculating the average age
averageAge = totalAge/noOfStudents;
cout << "\nThe average age is: "<< averageAge<<endl;

//calculating the averageGPA


averageGPA = totalGPA/noOfStudents;
cout << "\nThe average GAPA is: "<< averageGPA<< endl;
cout << "\nStudent with maxGPA is: "<<students[index].name<<endl;

//Determining the grade of the class


if(averageGPA > 4){
cout << "\nWrong grades have been enter: "<<endl;
}else if(averageGPA == 4){
cout << "\nThe average Grade of the class is: A"<<endl;
}else if(averageGPA>=3){
cout << "\nThe average Grade of the class is: B"<<endl;
}else if(averageGPA>=2){
cout << "\nThe average Grade of the class is: C"<<endl;
}else{
cout << "\nThe average Grade of the class is: F"<<endl;
}

system("pause");
}

Lec 21
\1 hexadecimal bit
/*
this program determines whether the fourth bit a number entered by user is set or
not
*/
#include<iostream.h>

main(){
int number;
cout << "Please enter a number : ";
cin >> number;
if(number & 0x8)

//8 is written in dexadecimal form

cout << "The fourth bit of the number is set" << endl;
else
cout << "The fourth bit of the number is not set" << endl;

system("pause");
}

\2 PassWordEncDenc
/*
The program takes a password from user, encryptsit by using Exclusive OR ( ^) with
a number. It displays the encrypted password. Then it decrypts the encrypted
password using Exclusive OR ( ^ ) with the same number and we get the original
password again.

This program demonstrate the encryption by using ^ operator


*/
#include<iostream.h>
main(){
char password[10];
char *passptr;
cout << "Please enter a password (less than 10 character):";

cin >> password;


passptr = password;
//now enctrypting the password by using ^ with 3
while(*passptr != '\0'){
*passptr = (*passptr ^ 3);
++passptr;
}
cout << "The encrypted password is: " << password << endl;

//now decrypting the encrypted password by using ^ with 3


cout << "Position of *ptr = " << &passptr << endl;
passptr = password;
cout << "Position of *ptr = " << &passptr << endl;
while(*passptr != '\0'){
*passptr = (*passptr ^ 3);
++passptr;
}
cout << "The decrypted password is: " << password << endl;
system("pause");
}

\3 shiftOperator
/*
this program demonstrate the left and right shift
*/
#include<iostream.h>
main(){

int number, result;


cout << "Please enter a number: ";
cin >> number;
result = number << 1;
cout << "The number after left shift is " << result << endl;
cout << "The number after left shift again is " << (result << 1) << endl;
cout << "Now applying right shift " << endl;
result = number >> 1;
cout << "The number after right shift is "<< result << endl;
cout << "The number after right shift again is " << (result >> 1) << endl;
system("pause");
}

You might also like