Explain Arrays Please

Pages: 1... 34567... 9
it shouldnt matter if it is a while loop or a for loop. that just means you didnt write it correctly
Changed it to this, Cmd doesnt get angry but it still stuck in that part of the program.

1
2
3
4
5
6
7
8
9
10
11
12
13
void printArray(int numStudents, float *data)
{
	int x;
	cout << "\nNumber of hours each student spent on Facebook / Twitter in ascending order : " << endl;

	while (x > numStudents)
	{
		for (x = 0; x < numStudents; x++)
		{
			cout << data[x] << "  ";
		}
	}
}


Edit: could it get stuck in on of the other function i call after this that never display anything?
Last edited on
no... youre just not writing this code correctly. x isnt initialized. you made the condition backwards for some reason. you used a nested for loop for idk why
yes x is initialized int x; and if i reverse it so while ( numStudents > x) it can never even progress to the for loop, because x doesn't have a value until that for loop.
Example of initialization:
 
int x = 0;

Attempting to use uninitialized variables such as in line 6 is unpredictable unless your compiler is set up to automatically initialize everything to 0. This unpredictability is especially true when using floating point numbers.

...because x doesn't have a value until that for loop.

So what is the point of the while loop?

Keep it simple.
1
2
3
4
5
void printArray(int num, float* data){
    cout << "\nNumber of hours each student spent on Facebook / Twitter in ascending order : " << endl;
    for(int i(0); i < num; ++i)
        cout << data[i] << "   ";
}
Last edited on
okay, that makes since, and it looks like its working but the program is still gething stuck somewhere after this.


C:\C++\Program Three>g++ main3.cpp -o a.exe

C:\C++\Program Three>a
How many students were surveyed? 3

Enter the number of hours each student spent on Facebook and/or Twitter.
Student 1: 12
Student 2: 13
Student 3: 14

Number of hours each student spent on Facebook / Twitter in ascending order :
12 13 14

it wont progress past this point.
Can you post your main function and point to the line the program appears to freeze at?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
#include <iostream>
#include <iomanip>

using namespace std;

float* makeArray(int);
void getFBTData(float* , int);
void selectionSort(float*, int);
void printArray(int, float*);
float getAverage(float *, int);
int getMode(float*, int);
double getMedian(float*, int);

int main()
{
	float *studentData;
	int numStudents;
	int mode;
	float average, median;



	cout << "How many students were surveyed? ";
	cin >> numStudents;
	cout << endl;

	studentData = makeArray(numStudents);

	 if (studentData == 0)
		 cout << "Error allocating memory.";
	 else
	 {
		getFBTData(studentData, numStudents);
		selectionSort(studentData, numStudents);
		printArray(numStudents, studentData); // here is where its not progressing should go on to calculate the average, median, and mode then display those underneath.

// EDIT: i added a random cout here just to test it and when i did the program completed kind of.
	}
		getAverage(studentData, numStudents);
		getMedian(studentData, numStudents);
		getMode(studentData, numStudents);

		average = getAverage(studentData, numStudents);
		median = getMedian(studentData, numStudents);
		mode = getMode(studentData, numStudents);

		cout << "STATISTICS FOR TIME SPENT ON FACEBOOK & TWITTER" << endl;
		cout << "\n  Mean: " << average;
		cout << "\n  Median: " << median;
		cout << "\n  Mode: " << mode; 
	return 0;
}


float* makeArray(int numStudents)
{
	float *data = new float[numStudents];
	return data;
}


void getFBTData(float *data, int numStudents)
{
	float myNum;
	cout << "Enter the number of hours each student spent on Facebook and/or Twitter." << endl;
	for (int i = 0; i < numStudents; i++)
	{
		do
		{
			cout << "Student " << i + 1 << ": ";
			cin >> myNum;
			*(data + i) = myNum;
		} while (myNum < 0);	
	}
}

void printArray(int num, float* data)
{
	cout << "\nNumber of hours each student spent on Facebook / Twitter in ascending order : " << endl;
	for (int i(0); i < num; ++i)
		cout << data[i] << "   ";
}

float getAverage(float *data, int numStudents)
{
	float total = 0;
	for (int i = 0; i < numStudents; i++)
		total += *(data + i);
	total = total / numStudents;
	return total;
}

int getMode(float *array, int numStudents)
{
	int *repetitions;
	int highest, element, i;
	*array = i;

	repetitions = new int[i];
	for (int x = 0; x<i; x++)
		*(repetitions + x) = 0;

	for (int x = 0; x<i; x++)
	{
		for (int y = 0; y<i; y++)
		{
			if ((numStudents + x) == (numStudents + y))
			{
				(*(repetitions + x))++;
			}
		}
	}
	highest = *(repetitions + 0);
	for (int x = 1; x<i; x++)
	{
		if (*(repetitions + x) > highest)
		{
			highest = *(repetitions + x);
			element = x;
		}
	}
	if (highest == 1)
		return -1;
	else
		return *(array + element);

}

double getMedian(float *array, int num )
{
	if (num <= 0) return 0;
	if (num % 2) return (float)array[(num + 1) / 2];
	else{
		int pos = num / 2;
		return (float)(array[pos] + (array[pos + 1]) / 2);
	}
}

void selectionSort(float *array, int numStudents)
{
	int startScan, minIndex;
	float minValue;

	for (startScan = 0; startScan < (numStudents - 1); startScan++)
	{
		minIndex = startScan;
		minValue = *(array + startScan);
		for (int index = startScan + 1; index < numStudents; index++)
		{
			if (*(array + index) < minValue)
			{
				minValue = *(array + index);
				minIndex = index;
			}
		}
		*(array + minIndex) = *(array + startScan);
		*(array + startScan) = minValue;
	}
}		
Last edited on
Alright i think i fixed it, not sure why it worked but adding some new lines after i call the printArray function made it work, now i just have to fix my woefully broken getMode function! Thank you softrix and all you other guys too!
I believe the main problem is in your getMode function. The variable i is never initialized but you start using it in many sections of your function.

It is possible that the variable i will have a very high junk value, which causes your function to take forever to run.


Other notes:
-Line 95 is suspicious. What exactly are you trying to achieve there?
-On line 97, you allocated heap memory. Remember that whenever you allocate memory, you also have to free it at some point in the program. In this case, you should be calling delete[] on repetition near the end of the getMode function.
-The getMedian function is a bit inconsistent. So far you've been dealing with the float type, but the getMedian function returns a double, not a huge deal but just inconsistent. This will only affect the precision of your numbers.
-Lines 130 and 133: If you are going to cast (but you really didn't have to), cast the returned value to the same type as the return type of the function.
return static_cast<double>(/*etc...*/);
--Also, prefer the C++ cast operators such as static_cast over C-style casting. They are more safer to use and have strictly defined properties.
We haven't learned "cast operators" yet dont think we will until the next class Data Structures. I think im going to redo my get mode function i forgot to insert a part anyway, and its modeled off some class work i did earlier.

Sorry, seems I've missed a few posts, been watching some Supernatural with the wife :)

Anyway.. lets get started... you have to crawl before you walk, avoid cast operators. furthermore, you are not asked to use them in your assignment - stick to the assignment guidelines.

A few things I noticed in your code:

You need to modify your getMedian function as its using array notation, i.e. array[i], your assignment states pointer notation.

Lines 39 - 50 shouldn't be running unless your studentData was allocated correctly, i.e. they would run regardless the way it is now.

When your allocating memory using the new operator you need to remember to free the memory after you have finished with it, but you haven't.


EDIT: getMedian returns a double, assignment states a float, id say getMode should also need to return a float to remain consistent with the other functions and data types, plus if you look at his test output its a float.
Last edited on

A good way of checking your program is to enter the test data provided in the screenshots of your pdf, that's your test data and expected results.

Last edited on
Met up with a friend and he helped me perfect my program.

No problem, glad your sorted.
Hey can you help me fix this function, my lab partner wrote our last lab and messes this function up and i have no idea how to fix it, he just gave me the program to work on and its due in 4 hours, can you set me in the right direction on how to fix it or spot our error?

Edit: Ive narrowed the problem down to the for loop with all the if statements inside of it.
Edit: heres the who program my lab partner has messed up something bad and i cant find it. dropbox.com/s/wgylnriy6vgnkay/Lab10.zip

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
void calculateTotals(int mtype, int numItems, int *type, float *cost, float *hours, float *price)
{
	string horizontalLine(65, '-');
	string canType;
	float totalCost = 0;
	float totalHour = 0;
	float totalPrice = 0;

	if (mtype == 2)
		canType = "Hard Candy";
	else if (mtype == 3)
		canType = "Jelly Beans";
	else if (mtype == 4)
		canType = "Chocolate";
	else if (mtype == 5)
		canType = "Candy in Inventory";

	cout << endl << horizontalLine << "\n\nTotal Pieces Of " << canType << ": \n\n";
	cout << setw(13) << left << "TYPE" << right << setw(13) << "MATERIALS COST" << setw(16) << "LABOR HOURS" << setw(16) << "ASKING PRICE" << endl;

	//added  @Ben Voigt's code so its "cleaner to debug" 
	if (mtype >= 2 && mtype <= 5) {
		for (int itemno = 0; itemno < 1; itemno++) {
			if (mtype == type[itemno]) {
				price[itemno] = calculatePrice(cost[itemno], hours[itemno]);
				totalCost += cost[itemno];
				totalHour += hours[itemno];
				totalPrice += price[itemno];

				if (mtype == 2) cout << setw(13) << left << canType;
				cout << setw(13) << right << cost[itemno]
					<< setw(16) << setprecision(2) << fixed << hours[itemno]
					<< setw(16) << price[itemno] << "\n\n";
				if (mtype == 3) cout << setw(13) << left << canType;
				cout << setw(13) << right << cost[itemno]
					<< setw(16) << setprecision(2) << fixed << hours[itemno]
					<< setw(16) << price[itemno] << "\n\n";
				if (mtype == 4) cout << setw(13) << left << canType;
				cout << setw(13) << right << cost[itemno]
					<< setw(16) << setprecision(2) << fixed << hours[itemno]
					<< setw(16) << price[itemno] << "\n\n";
				if (mtype == 5) cout << setw(13) << left << canType;
				cout << setw(13) << right << cost[itemno]
					<< setw(16) << setprecision(2) << fixed << hours[itemno]
					<< setw(16) << price[itemno] << "\n\n";
			}
		}
	}
	cout << "\n" << setw(9) << left << "TOTALS: "
		<< setw(5) << right << "$" << setw(12) << totalCost
		<< setw(17) << totalHour
		<< setw(11) << "$" << setw(5) << totalPrice << "\n\n";
	cout << horizontalLine << "\n\n";
	cout << flush;
}


heres what its supposed to do, I believe the issue is with the for loop he used to keep the running total of how much candy is added to the list, what ours does when we run it is adds 4 more peice than its supposed to.

FUNCTION: calculateTotals

Function Prototype: void calculateTotals(int, int, int[], float[], float[], float[]);

Function Purpose: This function is called when the user wants to view how many items are
in the different Candy types or all together and see how much in total the materials cost
and asking price is for inventory items. There are quite a few parameters accepted in this
function. First, an integer representing what kind of table will be printed out (1=hard
candy, 2=jelly beans, 3=chocolates, -1 = all). Then, an integer representing how many
total items are in the arrays. Then all four arrays that were defined in main.

This function will figure out what type of table the user is wanting based on the first integer
that is passed into the function and print out the respective table name. For example, if the
user wants to print out information on Hard Candy, the header should read “Total Pieces
Hard Candy:”.

Then, the function will print out the table headers. There should be four columns and each
column should have a header (words) at the top of the column explaining what that column
is.

The values should be printed underneath the column headers. The values for total material
cost and total asking price have to be calculated as running totals. To calculate the total
asking price, this function should call the calculatePrice() function.

If the user wants the totals for Hard Candy only, then your program should be able to
figure out if an item is a piece of hard candy and if it is, then print out the hard candy
information in the table.
Last edited on

Time difference is your worst enemy with me :)

What is the purpose of for (int itemno = 0; itemno < 1; itemno++), it will only run once.
I put that there to stop the program from iterating 3 times. dropbox.com/s/wgylnriy6vgnkay/Lab10.zip heres a link to the program. so you can see what the issue if you want to run it, its really hard for me to explain because this isn't not my code, its my lab partners his laptop died and life sucks.
Edit: that 1 is supposed to be numItems.
Last edited on

In your main() function you are using the comparison operator == instead of a assignment operator = when calling:

numItems = loadCandyItems(candyType, costMaterials, numHours);

In your calculate totals function remove: if (mtype == type[itemno]) as it is stopping the rest of the code being run. Furthermore, the IF statements need brackets around the code since the way it is now would cause 3 x results to be displayed regardless.

It would look like this....

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

void calculateTotals(int mtype, int numItems, int *type, float *cost, float *hours, float *price)
{
	string horizontalLine(65, '-');
	string canType;
	float totalCost = 0;
	float totalHour = 0;
	float totalPrice = 0;

	if (mtype == 2)
		canType = "Hard Candy";
	else if (mtype == 3)
		canType = "Jelly Beans";
	else if (mtype == 4)
		canType = "Chocolate";
	else if (mtype == 5)
		canType = "Candy in Inventory";

	cout << endl << horizontalLine << "\n\nTotal Pieces Of " << canType << ": \n\n";
	cout << setw(13) << left << "TYPE" << right << setw(13) << "MATERIALS COST" << setw(16) << "LABOR HOURS" << setw(16) << "ASKING PRICE" << endl;

	//added  @Ben Voigt's code so its "cleaner to debug" 
	if (mtype >= 2 && mtype <= 5) {
		for (int itemno = 0; itemno < numItems; itemno++) 
		{
			price[itemno] = calculatePrice(cost[itemno], hours[itemno]);
			totalCost += cost[itemno];
			totalHour += hours[itemno];
			totalPrice += price[itemno];

			if (mtype == 2) {
				cout << setw(13) << left << canType;
				cout << setw(13) << right << cost[itemno]
					<< setw(16) << setprecision(2) << fixed << hours[itemno]
					<< setw(16) << price[itemno] << "\n\n";
			}
			if (mtype == 3) {
				cout << setw(13) << left << canType;
				cout << setw(13) << right << cost[itemno]
				<< setw(16) << setprecision(2) << fixed << hours[itemno]
				<< setw(16) << price[itemno] << "\n\n";
			}
			if (mtype == 4) {
				cout << setw(13) << left << canType;
				cout << setw(13) << right << cost[itemno]
				<< setw(16) << setprecision(2) << fixed << hours[itemno]
				<< setw(16) << price[itemno] << "\n\n";
			}
			if (mtype == 5) {
				cout << setw(13) << left << canType;
				cout << setw(13) << right << cost[itemno]
				<< setw(16) << setprecision(2) << fixed << hours[itemno]
				<< setw(16) << price[itemno] << "\n\n";
			}
		}
	}
	cout << "\n" << setw(9) << left << "TOTALS: "
		<< setw(5) << right << "$" << setw(12) << totalCost
		<< setw(17) << totalHour
		<< setw(11) << "$" << setw(5) << totalPrice << "\n\n";
	cout << horizontalLine << "\n\n";
	cout << flush;
}



I made your edits and when i ran the program and go and lets say check the inventory, even if i have not added any to it it displays ten items in it.
Last edited on
Pages: 1... 34567... 9