Write a program which defines three functions of C++

Vu Old Solved Programming Based Assignments Codes are Available in this Section.
Post Reply
User avatar
ALI RAZA
★★★★★★★★★★★★★
★★★★★★★★★★★★★
Posts: 177
Joined: Fri Dec 22, 2017 8:10 am
Location: Lahore
Has thanked: 6 times
Been thanked: 7 times
Contact:
Status: Offline

Write a program which defines three functions of C++

Post by ALI RAZA » Thu Dec 13, 2018 7:19 am

Write a program which defines three functions:
• genRandNum()
• findMinNum()
• swapValue()

genRandNum(): This function will generate 5 random numbers in range 1-100 and store these numbers in array and print array on console.

Now start sorting these numbers in ascending order (lower to higher) by following the given steps:
1. findMinNum(): This function will search smallest number in unsorted part of array.
2. If leftmost number is the smallest number in unsorted array then no need to swap it otherwise swap the smallest number with left most unsorted number using swapValue() function. Now this number is fully sorted.

3. Repeat the above 2 steps until the whole array get sorted.
Now display the sorted array as given in the screenshot.

Code: Select all

#include <iostream>
#include <stdlib.h>		/*rand and srand function*/
#include <ctime>		/*time function*/
using namespace std;

const int arraySize = 5;
int array[arraySize];
int minVal=0;
int minValInd=0;

//Random Number Generation Function
void genRandNum(){
	srand(time(NULL));
	for(int i=0; i<arraySize; i++){
		array[i] = (rand()%100)+1;
		cout << array[i]  <<" ";
	}
	cout<< endl;
}

//Finding min value in unsorted array
void findMinNum(int unFirstIndex){
	minVal=array[unFirstIndex];
	for(int i=unFirstIndex; i<arraySize; i++){
		if(minVal>array[i]){
			minVal=array[i];
			minValInd = i;
		}
	}
}

//Swaping min value with leftmost num in unsorted array
void swapValue(int unFirstIndex, int minValInd){
	int temp =array[unFirstIndex];
	array[unFirstIndex] = minVal;
	array[minValInd] = temp;
}

main(){
	
	//Generating random numbers and store in array
	cout<<"\n   Random Numbers are    : ";
	genRandNum();
	
	//Sorting the array using findmin and swaping values in array
	for(int i=0; i<arraySize; i++){
		findMinNum(i); 						
		if(array[i]!=minVal)
			swapValue(i,minValInd);	
	}
	
	//Printing sorted array	
	cout<<"Sorted Random Numbers are: ";
	for(int i=0; i<arraySize; i++)
		cout<<array[i]<<" ";

	cout<<"\n\n";
	system("pause");
}




Post Reply

Last 10 Members Who Visited This Topic

User avatar ALI RAZA (1)

  • Similar Topics
    Replies
    Views
    Last post

Who is online

Users browsing this forum: No registered users and 1 guest