Using C++ The main purpose of this lab is to create functions using call-by-valu
ID: 3585064 • Letter: U
Question
Using C++
The main purpose of this lab is to create functions using call-by-value and call- by-reference parameters.
Activity #1
The first activity will be to write a function that sort an array of numbers (passed as a parameter) in ascending order. The input and output for the program are as follows:
Input/Output:
Enter 5 integers: 1 23 4 54 3
The array of integers sorted in ascending order is: 1 3 4 23 54
Include a function swapper(int& a, int& b) that can be used in your sort function. Save the source code in a file named assignment1.cpp.
Activity #2
Once you have completed the first activity, you should modify the program created in Activity #1 to take randomly generated input instead of command-line input. Save the source code in a file named assignment2.cpp.
Use the “time” command to detect how long it takes to sort 1000 numbers and 10,000 numbers. Include the time result as a comment in your program
Explanation / Answer
#include<iostream>
using namespace std;
// function that swaps 2 numbesr
void swapper(int& a, int& b)
{
int temp = a;
a = b;
b = temp;
}
main()
{
// declaring variables
int fiveInts[5], i, j;
int n = 5;
// taking user input
cout<<"Enter 5 integers: ";
for(i=0; i<n; i++)
{
cin>>fiveInts[i];
}
// Bubble sort technique to sort elements
for(i=0; i<(n-1); i++)
{
for(j=0; j<(n-i-1); j++)
{
if(fiveInts[j]>fiveInts[j+1])
{
swapper(fiveInts[j],fiveInts[j+1]);
}
}
}
// printing output
cout<<endl<<"The array of integers sorted in ascending order is: ";
for(i=0; i<n; i++)
{
cout<<fiveInts[i]<<" ";
}
}
SAMPLE OUTPUT
#include<iostream>
using namespace std;
// function that swaps 2 numbesr
void swapper(int& a, int& b)
{
int temp = a;
a = b;
b = temp;
}
main()
{
// declaring variables
int fiveInts[5], i, j;
int n = 5;
// taking user input
cout<<"Enter 5 integers: ";
for(i=0; i<n; i++)
{
cin>>fiveInts[i];
}
// Bubble sort technique to sort elements
for(i=0; i<(n-1); i++)
{
for(j=0; j<(n-i-1); j++)
{
if(fiveInts[j]>fiveInts[j+1])
{
swapper(fiveInts[j],fiveInts[j+1]);
}
}
}
// printing output
cout<<endl<<"The array of integers sorted in ascending order is: ";
for(i=0; i<n; i++)
{
cout<<fiveInts[i]<<" ";
}
}
SAMPLE OUTPUT
Enter 5 integers: 4 5 6 3 2 The array of integers sorted in ascending order is: 2 3 4 5 6
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.