In: Computer Science
1.
Write a function named “Number” that reads in a list of numbers until the user enters 0. It will return true if the user has entered more even numbers than odd numbers; otherwise it returns false.
2.
Write a code segment to sort an array of students in ascending order of their IDs. Assume the array has been filled with names and assume the following declaration:
struct Student {
string name;
int ID;
}
Student roster[30];
// Code to fill in the student info for all students.
// Sort the roster
// your code goes here
1.
Source Code:
Output:
Code in text format (See above images of code for indentation):
#include<iostream>
#include<iomanip>
using namespace std;
/*main function*/
int main()
{
/*function prototype*/
bool Number();
bool result;
/*function call*/
result=Number();
/*print results*/
if(result)
cout<<"You entered more even
numbers than odd numbers";
else
cout<<"You entered more odd
numbers than even numbers";
return 0;
}
/*function prototype*/
bool Number()
{
/*variables*/
int n,even=0,odd=0;
cout<<"Enter a number or 0 to
exit:"<<endl;
while(true)
{
/*read number from user*/
cin>>n;
/*if 0 then break*/
if(n==0)
break;
/*check for even or odd*/
if(n%2==0)
even++;
else
odd++;
}
/*return true or false based on condition*/
if(even>odd)
return true;
else
return false;
}
2.
Source Code:
Output:
Code in text format (See above images of code for indentation):
#include<iostream>
#include<iomanip>
using namespace std;
/*structure declaration*/
struct Student
{
/*members*/
string name;
int ID;
};
/*array of structures*/
Student roster[30];
/*main function*/
int main()
{
/*variables*/
int n,i,j;
/*read number of students from the user*/
cout<<"Enter number of students: ";
cin>>n;
/*read students data*/
for(i=0;i<n;i++)
{
/*read student ID*/
cout<<"Enter student
"<<i+1<<" ID:";
cin>>roster[i].ID;
cin.get();
/*read student Name*/
cout<<"Enter student
"<<i+1<<" Name: ";
getline(cin,roster[i].name);
}
/*sort the roster array*/
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(roster[j].ID>roster[j+1].ID)
{
/*swapping of ID's*/
int temp=roster[j].ID;
roster[j].ID=roster[j+1].ID;
roster[j+1].ID=temp;
/*swapping of Names*/
string sn=roster[j].name;
roster[j].name=roster[j+1].name;
roster[j+1].name=sn;
}
}
/*print id and names*/
cout<<"ID\tName"<<endl;
cout<<"-----------------------------"<<endl;
for(i=0;i<n;i++)
{
cout<<roster[i].ID<<"\t"<<roster[i].name<<endl;
}
}
return 0;
}