In: Computer Science
How do you translate this pseudocode go regular code in C++
int iMin = 0,i = 0;
for(j = 0; j < n - 1; j++)
int iMin = j;
for(i = j + 1; i < n; i++)
if(a[i] < a[iMin])
iMin = i;
if(iMin != j)
swap(a[i], a[iMin]);
Here is the code with the proper comments:
Code:
//importing the necessary packages needed for the code
#include<bits/stdc++.h>
using namespace std;
void swap(int& x, int& y) // Function to swap the
values, which is passed by reference
{
int z = x;
x = y;
y = z;
}
int main()
{
int iMin = 0,i = 0, j=0, n=0; //variable declaration
cin>> n; // taking the size of the array
from the user
int a[n]; //declaration of the array
for (int k=0;k<n;k++) // taking the array
values from the user and display it on screen
{
int x=0;
cin>>x;
a[k] = x;
cout<<a[k]<<" ";
}
cout<<"\n"; // leaving the space for showing the
better output
for(j = 0; j < n - 1; j++) // Starting of your
Pseudocode arrange the for loops through the brackets
{
int iMin = j;
for(i = j + 1; i < n; i++)
{
if(a[i] < a[iMin])
iMin = i;
if(iMin != j)
swap(a[i], a[iMin]); // calling of the function
}
}
for (int k=0;k<n;k++) // printing the final array to
see the manipulation made by the program.
{
cout<<a[k]<<" ";
}
}
Output:
Input from the user, the user needed to enter the array size and array elements values.
5
9 4 5 7 2
code output for the above inputs:
9 7 5 4 2
Please see the indentation while pasting this code at your own end:
Screenshot of the running code Input and output just for the reference.
Inputs:
The functionality of the code might be converting the middle elements of the array in the descending order. But this code produces the same output as a logic shared in the form of pseudocode.