Compare Class Object using bubble sort - c++

Task: Model in OOP a class named Student containing name, surname and the marks from the winter session exams. Display the name of the students who have arrears exams and the first three students in the group.
I have troubles in comparing the marks(first three students).
My code:
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
#include <string>
#include<stdio.h>
class Student {
private:
char nume[10];
char prenume[20];
double matematica;
double fizica;
double programare;
public:
Student(char num[10], char pren[20], double mate, double fiz, double progra);
void afis();
void citire_stud();
int restanta();
double media();
};
Student::Student(char num[10] = "", char pren[20] = "", double mate = 0, double fiz = 0, double progra = 0)
{
strcpy(nume, num);
strcpy(prenume, pren);
matematica = mate;
fizica = fiz;
programare = progra;
}
void Student::afis()
{
cout << "Nume: " << nume << endl;
cout << "Prenume: " << prenume << endl;
cout << "Nota la matematica: " << matematica << endl;
cout << "Nota fizica: " << fizica << endl;
cout << "Nota programare: " << programare << endl;
cout << endl;
}
void Student::citire_stud()
{
char num[10];
char pren[20];
double mate, fiz, progra;
cout << "Introduceti numele studentului: " << endl;
cin >> num;
strcpy(nume, num);
cout << "Introduceti preumele studentului: " << endl;
cin >> pren;
strcpy(prenume, pren);
cout << "Introduceti nota la mate studentului: " << endl;
cin >> mate;
matematica = mate;
cout << "Introduceti nota la fizica studentului: " << endl;
cin >> fiz;
fizica = fiz;
cout << "Introduceti nota la programare studentului: " << endl;
cin >> progra;
programare = progra;
}
int Student::restanta() //arrears
{
if (matematica < 5 || programare <5 || fizica < 5)
return 1;
else return 0;
}
double Student::media()
{
double med;
med = (matematica + fizica + programare) / 3;
return med;
}
void main()
{
int cont = 0;
int res[10];
int nr;
cout << "Cati studenti sunt(max 10): "; //How many students
cin >> nr;
Student ob2[10], temp;
for (int i = 0;i < nr;i++)
{
ob2[i].citire_stud();
if (ob2[i].restanta())
{
res[cont++] = i;
}
}
if (cont == 0)
{
cout << "Nu sunt studenti restanti! " << endl;
goto jmp;
}
else
{
cout << "\nStundetii restanti sunt: " << endl;
int i = 0;
int k = 0;
do
{
k = res[i];
ob2[k].afis();
i++;
} while (i != cont);
}
jmp:
cout << "\n\n\n\nStudentii in ordinea medilor sunt: " << endl;
for (int i = 0;i < nr;i++)
{
if (ob2[i].media() < ob2[i + 1].media()) //Not working
{
temp = ob2[i];
ob2[i] = ob2[i + 1];
ob2[i + 1] = temp;
}
}
for (int i = 0;i < nr;i++)
ob2[i].afis();
system("pause");
}
Output: Output
It should be: 9 - 7 - 5

Your bubble sort is broken. A) You need 2 loops. B) you go out of bounds. Change it to something like:
for (int j = 0; j < nr; j++)
{
for (int i = 0;i < nr - 1 ; i++)
{
if (ob2[i].media() < ob2[i + 1].media())
{
temp = ob2[i];
ob2[i] = ob2[i + 1];
ob2[i + 1] = temp;
}
}
}

Related

c++ when reading from a file i continualy get dirty memory in my array and in my file

we were supposed to create a program that can memorize drugs data for a farmacy we were supposd to make 3 function 1 for searching using the code 2 to show the understock in alphabetical description order and 3 to save and load the memorized data from a file called "dati.txt" but we ran in a dirty data problem the program write dirty data or read dirty data i can't figure out if is the loading or the writing pls help me
ps i'm new to programming and i m still learnign
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
#define Num 300
int n = 0;
FILE* file;
struct s_farmaci {
int codice;
string descrizione;
float prezzo;
int disponibilita;
};
void bubblesort(s_farmaci vet[], int num);
void sottoscorta(s_farmaci vet[], int tanti);
int ricercabin(s_farmaci vet[], int inizio, int fine, int codice);
int menu();
void caricamento(s_farmaci farmaco[]);
void mostrafarmaco(s_farmaci farmaco[], int indice);
void scambia(s_farmaci v[], int i, int j);
void salvahdd(s_farmaci farmaco[]);
void caricahdd(s_farmaci farmaco[]);
int main()
{
s_farmaci farmaco[Num];
int scelta;
int codicericerca;
int trovato = -1;
caricahdd(farmaco);
system("pause");
scelta = menu();
do
{
switch (scelta) {
case 4:
{
cout << "stai per uscire dal programma" << endl;
salvahdd(farmaco);
cout << "dati salvati correttamente correttamente" << endl;
break;
}
case 1:
{
caricamento(farmaco);
break;
}
case 2:
{
bubblesort(farmaco, n);
cout << "quale codice vuoi cercare? ";
cin >> codicericerca;
trovato = ricercabin(farmaco, 0, n - 1, codicericerca);
if (trovato == -1)
cout << "Prodotto non trovato!" << endl;
else {
cout << "prodotto trovato: " << endl;
mostrafarmaco(farmaco, trovato);
}
break;
}
case 3:
{
sottoscorta(farmaco, n);
break;
}
default:
{
cout << " errore scelta non valida riprova " << endl;
break;
}
}
system("pause");
scelta = menu();
} while (scelta != 0);
return 0;
}
//bubblesort of the code
void bubblesort(s_farmaci vet[], int num)
{
int tempcodice;
float tempprezzo;
int tempquantita;
string tempdescrizzione;
bool scambi = false;
do {
scambi = false;
for (int i = 0; i < num - 1; i++) {
if (vet[i].codice > vet[i + 1].codice) {
scambi = true;
tempcodice = vet[i].codice;
vet[i].codice = vet[i + 1].codice;
vet[i + 1].codice = tempcodice;
tempprezzo = vet[i].prezzo;
vet[i].prezzo = vet[i + 1].prezzo;
vet[i + 1].prezzo = tempprezzo;
tempquantita = vet[i].disponibilita;
vet[i].disponibilita = vet[i + 1].disponibilita;
vet[i + 1].disponibilita = tempcodice;
tempdescrizzione = vet[i].descrizione;
vet[i].descrizione = vet[i + 1].descrizione;
vet[i + 1].descrizione = tempdescrizzione;
}
}
} while (scambi == true);
}
//menu
int menu()
{
system("cls");
int scelta;
cout << "-----------------------------" << endl;
cout << "- BENVENUTI -" << endl;
cout << "-----------------------------" << endl;
cout << "- -" << endl;
cout << "- 1 caricamento -" << endl;
cout << "- 2 ricerca -" << endl;
cout << "- 3 mostra -" << endl;
cout << "- 4 salva -" << endl;
cout << "- -" << endl;
cout << "-----------------------------" << endl;
cout << "-- inserici numero: ";
cin >> scelta;
return scelta;
}
//get drugs information
void caricamento(s_farmaci farmaco[]) {
system("cls");
cout << "inserisci il " << n + 1 << " farmaco" << endl;
//inserisco il codice
cout << "insersci il codice: ";
cin >> farmaco[n].codice;
//inserisco la descrizione
cout << "inserisci la descrizione del farmaco: ";
cin.ignore();
getline(cin, farmaco[n].descrizione);
//inserisco il prezzo
cout << "inserici il prezzo: ";
cin >> farmaco[n].prezzo;
//inserico la disponibilita
cout << "inserci quanti farmaci sono disponibili: ";
cin >> farmaco[n].disponibilita;
cout << endl;
n++;
}
/show memorized drugs
void mostrafarmaco(s_farmaci farmaco[], int indice) {
cout << endl;
cout << "codice farmaco :" << farmaco[indice].codice << endl;
cout << "descrizione farmaco :" << farmaco[indice].descrizione << endl;
cout << "prezzo farmaco :" << farmaco[indice].prezzo << endl;
cout << "quantita disponibili :" << farmaco[indice].disponibilita << endl;
}
//binary search
int ricercabin(s_farmaci vet[], int inizio, int fine, int codice) {
int medio;
if (inizio > fine)
return -1;
else {
medio = (inizio + fine) / 2;
if (codice == vet[medio].codice)
return medio;
else
if (codice > vet[medio].codice)
return ricercabin(vet, medio + 1, fine, codice);
else
return ricercabin(vet, inizio, medio - 1, codice);
}
}
//show me understock
void sottoscorta(s_farmaci vet[], int tanti) {
int tempcodice;
float tempprezzo;
int tempquantita;
for (int x = 0; x < tanti; x++) {
//algoritmo di ordinamento
int i, j;
string temp;
//sorting farmacs description
for (j = 0; j < tanti - 1; j++)
for (i = 0; i < tanti - 1; i++)
if (vet[i].descrizione > vet[i+1].descrizione)
scambia(vet, i, i+1);
}
for (int k = 0; k < tanti; k++) {
if (vet[k].disponibilita < 3) {
cout << endl;
cout << " il codice del farmaco e':" << vet[k].codice << endl;
cout << " la descrizione del farmaco e':" << vet[k].descrizione << endl;
cout << " il prezzo del farmaco e':" << vet[k].prezzo << endl;
cout << " la disponibilita' del farmaco e':" << vet[k].disponibilita << endl;
}
}
}
//exchange variables
void scambia(s_farmaci v[], int i, int j) {
s_farmaci temp;
temp = v[i];
v[i] = v[j];
v[j] = temp;
}
//get file from hdd
void caricahdd(s_farmaci farmaco[]) {
n = 0;
if ((file = fopen("dati.txt", "rb")) == NULL)
cout << "errore apertura file" << endl;
else {
while (!feof(file)) {
fread(&farmaco[n], sizeof(s_farmaci), 1, file);
n++;
}
fclose(file);
cout << "dati caricati correttamente" << endl;
}
}
//save file on hdd
void salvahdd(s_farmaci farmaco[]) {
if ((file = fopen("dati.txt", "wb")) == NULL)
cout << "errore apertura file" << endl;
else {
for (int i = 0; i <= n; i++) {
fwrite(&farmaco[i], sizeof(s_farmaci), 1, file);
}
fclose(file);
}
}
You say read-file get dirty data in array;
But it's not dirty data
fread(&farmaco[n], sizeof(s_farmaci), 1, file);
It only means that, read some data and put in the address(&farmaco[n]).But C++ don't know how to correctly set the data for the member of the array.
For Example:
/*this is the data file*/
19 /*set age value*/
Hello /*set name value*/
20 /*set age value*/
Exam /*set name value*/
And a struct has two members
struct people
{
int age;
string name;
}
The array people[2],this is how to read data and set value
/*read the first data and set people[0].age*/
people[0].age = 19
/*read the second data and set people[0].name*/
people[0].name= Hello
/*read the third data and set people[1].age*/
people[1].age = 19
/*read the fourth data and set people[1].name*/
people[1].name= Hello
/*and so on*/

C++ My files were working before I attempted to move them into a source file, and now there are no errors and nothing being displayed

My apologies for being a little vague about the issue(s) in the topic, but I really am not sure. I am attempting to create a course_directory as a lab project for school, and up until now everything had been progressing quite well. I have written and tested each of the function in the main.cpp before attempting to move the class functions into the .hpp file. My goal is to have nothing in main except for a call to "Run" that will open a file, and in turn make a call to "displayMenu", and allow the user to interact with the information as they choose, but now everything is compiling correctly, and nothing is being displayed.
Course_directory.hpp
#include "Course_Directory.h"
using namespace std;
Course_Directory::Course_Directory(){};
Course_Directory courses[1001];
void Course_Directory::displayMenu(){
cout << "1.Print all courses" << endl;
cout << "2.Print all courses for a department" << endl;
cout << "3.Print roster for a course" << endl;
cout << "4.Print the largest class" << endl;
cout << "5.Swap two classes" << endl;
cout << "6.Print schedule for a student" << endl;
cout << "7.Exit" << endl;
char dept[50], dept2[50];
int courseNo, courseNo2, i, choice;
while (choice != 7) {
cout << "\nEnter your choice: ";
cin >> choice;
if (choice == 1)
printAllCourses(i);
else if (choice == 2) {
cout << "\nEnter department name:";
cin >> dept;
for(int j = 0; j < sizeof(dept); j++)
{
dept[j] = (toupper(dept[j]));
}
coursesInDept(dept, i);
}
else if (choice == 3) {
cout << "\nEnter course number:";
cin >> courseNo;
studentsInCourse(courseNo, i);
}
else if (choice == 4) {
largestClass(i);
}
else if (choice == 5) {
cout << "\nEnter first department name :";
cin >> dept;
for(int j = 0; j < sizeof(dept); j++)
{
dept[j] = (toupper(dept[j]));
}
cout << "\nEnter first course number: ";
cin >> courseNo;
cout << "\nEnter second department name :";
cin >> dept2;
for(int k = 0; k < sizeof(dept2); k++)
{
dept2[k] = (toupper(dept2[k]));
}
cout << "\nEnter second course number: ";
cin >> courseNo2;
swap2(dept, courseNo, dept2, courseNo2, i);
}
else if (choice == 6) {
int id;
cout << "\nEnter a student Id:";
cin >> id;
schedule(id, i);
}
}
cout << "Goodbye!\n";
}
void Course_Directory::printAllCourses(int len){
for (int i = 0; i < len; i++)
cout << "Course name: " << courses[i].courseName << ", Course
number: " << courses[i].courseNum << endl;
cout << len;
}
void Course_Directory::coursesInDept(char *dept, int len) {
for (int i = 0; i < len; i++)
if (strcmp(dept, courses[i].courseName) == 0)
cout << "Course Name: " << courses[i].courseName << ",
Course number: " << courses[i].courseNum << endl;
}
void Course_Directory::studentsInCourse(int courseNo, int len) {
for (int i = 0; i < len; i++)
if (courseNo == courses[i].courseNum) {
for (int m = 0; m < courses[i].numStudents - 1; m++)
cout << courses[i].IDs[m] << ",";
cout << courses[i].IDs[courses[i].numStudents - 1] <<
endl;
}
}
void Course_Directory::largestClass(int len) {
int max = -999;
for (int i = 0; i < len; i++) {
if (courses[i].numStudents > max)
max = courses[i].numStudents;
}
for (int i = 0; i < len; i++) {
if (courses[i].numStudents == max){
cout << "\nThe largest class is in department: " <<
courses[i].courseName
<< ", and the course number is: " << courses[i].courseNum
<< "\n";
cout << "The class currently has " << max << " students
enrolled.\n";
}
}
}
void Course_Directory::swap2(char *firstDep, int firstNo, char
*secondDep, int secondNo, int len) {
Course_Directory temp;
int firstIndex, secondIndex;
for (int i = 0; i < len; i++) {
if (strcmp(firstDep, courses[i].courseName) == 0 &&
courses[i].courseNum == firstNo)
firstIndex = i;
if (strcmp(secondDep, courses[i].courseName) == 0 &&
courses[i].courseNum == secondNo)
secondIndex = i;
}
temp = courses[firstIndex];
courses[firstIndex] = courses[secondIndex];
courses[secondIndex] = temp;
}
void Course_Directory::schedule(int id, int len) {
cout << "Courses student " << id << " is enrolled in: " << endl;
for (int i = 0; i < len; i++) {
for (int j = 0; j < courses[i].numStudents; j++)
if (courses[i].IDs[j] == id)
cout << courses[i].courseNum << " \n";
}
}
Course_Directory.h
#ifndef COURSE_DIRECTORY_H
#define COURSE_DIRECTORY_H
#include <iostream>
using namespace std;
class Course_Directory{
private:
int* deptSize;
string filename;
public:
char courseName[1001];
int courseNum;
int numStudents;
int IDs[1001];
int* choice;
void displayMenu();
Course_Directory();
//Course_Directory(const Course_Directory& original);
//~Course_Directory();
//void run(string);
void coursesInDept(char*, int);
void studentsInCourse(int, int);
void largestClass(int);
void swap2(char*, int, char*, int, int);
void schedule(int, int);
void printAllCourses(int);
};
#include "Course_Directory.hpp"
#endif //COURSE_DIRECTORY_H
main.cpp
#include "Course_Directory.h"
using namespace std;
class Course_Directory;
int main() {
ifstream file;
file.open("input.txt");
char *token;
int i = 0, j;
Course_Directory courses[100];
if (!file.fail()) {
std::string line;
while (getline(file, line)) {
j = 0;
char *str = const_cast<char *>(line.c_str());
token = strtok(str, " ");
while (token != NULL)
{
if (j == 0)
strcpy(courses[i].courseName, token);
else if (j == 1)
courses[i].courseNum = atoi(token);
else if (j == 2)
courses[i].numStudents = atoi(token);
else
courses[i].IDs[j - 3] = atoi(token);
j++;
token = strtok(NULL, " ");
cout << courses[i].courseName << endl;
}
i++;
}
file.close();
}
else{
cout << "File not found." << endl;
}
//menu
Course_Directory displayMenu();
return 0;
}
If I leave Course_Directory off of displayMenu(); then I get "displayMenu" was not declared in this scope. I'm not sure what the problem is or why the menu will not display. Any help would be greatly appreciated!

C++ Two dimensional array multiplication table

I am using C++ and want to do a 2-dimensional array. 10 rows and 3 columns. First column is(1 through 10). For Second column, user enters his/her choice of a number from (1-10) resulting in a times table displaying the results as follows: In this example the user's choice is '4':
1x4=4
2x4=8
3x4=12
4x4=16
5x4=20
6x4=24
7x4=28
8x4=32
9x4=36
10x4=40
I can't get the user's input to calculate correctly when using the for loop.
Well you can try this to get that output
#include<iostream>
using namespace std;
int main()
{
int n; //To take input
int table[10][3]; // Table
cout << "Input a number: ";
cin >> n;
// Generating Output
for (int i = 0; i < 10; i++)
{
table[i][0] = i + 1;
table[i][1] = n;
table[i][2] = table[i][0] * table[i][1];
}
for (int i = 0; i < 10; i++)
{
cout << table[i][0] << " * " << table[i][1] << " = " << table[i][2]<<endl;
}
return 0;
}
Output
SOLVED: Everything seems to be working now!! Here's the code:
#include <iostream>
#include<cstdlib>
#include<iomanip>
#include <ctime>
using namespace std;
void displayTable(int table[10][3]);
bool testMe(int testTable[10][3]);
void createTables(int testTable[10][3], int ansTable[10][3], int
usersChoice);
bool AllAnswersAreTested(bool tested[10]);
void gradeMe(int testTable[10][3], int ansTable[10][3]);
void displayMenu();
int main()
{
srand(time(NULL));
int userInput = 0;
int tableChoice = 0;
int myTable[10][3] = {0};
int testTable[10][3];
int ansTable[10][3];
bool tested = false;
do
{
displayMenu(); //Display the menu of choices
cin >> userInput;
cout << endl;
switch (userInput) //Validate menu choices 1-4
{
case 1: //Display a users choice of table
displayTable(myTable);
break;
case 2: //Test user on users choice of table
cout << "What times table test would you like to take? > ";
cin >> tableChoice;
createTables(testTable, ansTable, tableChoice);
tested = testMe(testTable);
if (tested)
{
gradeMe(testTable, ansTable);
}
break;
case 3: //Display a new table of the users choice
displayTable(myTable);
break;
case 4: //Quit program menu option
cout << "Program ending.\n";
return 0;
default: //Invalid entry
cout << "You entered an invalid item number. Please enter a number from 1 to 4.\n";
cout << endl;
}
} while (userInput != 4);
return 0;
}
void displayTable(int myTable[10][3])
{
int num; //initialize local variables
//Ask the user what times table they would like to review
cout << "What times table would you like to review?" << endl;;
cout << "Please enter a value from 1 to 12 > \n";
cout << "\n";
cin >> num;
cout << endl;
for (int i = 0; i < 10; i++)
{
myTable[i][0] = i + 1;
myTable[i][1] = num;
myTable[i][2] = myTable[i][0] * myTable[i][1];
}
for (int i = 0; i < 10; i++)
{
cout << setw(3)<< myTable[i][0] << " * " << myTable[i][1] << " = " << myTable[i][2] << endl;
}
cout << endl;
}
void createTables(int testTable[10][3], int ansTable[10][3], int usersChoice)
{
for (int i = 0; i < 10; i++)
{
testTable[i][0] = i + 1;
testTable[i][1] = usersChoice;
testTable[i][2] = 0;
ansTable[i][0] = i + 1;
ansTable[i][1] = usersChoice;
ansTable[i][2] = usersChoice * (i + 1);
}
}
bool testMe(int testTable[10][3])
{
bool tested[10] = { false, false, false, false, false,false, false, false, false, false };
while (!AllAnswersAreTested(tested))
{
int index = rand() % 10;
if (tested[index] == false)
{
int randomNum = testTable[index][0];
int tableChoice = testTable[index][1];
int answer;
cout << "What is " << randomNum << " X " << tableChoice << " = ";
cin >> answer;
testTable[index][2] = answer;
tested[index] = true;
}
}
return true;
}
bool AllAnswersAreTested(bool tested[10])
{
for (int i = 0; i < 10; i++)
{
if (tested[i] == false)
{
return false;
}
}
return true;
}
void gradeMe(int testTable[10][3], int ansTable[10][3])
{
int correctAnswers = 0;
for (int i = 0; i<10; i++)
{
if (testTable[i][2] == ansTable[i][2])
{
correctAnswers++;
}
}
int score = (correctAnswers * 10);
if (score == 100)
{
cout << "You passed the test! PERFECT SCORE!!" << endl;
cout << endl;
}
else if (score >= 70)
{
cout << "You passed the test. Your Score is: ";
cout << score;
cout << endl;
}
else if (score < 70)
{
cout << "You did not pass the test. Your Score is: ";
cout << score;
cout << endl;
}
}
//Display the menu function
void displayMenu()
{
cout << " Multiplication Tables" << endl;
cout << endl;
cout << " 1. Review MyTable" << endl;
cout << " 2. Test Me" << endl;
cout << " 3. Enter a New Multiplication Table (1-12)";
cout << " 4. Quit" << endl;
cout << " Enter a Menu Item > ";
}
#include <iostream>
using namespace std;
int main()
{
int a[100][100];
for(int i=1;i<10;i++){
for(int j=1;j<10;j++){
a[i][j] = (i)*(j);
cout<<a[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
There is how the output looks like:

How to do selection sort?

Count all the records from the file "8.dat". To read each individual recording perform dynamic memory capture.
Sort the records to different keys:
Item number (ascending);
The cost (descending);
Number of stock (descending).
Use selection sort
Total sorting will be done 12 times, each time the array is sorted in its original condition.
For each case count of comparisons to and permutations.
Below code implements insertion sort. Twice, without saying so much.
I need to use selection sort. How to do selection sort?
#include <iostream>
#include <fstream>
#include <conio.h>
using namespace std;
struct PRICE
{
int number;
char name[20];
int cost;
int quantity;
} *pm;
int Menu();
void PrintPRICE(PRICE);
void sort_cost(PRICE*, int);
void sort_quantity(PRICE*, int);
long file_size(const char*);
int main()
{
int count = 0;
const char *fname = "D:\8.dat";
FILE* file = fopen(fname, "r");
if (file != NULL)
{
long size = file_size(fname);
count = size / sizeof PRICE;
pm = new PRICE[count];
fread(pm, sizeof PRICE, count, file);
fclose(file);
}
for (int i=0; i<count; i++)
{
PrintPRICE(pm[i]);
cout << endl;
}
int ch = Menu();
switch (ch)
{
case 1:
{
sort_cost(pm, count);
cout << endl;
cout << " Result: " << endl;
cout << "-----------------------" << endl;
for (int i=0; i<count; i++)
{
PrintPRICE(pm[i]);
cout << endl;
}
break;
}
case 2:
{
sort_quantity(pm, count);
cout << " Result: " << endl;
cout << "-----------------------" << endl;
for (int i=0; i<count; i++)
{
PrintPRICE(pm[i]);
cout << endl;
}
break;
}
default: break;
}
delete [] pm;
_getch();
}
void PrintPRICE(PRICE price)
{
cout << " Product: " << price.name << endl;
cout << " Number of orden: " << price.number << endl;
cout << " Product cost: " << price.cost << endl;
cout << " Quantity in stock: " << price.quantity << endl;
cout << "-----------------------------------n" << endl;
}
long file_size(const char* filename)
{
FILE *Pfile = NULL;
Pfile = fopen(filename, "rb");
fseek(Pfile, 0, SEEK_END);
long size = ftell(Pfile);
fclose(Pfile);
return size;
}
void sort_cost(PRICE* array, int count)
{
int change = 0;
int comparesion = 0;
for (int i=1; i<count; i++)
{
PRICE key = array[i];
int j = i - 1;
comparesion++;
while (i>=0 && array[i].cost>key.cost)
{
array[j + 1] = array[j];
j = j - 1;
change++;
}
array[j + 1] = key;
}
cout << "n Quantity change: " << change << endl;
cout << " Quantity comparesion: " << comparesion << endl;
}
void sort_quantity(PRICE* array, int count)
{
int change = 0;
int comparesion = 0;
for (int i=1; i<count; i++)
{
PRICE key = array[i];
int j = i - 1;
comparesion++;
while (j>=0 && array[i].quantity>key.quantity)
{
array[j + 1] = array[j];
j = j - 1;
change++;
}
array[j + 1] = array[j];
}
cout << "n Quantity change: " << change << endl;
cout << " Quantity comparesion: " << comparesion << endl;
}
int Menu()
{
int n;
cout << " 1 - Sort by cost" << endl;
cout << " 2 - Sort by quantity" << endl;
cout << "n Your choice: "; cin >> n;
return n;
}
source code for the selection sort
void selectSort(int arr[], int n)
{
int pos_min,temp;
for (int i=0; i < n-1; i++)
{
pos_min = i;
for (int j=i+1; j < n; j++)
{
if (arr[j] < arr[pos_min])
pos_min=j;
}
if (pos_min != i)
{
temp = arr[i];
arr[i] = arr[pos_min];
arr[pos_min] = temp;
}
}
}

Can't find a solution to a c++ program [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
So I have to write a code for the following program:
Write a program with a main function and menu for choosing a function to:
a) input data for students into an array (faculty number, age, sex) (up to 25)
b) rewrite the data for the male and female students into two new arrays and output the arrays and the average age
c) output the youngest student and make the arrays into ascending order of the age and output the arrays
d) search for a student by a faculty number and output his information
Ok, so far so good. The a) and d) are working as they should, but b) and c) are giving me some trouble. On c) it says the youngest student is -88758375 year-old and it isn't outputting the arrays. And on b) it gives me a logical error and it says Integer division by zero and crashes the program. I really tried to find any mistakes but I'm stuck, so I ask you for some help:)))
#include "stdafx.h"
#include <iostream>
using namespace std;
const int N = 25;
struct student
{
int fN;
int age;
char sex;
};
// a)
void input(student fN[N], int numberOfStudents)
{
for (int i = 0; i<numberOfStudents; i++)
{
cout << "Faculty number: ";
cin >> fN[i].fN;
cout << "Age: ";
cin >> fN[i].age;
cout << "Sex: ";
cin >> fN[i].sex;
cout << endl;
}
}
// b)
void rearrange(student fN[N], student fNm[N], student fNf[N], int numberOfStudents, int m, int f)
{
int avgAgeM = 0, avgAgeF = 0;
for (int i = 0; i < numberOfStudents; i++)
{
if (fN[i].sex == 'm')
{
fNm[m].fN = fN[i].fN;
fNm[m].age = fN[i].age;
fNm[m].sex = fN[i].sex;
m++;
avgAgeM = avgAgeM + fN[i].age;
}
else if (fN[i].sex == 'f')
{
fNf[f].fN = fN[i].fN;
fNf[f].age = fN[i].age;
fNf[f].sex = fN[i].sex;
f++;
avgAgeF = avgAgeF + fN[i].age;
}
cout << endl;
for (int i = 0; i < m; i++)
{
cout << "\tFaculty number: " << fNm[i].fN << "\tAge: " << fNm[i].age << "\tSex: " << fNm[i].sex << endl;
}
cout << "Average male age: " << avgAgeM / m << "\n\n";
for (int i = 0; i<f; i++)
{
cout << "\tFaculty number: " << fNf[i].fN << "\tAge: " << fNf[i].age << "\tSex: " << fNf[i].sex << endl;
}
cout << "Average female age: " << avgAgeF / f << "\n\n";
}
}
// c)
void ascendingAge(student fNm[N], student fNf[N], int m, int f)
{
int x, y;
char z;
for (int i = 0; i < m-1; i++)
for (int j = 0; j < m-i-1; j++)
{
if (fNm[j].age > fNm[j + 1].age)
{
x = fNm[j].age;
y = fNm[j].fN;
z = fNm[j].sex;
fNm[j + 1].age = fNm[j].age;
fNm[j].age = x;
fNm[j + 1].fN = fNm[j].fN;
fNm[j].fN = y;
fNm[j + 1].sex = fNm[j].sex;
fNm[j].sex = z;
}
}
for (int i = 0; i < f-1; i++)
for (int j = 0; j < f-i-1; j++)
{
if (fNf[j].age > fNf[j + 1].age)
{
x = fNf[j].age;
y = fNf[j].fN;
z = fNf[j].sex;
fNf[j + 1].age = fNf[j].age;
fNf[j].age = x;
fNf[j + 1].fN = fNf[j].fN;
fNf[j].fN = y;
fNf[j + 1].sex = fNf[j].sex;
fNf[j].sex = z;
}
}
cout << "The youngest female student is " << fNf[0].age << " year-old." << endl;
for (int i = 0; i < m; i++)
cout << "\tFaculty number: " << fNm[i].fN << "\tAge: " << fNm[i].age << "\tSex: " << fNm[i].sex << endl;
for (int i = 0; i<f; i++)
cout << "\tFaculty number: " << fNf[i].fN << "\tAge: " << fNf[i].age << "\tSex: " << fNf[i].sex << endl;
cout << endl;
}
//d
void searchStudent(student fN[N], int numberOfStudents)
{
int x, index;
bool yes = false;
cout << "Enter a faculty number: ";
cin >> x;
for (int i = 0; i < numberOfStudents; i++)
if (fN[i].fN == x)
{
yes = true;
index = i;
}
cout << endl;
if (yes == true)
cout << "\tFaculty number: " << fN[index].fN << "\tAge: " << fN[index].age << "\tSex: " << fN[index].sex << endl;
else
cout << "No such faculty number.\n\n";
}
int main()
{
student fN[N], fNm[N], fNf[N];
int numberOfStudents, m = 0, f = 0;
char check;
cout << "Enter number of students: ";
cin >> numberOfStudents;
BACK:
cout << "\n\n";
cout << "\t a) \n\t b) \n\t c) \n\t d)\n Press'q' to exit.\n\n";
cin >> check;
switch (check)
{
case 'a':
input(fN, numberOfStudents);
goto BACK;
break;
case 'b':
rearrange(fN, fNm, fNf, numberOfStudents, m, f);
goto BACK;
break;
case 'c':
ascendingAge(fNm, fNf, m, f);
goto BACK;
break;
case 'd':
searchStudent(fN, numberOfStudents);
goto BACK;
break;
case 'q':
return 0;
break;
default:
cout << "Wrong input.\n";
goto BACK;
}
system("pause");
return 0;
}
In the function rearrange you need pass m and k by reference:
void rearrange(student fN[N], student fNm[N], student fNf[N], int numberOfStudents, int& m, int& f):
Оr they will not be changed
You seem to want m and f to be outputs from this function
void rearrange(student fN[N], student fNm[N], student fNf[N], int numberOfStudents, int m, int f)
but that would work only if passed by reference:
void rearrange(student fN[N], student fNm[N], student fNf[N], int numberOfStudents, int& m, int& f)
You should guard against divide by zero by testing. Instead of:
cout << "Average male age: " << avgAgeM / m << "\n\n";
use
if (m)
cout << "Average male age: " << avgAgeM / m << "\n\n";
else
cout << "There are zero males\n\n";
and similarly for f