Computer Programming: CSC-113 Instructor:Mahwish
Computer Programming: CSC-113 Instructor:Mahwish
CSC-113
Instructor:Mahwish
Scenario
Write a C++ program that takes 5 numbers from a user and displays their sum.
Write a C++ program that takes 5 numbers from the user and displays the sum
of their squares.
Write a C++ program that copies the contents of one array into another.
Searching An Array
Sequential / Linear Search
Examples
Write a C++ program that displays the minimum number entered in the array.
Write a C++ program that displays the maximum number entered in the array.
Sorting An Array
Bubble Sort
#include<iostream>
using namespace std;
int main(){ //declaring array
int array[5];
cout<<"Enter 5 numbers randomly : "<<endl;
for(int i=0; i<5; i++)
{
//Taking input in array
cin>>array[i];
}
cout<<endl;
cout<<"Input array is: "<<endl;
for(int j=0; j<5; j++)
{
//Displaying Array
cout<<"\t\t\tValue at "<<j<<" Index: "<<array[j]<<endl;
}
cout<<endl;
// Bubble Sort Starts Here
int temp;
for(int i2=0; i2<=4; i2++)
{
for(int j=0; j<4; j++)
{
//Swapping element in if statement
if(array[j]>array[j+1])
{
temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}
}
// Displaying Sorted array
cout<<" Sorted Array is: "<<endl;
for(int i3=0; i3<5; i3++)
{
cout<<"\t\t\tValue at "<<i3<<" Index: "<<array[i3]<<endl;
}
return 0;}
Binary Search
#include<iostream.h>
#include<conio.h>
void main()
{ const int n=100;
int arr[n],beg,mid,end,i,num;
cout << "\n Enter the values in sorted order (asc or desc) \n";
for(i = 0; i < n; i++)
{ cin >> arr[i]; } /* Initialize beg and end value. */
beg = 0;
end = n-1;
cout << "\n Enter a value to be searched in an array ";
cin >> num;
/* Run loop, while beg is less than end. */
while( beg <= end)
{ /* Calculate mid. */
mid = (beg+end)/2;
/* If value is found at mid index, the print the position and exit. */
if(arr[mid] == num)
{
cout << "\nItem found at position "<< (mid+1); exit(0);
}
else if(num > arr[mid])
{ beg=mid+1; }
else if (num < arr[mid])
{ end=mid-1; }
}
cout << "Number does not found."; }