Progs of cs201
Progs of cs201
Progs of cs201
#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
/*
Char
/*this program store char data type*/
#include<iostream.h>
main(){
char a, b;
a = 'The';
b = ' Good';
cout << a ;
cout << b;
}
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':
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':
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;
int totalAges;
float avarageAge;
totalAges = age1 + age2 ;//+ age3 + age4 + age5 + age6 + age7 + age8 +
age9 + age10;
avarageAge = totalAges/2;
External-link
#include<iostream.h>
#include<evenOdd.h>
int EvenOdd(int x);
signature
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;
}
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;
evenOdd
/*
This program takes a number as input and check weather number is even or odd
throug function.
and then provide output
*/
#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;
}
functionCalculPow
double returnPowerNum(double a, int b){
double result = 1.0;
int i;
#include<iostream.h>
main(){
double number;
int
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
#include<iostream.h>
main(){
int input, result;
cout << "\nPlease enter a number: ";
cin >> input;
//
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;
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;
square (&x);
//address of 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;
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
/*
Lec 12
string_array
#include<iostream.h>
main(){
char name[10];
cout <<endl << "Please enter a new name: ";
cin >> name;
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);
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;
studentFunc(student, num);
matrix
#include<iostream.h>
main(){
int matrix[2][3], rows, cols, maxrows = 2, maxcols = 3;
Lec 13
fliping_matrix
#include<iostream.h>
const int maxRow = 3;
const int maxCols = 3;
main(){
int a[maxRow][maxCols];
readMatrix(a);
//display matrix
displayMatrix(a);
cout << "\n\n";
}
//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;
}
unLuckyEmployess
/*
this is first cut of problem to solve real worl problem of 'Unlucky Employess'
*/
#include<iostream.h>
main(){
const int arraySize = 100;
double sal[arraySize][2];
int lucky[arraySize] = {0};
int numEmps;
// 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);
cout << endl << "Please enter the gross salary for employee number:
"<<i<<": ";
cin >> sal[i][0];
}
}
variable
//Tax deduction is 5%
sal[i][1] = sal[i][0] -(0.5 * sal[i][0]);
}
}
/*
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.
*/
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*);
main(){
int x[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
int i, j, tmp, swaps;
swaps = 0;
for(j = 0; j<10; j++){
swaps++;
swap(&x[j], &x[j+1]);
}
}
if(swaps == 0)
break;
}
}
}
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;
}
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;
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';
copyArray
/*This program copies a character array into a given array*/
#include<iostream.h>
main(){
while(*ptrA != '\0'){
*ptrB++ = *ptrA++;
}
*ptrB = '\0';
pointerIncrement
#include<iostream.h>
main(){
int y [10] = {1, 2, 3, 4, 5, 6, 7, 8, 9 ,10};
int *yptr;
yptr = y;
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");
}
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];
inFile.open(inputFileName);
//opening file
inFile.close();
system("pause");
}
fileWrite
#include<iostream.h>
#include<fstream.h>
main(){
ofstream outputFile;
outputFile.open(fileName, ios::out);
if(!outputFile){
cout<< "Sorry. Given file "<<fileName <<" can't open";
system("pause");
exit(1);
}
fileWrite
#include<iostream.h>
#include<fstream.h>
main(){
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);
}
fileWrite
#include<iostream.h>
#include<fstream.h>
main(){
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);
}
system("pause");
}
fileWrite
#include<iostream.h>
#include<fstream.h>
main(){
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);
fileWrite
#include<iostream.h>
#include<fstream.h>
main(){
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){
char c;
while ( (c = outputFile.get()) != EOF)
{
// do all the processing
outputFile.put(c);
}
>> getline
Test.txt
hello world
gud luck
good morning
getline
#include<iostream.h>
#include<fstream.h>
main(){
ifstream inFile;
inFile.open(inputFileName);
>> 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;
ofstream outFile;
line
char completeLineText[MAX_CHAR_TO_READ];
char *tokenPtr;
int salary, totalSalary;
salary = 0;
totalSalary = 0;
inFile.open(inputFileName);
outFile.open(outputFileName);
//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;
}
#include<iostream.h>
#include<fstream.h>
main(){
ofstream out("test.txt");
if(!out){
cout << "Can't open file."<<endl;
system("pause");
return 1;
}
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;
}
\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;
/*
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;
}
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;
fi.open("test.txt", ios::in);
fi.read(str, j-(i*10000));
fo.write(str, j-(i*10000));
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;
ofstream fo;
ifstream fi;
fi.open("test.txt");
fo.open("test.txt");
if(fo){
for (i = 0; i<100; i++){
}
}
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>
if(!inFile){
cout << "Error opening file"<<endl;
system("pause");
}
scrn.open("CON", ios::out);
while(inFile.get(inChar)){
scrn<<inChar;
}
scrn.close();
inFile.seekg(0, ios::beg);
prnt.open("LPT1", ios::out);
while(inFile.get(inChar)){
prnt << inChar;
}
prnt.close();
inFile.close();
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;
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;
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>
main(){
\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;
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
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];
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;
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)
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.
\3 shiftOperator
/*
this program demonstrate the left and right shift
*/
#include<iostream.h>
main(){