0% found this document useful (0 votes)
18 views46 pages

Coding

The program declares an integer variable i and initializes it to 10. It then declares an integer pointer variable ptr and uses the address-of operator (&) to make ptr point to the memory address of i. The value of i (which is 10) is printed using the pointer ptr. This demonstrates that a pointer can be used to access the value of a variable it points to.

Uploaded by

raaed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
18 views46 pages

Coding

The program declares an integer variable i and initializes it to 10. It then declares an integer pointer variable ptr and uses the address-of operator (&) to make ptr point to the memory address of i. The value of i (which is 10) is printed using the pointer ptr. This demonstrates that a pointer can be used to access the value of a variable it points to.

Uploaded by

raaed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 46

Program illustrates user interactive input of array element

Write a C++ program that asks the users to enter 5 integer numbers as
elements of an array, and displays them on the monitor.

#include <iostream>
using namespace std;
int main()
{ int A[5]; //Declaration array A
int i ;
//read elements of array from keyboard
for(i=0;i<=4;i++)
{
cout<<"Enter an integer : ";
cin>>A[i]; //Entering array elements
}
//for loop for output of array
for(i=0;i<=4;i++)
cout<<"A["<<i<<"]= "<<A[i]<<"\t";
return 0;
}
1
Copy one Array to another
#include<iostream>
using namespace std;
int main()
{ int a[5]; //a is an array of 5 integers
int b[5]; //b is an array of 5 integers
int i;
for(i=0; i<5; i++) // this loop is used to enter 5 integer numbers.
{ cout<<"b["<<i<<"]= ";
cin>>b[i]; //entering array b elements
}
for (i=0; i<5; i++) // this loop is used to print array b element's value
cout<<“b["<<i<<"]= "<<b[i]<<"\t";

for (i=0; i<5; i++) // this loop is used to copy elements from array b to array a
{ a[i]=b[i];
cout<<"a["<<i<<"]= "<<a[i]<<"\t";
}
return 0;
}
2
Searching a value in an Array? (Linear Searching)
#include<iostream>
using namespace std;
int main()
{
int A[10]={2,0,-6,8,5,12,15,5,0,20};//Declaration and initialization
int x,i;
bool found = 0;
cout<<"Enter integer search Key : ";
cin>>x; //x is the value to be searched in the array

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


{
if(A[i]==x) //if found
{found = 1;
break;
}
}
if(found == 1)
cout<<"Found value in element "<<i<<endl;
else
cout<<"Value not found"<<endl;
return 0; } 3
Finding the array element with maximum value in
an array
#include<iostream>
using namespace std;
int main()
{int i ; max = A[0];//initialize with first array element
int A[10];//A is an array of 10 integers
int max; for(i=1; i<10; i++)
{
if(A[i]>max)
for(i=0; i<10; i++)
max = A[i];/*stores current value if it is
{ higher than the highest so far*/
cout<<"Enter A["<<i<<"]="; }
cin>>A[i]; //Entering array elements cout<<endl;
} cout<<“maximum value = "<<max<<endl;
return 0;
cout<<"\n array elements numbers :\n";
//output each element's array value }

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


cout<<A[i]<<"\t";

4
Swapping
#include<iostream>
using namespace std;
int main()
{ int A[10];
int i,x;

for(i=0;i<10;i++)
A[i]=i;

for(i=0;i<10;i++)
cout<<"A["<<i<<"]="<<A[i]<<"\t";

x=A[0];
A[0]=A[9];
A[9]=x;
//swap(A[0],A[9])
cout<<"Array after swapping"<<endl;

for(i=0;i<10;i++) //for loop for output of array


cout<<"A["<<i<<"]="<<A[i]<<"\t";
5
return 0; }
PROGRAM : Illustrates arithmetic operations on
array elements.
#include<iostream>
using namespace std;
int main()
{double sum = 0, average = 0;
double price[5];
int i, size;
cout<<"write elements of array"<<endl;
for(i=0; i<5; i++)
cin>>price[i]; //Entering price elements
size = sizeof (price)/sizeof(double); // size is the number of elements in an array
cout<<"size ="<<size; //sizeof (price) is the total number of bytes used for array

for(i=0; i<size; i++) //use of size


sum += price[i];
cout<<"\nelements of array :"<<endl;
for(i=0; i<size; i++) //use of size
cout<<price[i]<<"\t" ;
cout<<"\nthe number of elements in array is = "<<size<<endl;
cout<<"sum ="<<sum<<endl;
cout<<"average price = "<<sum/size<<endl;
return 0;
6
}
Simple program to sort an Array
#include<iostream>
cout<<"array after sort"<<endl;
using namespace std;
for(i=0; i<=4; i++)
int main() cout<<A[i]<<"\t";
{ int A[5]={6,4,2,1,4};//Declaration and initialization
return 0 ;
int i,j,temp;
}

for(i=0; i<4; i++)


{
for(j=i+1; j<=4; j++)
{
if (A[i]>A[j])
{
temp=A[i];
A[i]=A[j];
A[j]=temp;
}
}
}

7
PROGRAM Illustrates input/output of two
dimensional arrays.
#include<iostream>
using namespace std;
int main()
{ int matrix[2][3];
int row,col ;

for(row=0;row<2;row++)
{ for(col=0;col<3;col++)
{ cout<<"matrix["<<row<<"]["<<col<<"]=";
cin>>matrix[row][col]; //Entering matrix elements
}
}
cout<<"you have entered the following numbers for matrix<"<<endl;
for(row=0;row<2;row++)
{
for(col=0;col<3;col++)
{ cout<<matrix[row][col]<<"\t";
}
cout<<endl;
}
return 0;
8
}
Example Transpose Matrix
#include<iostream>
using namespace std;

int main()
{int A[4][3]={0,1,2,3,4,5,6,7,8,9,10,11};
int B[3][4];
int i,j;
cout<<"Matrix B\n\n";

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


{
for(j=0; j<4; j++)
{
B[i][j]=A[j][i];
cout<<B[i][j]<<"\t";
}
cout<<endl;
}
return 0;
9
}
PROGRAM Illustrates passing of an array to a
function.
using namespace std;
double average (double [], unsigned int ); //prototype of the function average
int main()
{ int i, n=10;
double A[10];
cout<<"Enter 10 floating point numbers"<<endl;
for(i=0; i<10; i++)
{ cout<<"A["<<i<<"]=";
cin>>A[i]; //entering the array elements
}
cout<<"you have entered the following numbers :"<<endl;
for(i=0; i<10; i++)
cout<<A[i]<<"\t";

cout<<"\nAverage = "<<average(A,n)<<endl;
return 0;
}
10
double average (double A[],unsigned int n) //definition of function
{
int i;
double sum=0;
for(i=0; i<n; i++)
{sum = sum + A[i];}

return(sum/n);

11
String

#include<iostream>
#include<cstring>
using namespace std;

int main()
{ char name[4];

strcpy(name,"sam");
cout<<name;

return 0 ;
}

12
Q : Takes a first name and a last name and combines the two
strings.
#include<iostream>
#include <cstring>
using namespace std;
int main()
{
char first[100]; // first name
char last[100]; // last name
char full_name[200]; //full version of first and last name

strcpy(first, "Muhammad"); // Initialize first name


strcpy(last, "Ali"); //Initialize last name
strcpy(full_name, first); // full _name= "Muhammad"
// Note: strcat not strcpy
strcat(full_name, " "); //full_name = "Muhammad "
strcat(full_name, last); //full _name= "Muhammad Ali"
cout<<"The full name is" << full_name;
return 0;
}
13
PROGRAM Illustrates strlen() and strcpy() functions.
#include<iostream>
#include<cstring>
using namespace std;

int main() The expected output is given below.


{char Str1[]="Mona";
char Str2[]="learn C++"; Length of Str1= 4
char Str3[]="Lisa"; Length of Str2 = 9
Contents of Str1 are = Mona
Contents of Str2 are = Learn C++
cout<<"Length of Str1 = "<<strlen(Str1)<<endl; Now contents of Str1 = Learn C++
Now contents of Str2 = Learn C++
cout<<"Length of Str2 = "<<strlen(Str2)<<endl;

cout<<"Contents of Str1 are = "<<Str1<<endl;


cout<<"Contents of Str2 are = "<<Str2<<endl;
strcpy(Str1,Str2);
cout<<"Now contents of Str1 = "<<Str1<<endl;
cout<<"Now contents of Str2 = "<<Str2<<endl;
return 0;
}
PROGRAM 1 – Illustrates declaration of pointers
and use of address-of operator (&)
#include<iostream>
using namespace std;
int main()
{
int n = 60 ; //n is integer variable
double B = 8.56; //B is double variable
int *ptrn = &n ; //ptrn is pointer to int variable n
double *pB = &B; //pB is pointer to double variable B

cout<<"n = "<<n<<", B = "<<B<<endl;


cout<<"The address of n is = "<<&n<<" , ptrn = "<<ptrn<<endl;
cout<<"*ptrn = "<<*ptrn<<", *pB = "<<*pB<<endl;
cout<<"The address of B is = "<<&B<<" , pB = "<<pB<<endl;
cout<<"Address of ptrn = "<<&ptrn<<endl;
return 0;
}

15
Output

• The expected output is given below.

n = 60, B = 8.56
The address of n is = 0012FF7C , ptrn = 0012FF7C
*ptrn = 60, *pB = 8.56
The address of B = 0012FF74, pB = 0012FF74
Address of ptrn = 0012FF70

16
Pointers Example 2
#include <iostream>
using namespace std;
int main()
{
int i=10;
int *x= &i;
int *y;
//x stores the address of variable i. Pointer assignment could also be done as :
Y=&i;
cout<<“The pointer x is stored at the memory address”<< &x<<“\n”;
cout<<“The pointer x stored the memory address of i :”<<x<<“\n”;
/* contrast the difference between the memory address of the pointer and the
memory address it stores. */.
cout<<“The value of i accessed through pointer x is “<<*x<<“ \n”;
/* Now we manipulate the value of i using pointer x. */
*x= *x+ 1; // increment i by 1.
cout<<“ i (Though pointer) =“<<*x<<“ which equals i ( direct access)” <<i<<“\n”;
// A pointer does not create the copy of the variable it points to.
cout<<“The memory allocated to the pointer x is “<<sizeof(x)<<“Bytes”<<endl;
return 0; 17
}
Example 1
#include<iostream>
using namespace std;
int main ()
{ int y[10]; // y is an array of integer
int *yptr; //yptr is pointer to any integer number
yptr = y; //yptr is pointer to the array y Note there is no & operator before y

cout<<"yptr = "<<yptr<<endl;
yptr++;
cout<<"after increment yptr = "<<yptr<<endl;
return 0 ;
}

The expected output is as below.

yptr = 0×0028fed4
After increment yptr = 0×0028fed8

18
Example : pointer to an array
#include<iostream>
using namespace std;
int main()
{ int y[5]={10,2,6,5,7}; //y is an array of integer
int *ptry = y; //ptry is pointer to array y

cout<<y[3]<<endl;
cout<<*ptry<<endl;
cout<<(*ptry)+3<<endl;
cout<<*(ptry+3)<<endl; //it is equal to y[3]
cout<<ptry[3]<<endl;
//This will display the values of array elements
cout<<ptry[0]<<"\t"<<ptry[1]<<"\t"<<ptry[2]<<"\t"<<ptry[3]<<"\t"<<ptry[4]<<endl;
return 0;
}

19
The output of the program

5
10
13
5
5
10 2 6 5 7

20
PROGRAM Illustrates traversing an array by
pointers
#include<iostream>
using namespace std;

int main()
{int A[5]={10,20,30,40,50};
int *ptrA=A; // defining the pointer to array A
int i ;

for(i=0;i<5;i++) // for loop for output of array The expected output of the program is
cout<<*(ptrA+i)<<"\t";
10 20 30 40 50
//*(ptrA +i) is the value of A[i]element of array
return 0 ;
}

21
Example Pointer Arithmetic

#include<iostream>
using namespace std; The expected output of the program is
int main()
{int x = 10; x = 10
*ptr = 10
int *ptr;
x = 13
ptr = &x; *ptr = 13

cout<<"x = "<<x<<endl;
cout<<"*ptr = "<<*ptr<<endl;
*ptr = *ptr +3 ;
cout<<"x = "<<x<<endl;
cout<<"*ptr = "<<*ptr<<endl;
return 0;
}

22
Arithmetic Operation
#include<iostream>>
using namespace std;
int main()
{
int y[10], *y1,*y2;
y1=&y[0]; // y1 carries the address of first element of array
y2=&y[3]; //y2 carries the address of forth element of array
cout<<y2-y1;
return 0;
}

The expected output of the program is


3

23
PROGRAM – Illustrates pointers to two dimensional
arrays and output of arrays.
#include <iostream>
using namespace std;
int main()
{ int KBS [3][4] = {6,8,5,4, 2,3,7,9, 10,11,12,13};
int(*pKBS )[4] = KBS ; // declaration of pointer to KBS

cout<<**pKBS<<“\t”<<*(*(pKBS)+1)<<“\t”<<*(*(pKBS)+2)<<“\t”<<*(*(pKBS)+3)<<endl;
cout<<*(*(pKBS+1))<<“\t”<<*(*(pKBS+1)+1)<<“\t”<<*(*(pKBS+1)+2)<<“\t”<<*(*(pKBS+1)+3)<<endl;
cout<<*(*(pKBS+2))<<“\t”<<*(*(pKBS+2)+1)<<“\t”<<*(*(pKBS+2)+2)<<“\t”<<*(*( pKBS+2)+3)<<endl;
return 0 ;
}

The expected output is given below.

6 8 5 4
2 3 7 9
10 11 12 13

24
Example Array of Pointers
#include <iostream>
using namespace std;
const int MAX = 3;
int main ()
{
int var[MAX] = {10, 100, 200};
int *ptr[MAX];
for (int i = 0; i < MAX; i++)
{
ptr[i] = &var[i]; // assign the address of integer.
}
for (int i = 0; i < MAX; i++)
{
cout << "Value of var[" << i << "] = "; cout << *ptr[i] << endl;
}
return 0;
} 25
Pointers to characters to store a list of strings
#include <iostream>
using namespace std;
const int MAX = 4;
int main ()
{ // It is an array of pointers of type char
char *names[MAX] = { "Zara Ali", "Hina Ali", "Nuha Ali", "Sara Ali" };
for (int i = 0; i < MAX; i++)
{
cout << "Value of names[" << i << "] = ";
cout << names[i] << endl; //Equivalent to *(names+i)
}
return 0;
}

To declare an array of string :


char *identifier [n]
It is an array of pointers of type char
26
Example
#include<iostream>
#include<cstring>
using namespace std;
struct student
{ char name[64]; // Now we have defined a structure called student
char course[128];
int age; // Now we have to input data.
int year;
};
int main()
{
student s1; // Now, input the values in members of this student structure.

cout<<"The name of the student is"<<strcpy(s1.name, "Ali")<<endl;

cout<<"The Course of the student is"<<strcpy(s1.course,"CS221")<<endl; 27


cout<<"Enter the age of the student"<<endl;
cin>>s1.age;

cout<<"Enter the year of enrollment"<<endl;


cin>>s1.year;

cout<<"The age of the student is "<<s1.age<<endl;


cout<<"The year of the student is "<<s1.year<<endl;

return 0;
}

28
Example2
/* Write a program to accept and print the details of an employee using structure*/
#include <iostream>
using namespace std;
struct emp
{
int eno;
char name[20];
float sal;
};
int main()
{
emp e;

29
do{
cout<<"Enter Employee number :";
cin>>e.eno;
cout<<"Enter Employee name :";
cin>>e.name;
cout<<"Enter Employee salary :";
cin>>e.sal;
cout<<"Employee Details are as follows…."<<endl;
cout<<"Employee Number is-->"<<"\t" <<e.eno<<"\t"<<"The name of the employee
is-->"<<"\t"<<e.name<<"\t"<<"Employee salary is--> "<<"\t"<<e.sal<<endl;

}while(e.sal!=0);

return 0;
}

30
int main()
{
emp e;
cout<<"Enter employee Number : ";
cin>>e.eno ;
cout<<"Enter employee name : ";
cin>>e.name;
cout<< "Enter employee salary : ";
cin>>e.sal;
cout<<"Enter street name :";
cin>>e.addr.street;
cout<<"Enter city name "<<endl;
cin>>e.addr.city;
cout<<"Employee Details are as follows …."<<endl;
cout<<e.eno<<"\t"<<e.name<<"\t"<<e.sal<<"\t"<<e.addr.street<<"\t"<<e.addr.city;

return 0;
}
31
Array of Structures
• We can create an array of structures. The array will have individual structures as its
elements.
Example :
/* Write a program to accept and print the details of an employee by using array of
structures*/

#include<iostream>
using namespace std;
struct emp
{ int eno;
char name[20];
float sal;
};
int main()
{ emp e[5];
int i;

32
for(i=0;i<5;i++)
{
cout<<"Enter employee number : ";cin>>e[i].eno;
cout<<"Enter employee name : ";cin>>e[i].name;
cout<<"Enter employee salary : ";cin>>e[i].sal;
}
cout<<"\nEmployee Details are as follows ..."<<endl;
for(i=0;i<5;i++)
{
cout<<"Employee Number "<<i+1<<endl;
cout<<e[i].eno<<"\t"<<e[i].name<<"\t"<<e[i].sal<<endl;
}
return 0;
}

33
PROGRAM Structures Containing Pointers
#include<iostream>
#include<cstring>
using namespace std;

struct product
{ int reference;
char name[20];
float price;
};
int main()
{ product p1 ={1001, "apple", 5};
product *ptr = &p1;
strcpy(ptr->name,"peach");
ptr ->price = 6.5;

34
cout<<"product p1"<<endl;
cout<<"\t reference = "<<ptr->reference<<endl;
cout<<"\t name = "<<ptr->name<<endl;
cout <<"\t price = "<<ptr->price<<endl;

return 0;
}

The expected output is given below.

35
#include<iostream>
using namespace std;
struct employee
{ int eno;
char name[10];
};
int main()
{ struct employee *emp;
emp = new(employee); /* The operator new allocates memory for the additional
object and returns pointer to it */
cout<<"Enter employee details ..."<<endl;
cout<<"Enter employee number : ";
cin>>emp->eno;
cout<<"Enter employee name : ";
cin>>emp->name;
cout<<"emp->eno = "<<emp->eno<<endl;
cout<<"emp->name = "<<emp->name<<endl;
delete(emp); //free the memory so allocated
return 0 ; }
}
36
Create list
#include <iostream>
using namespace std; cout<<"first node "<< n1.data<<endl;
cout<<"second node "<< n2.data<<endl;
n1.next = &n2;
struct node n2.next = &n3;
{ int data; k = n1.next->data;
node *next; cout<<"Last node "<< n2.next->data;
};
return 0;
}
int main()
{
node n1, n2, n3; The expected output is
int k;
First node 10
n1.data = 10; Second node 20
n2.data = 20; Last node 30
n3.data = 30;

37
Add List
#include<iostream>
using namespace std;
struct node n1.next = &n2;
n2.next = &n3;
{ k = n1.next->data;
int data; cout<<"create list"<< n2.next->data<<endl;
/*Add node at the end of list */
node *next;
n3.next = &n4;
}; cout<<"add of struct node"<< n3.next->data<<endl;
int main()
return 0;
{ }
node n1, n2, n3,n4;
int k;
n1.data = 10;
n2.data = 20;
n3.data = 30;
n4.data =40;
cout<<"first node "<< n1.data<<endl;
cout<<"second node “<< n2.data<<endl;

38
Coding Linked list Implementation
#include<iostream>
using namespace std;
struct node
{ int data ;
node *nextPtr;
};
//The entire linked list is accesses from an external pointer list, that points to the first node in the list
node* insertAtend (node *head, int n)
{ node *temp;
if(head == NULL) //if the exist list is empty then insert a new node as the starting node
{ head = new(node); //creates new node data values passes as parameter
head->data = n;
head->nextPtr = NULL; //makes the pointer pointing to NULL
}

39
else
{ node *q ;
temp = head; //traverse the existing list to get the pointer to the last node of it
while(temp->nextPtr != NULL)
temp = temp->nextPtr;

q = new (node); //creates new node data values passes as parameter


q->data = n;
q->nextPtr= NULL; //makes the pointer pointing to NULL
temp->nextPtr = q;
}
return(head);
};

40
void printlist (node *head) int main()
{ { int nbr,x;
node *temp = head; node *start = NULL;
cout<<"Enter the nodes to be created : ";
cout<<"the data values in the list are :"<<endl; cin>>nbr;
while(nbr>0)
{
if(head == NULL) cout<<"Enter data node : ";
cout<<"The list is empty"; cin>>x;
else start = insertAtend(start,x);
{ do nbr--;
{ cout<<temp->data<<"\t";
}
temp = temp->nextPtr;
} while(temp!= NULL); cout<<"The created list is :"<<endl;
} printlist(start);
};
return 0 ;
}

41
Implementation of Stack
#include <stdio.h>
#define MAX 10 /* The maximum size of the stack */

void push(int stack[], int *top, int value) // put item on top of stack
{
if(*top < MAX )
{
*top = *top + 1; // increment top
stack[*top] = value; // insert item
}
else
cout<<"The stack is full can not push a value\n";

}
42
void pop(int stack[], int *top, int * value) // take item from top of stack
{
if(*top >= 0 )
{
*value = stack[*top]; //access item, decrement top
*top = *top - 1;
}
else
cout<<"The stack is empty can not pop a value\n";
}

int main()
{
int steak [MAX]; //size of stack array
int top = -1; // no items yet
int n, value;
cout<<"Enter the size of steak ";
cin>>n;

43
while (n>0)
{cout<<"Enter the element to be pushed : ";
cin>>value;
push(steak,&top,value); // push items onto stack
n--;
}
while(top != -1)
{
pop(steak,&top,&value) ; // delete item from stack
cout<<"The value poped is : "<<value <<endl;
}
return 0;
}

44
#include<iostream>
using namespace std;
#define MAX 10
void insert (int queue[], int *rear, int value)
{
if(*rear < MAX -1)
{ queue[*rear] = value;
*rear = *rear + 1 ;
}
else
cout<<"The queue is full can not insert a value ";
}
void deleteQ(int queue[], int *front, int rear, int *value)
{
if(*front == rear)
cout <<"The queue is empty can not delete a value"<<endl;
else
{*value = queue[*front];
*front = *front + 1;}
}
45
int main()
{int queue[MAX];
int front,rear,n,value,i;
front = -1;
rear = -1;
cout<<"Enter the size of queue ";
cin>>n;
for(i=0;i<=n;i++)
{
cout<<"Enter the element to be inserted ";
cin>>value;
insert(queue,&rear,value);
}
deleteQ(queue,&front,rear,&value);
cout<<"The value deleted is "<<value;

return 0;
}
46

You might also like