I'm trying to do some of my C++ homework, but I seem to have run into an issue. I need to make it so that the user inputs 8 numbers, and those said 8 get stored in an array. Then, if one of the numbers is greater than 21, to output said number. The code is below, and it's kind of sloppy. Yes, first year C++ learner here :p
#include <iostream>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8; // Number of elements
int userVals[NUM_ELEMENTS]; // User numbers
int i = 0; // Loop index
int sumVal = 0; // For computing sum
int prntSel = 0; // For printing greater than 21
// Prompt user to populate array
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
// Determine sum
sumVal = 0;
for (i = 0; i < NUM_ELEMENTS; ++i) {
sumVal = sumVal + userVals[i];
}
cout << "Sum: " << sumVal << endl;
return 0;
}
Don't reinvent the wheel, use standard algorithms:
std::copy_if(std::begin(userVals), std::end(userVals),
std::ostream_iterator<int>(std::cout, "\n"),
[] (auto x) { return x > 21; });
I improved the rest of your program as well:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>
auto constexpr count = 8;
int main() {
std::vector<int> numbers(count);
std::cout << "Enter " << count << " integer values...\n";
std::copy_n(std::istream_iterator<int>(std::cin), numbers.size(), numbers.begin());
std::copy_if(numbers.begin(), numbers.end(),
std::ostream_iterator<int>(std::cout, "\n"),
[] (auto x) { return x > 21; });
auto sum = std::accumulate(numbers.begin(), numbers.end(), 0);
std::cout << "Sum: " << sum << '\n';
return 0;
}
See it live on Coliru!
Ok, I'm going to explain this to you and keep it simple. This loop
`for (int i = NUM_ELEMENTS - 1; i > 21; i--)`
will never execute because in your first iteration you are checking if (NUM_ELEMENTS-1=7)>21. You are then decrementing i so this will take the series (6,5,4,...) and nothing would ever happen here.
If you have to sum the numbers greater than 21, which I presume is what you need then you will have to remove the above loop and modify your second loop to:
for (i = 0; i < NUM_ELEMENTS; i++) {
if(userVals[i]>21)
sumVal = sumVal + userVals[i];
}
This way, you add the numbers in the array that are only greater than 21. The index of userVals is determined by the i variable which also acts as a counter.
You're on the right track. There's just a few things wrong with your approach.
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8;
int userVals[NUM_ELEMENTS];
int i = 0;
int sumVal = 0;
int prntSel = 0;
int size = sizeof(userVals) / sizeof(int); // Get size of your array
// 32/4 = 8 (ints are 4 bytes)
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
for(int i = 0; i < size; i++) {
if(userVals[i] > 21) { // Is number > 21?
cout << userVals[i] << endl; // If so, print said number
exit(0); // And exit
}
else
sumVal += userVals[i]; // Else sum your values
}
cout << "Sum: " << sumVal << endl;
return 0;
}
#include <iostream>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8; // Number of elements
int userVals[NUM_ELEMENTS]; // User numbers
int i = 0; // Loop index
int sumVal = 0; // For computing sum
int prntSel = 0; // For printing greater than 21
// Prompt user to populate array
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
// for (int i = NUM_ELEMENTS - 1; i > 21; i--)
// cout << "Value: " << sumVal << endl;
for( i = 0; i < NUM_ELEMENTS; ++i )
{
if( userVals[ i ] > 21 )
{
cout << "Value: " << i << " is " << userVals[ i ] << endl;
}
}
for (i = 0; i < NUM_ELEMENTS; ++i) {
sumVal = sumVal + userVals[i];
}
cout << "Sum: " << sumVal << endl;
return 0;
}
Try
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
to
for (i = 0; i < NUM_ELEMENTS; ++i) {
if(userVals[i] > 21)
cout << "Value: " << userVals[i] << endl;
}
This line isnt needed as well, as you arent using it.
int prntSel = 0; // For printing greater than 21
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
Here you are printing the value of sumVal, not the value of the array in the position i. The line should be:
cout << "Value: " << usersVals[i] << endl;
Also that that your for is not doing what you think it does. for doesn't use the condition you gave to decide if will execute the current iteration or not, it uses the condition to decide if the loop should continue or not. So when you put i > 21, means that it will continue running while i is bigger than 21. To achieve your goal, you should make a test (if statement) inside the loop.
The final result it would be:
for (i = 0; i < NUM_ELEMENTS; ++i) {
if (usersVals[i] > 21) {
cout << "Value: " << usersVals[i] << endl;
}
}
Related
I am trying this code in CodeBlocks but the result is some random numbers!
I appreciate if you check the code and let me know what my mistake is. It should result in multipliers of 25:
#include <iostream>
using namespace std;
main(){
const int array_size = 10;
int numbers[array_size];
int counter = 0;
while(counter < array_size){
numbers[counter] = 25 * counter;
counter++;
cout << "number[" << counter << "] = " << numbers[counter] << endl;
}
}
Thanks in advance.
You are incrementing counter after setting the value of numbers[counter]. After that. numbers[counter] (with the new value of counter) is a new uninitialized element.
You should move the increment after the printing:
#include <iostream>
using namespace std;
int main(){
const int array_size = 10;
int numbers[array_size];
int counter = 0;
while(counter < array_size){
numbers[counter] = 25 * counter;
cout << "number[" << counter << "] = " << numbers[counter] << endl;
counter++;
}
}
Or simply avoid using an array (in this case):
#include <iostream>
int main(){
const int array_size = 10;
int counter = 0;
while(counter < array_size){
std::cout << "number[" << counter << "] = " << 25 * counter << std::endl;
counter++;
}
}
Another way is using two loops -- one for initialization and one for printing:
#include <iostream>
using namespace std;
int main(){
const int array_size = 10;
int numbers[array_size];
int counter = 0;
while(counter < array_size){
numbers[counter] = 25 * counter;
counter++;
}
counter = 0;
while(counter < array_size){
cout << "number[" << counter << "] = " << numbers[counter] << endl;
counter++;
}
}
You are outputting an uninitialized element of the array after incrementing of the variable counter.
counter++;
cout << "number[" << counter << "] = " << numbers[counter] << endl;
The reason of the error is usage of an inappropriate loop.
Instead of the while loop it is better to use for loop.
For example
for ( int counter = 0; counter < array_size; counter++ ){
numbers[counter] = 25 * counter;
cout << "number[" << counter << "] = " << numbers[counter] << endl;
}
Pay attention to that the function main without parameters shall be declared like
int main()
That is you may not omit the function return type.
change for this code
const int array_size = 10;
int numbers[array_size];
int counter = 0;
while(counter < array_size){
numbers[counter] = 25 * counter;
cout << "number[" << counter << "] = " << numbers[counter] << endl;
counter++;
}
My task is to convert my for loops into for-each loops.
The task begins with creating a two dimensional array 6x30. This represents 6 classes of 30 students each. Each position in the array contains a random number between 55 and 100 which represents a student score.
Next I display that array to the console.
Next I calculate the average score of each class.
Next I find the highest average among the 6 classes and display that to the screen.
I am using Xcode on MacBook Pro.
Question: How can I properly convert my for loops into for-each loops?
My code is below:
#include <iostream>
#include <iomanip>
using namespace std;
const int NUM_CLASSES = 6, NUM_STUDENTS_PER_CLASS = 30;
void bubbleSort(int arr[], int n){
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] < arr[j + 1])
swap(arr[j], arr[j + 1]);
}
}
}
void classGradeGeneration() {
int arrayOne[NUM_CLASSES][NUM_STUDENTS_PER_CLASS], classAverage[NUM_CLASSES];
//Generating random average student scores until array filled
for (int classNumber = 0; classNumber < NUM_CLASSES; classNumber++) {
for (int column = 0; column < NUM_STUDENTS_PER_CLASS; column++) {
arrayOne[classNumber][column] = rand() % 46 + 55;
}
}
//Displaying array of student scores
for (int classNumber = 0; classNumber < NUM_CLASSES; classNumber++) {
cout << "Class " << classNumber + 1 << ": ";
for (int column = 0; column < NUM_STUDENTS_PER_CLASS; column++) {
cout << setw(3) << arrayOne[classNumber][column] << " ";
classAverage[classNumber] += arrayOne[classNumber][column];
}
cout << endl;
}
cout << endl;
int averageScore, averageOfClasses[NUM_CLASSES];
//Displaying average class scores
for (int temp = 0; temp < NUM_CLASSES; temp++) {
averageScore = classAverage[temp] / NUM_STUDENTS_PER_CLASS;
cout << "Class " << temp + 1 <<" Average score: " << averageScore << endl;
averageOfClasses[temp] = averageScore;
}
cout << endl;
bubbleSort(averageOfClasses, NUM_CLASSES); // Sorting average scores highest to lowest
cout << endl;
cout << "The highest average score is: " << averageOfClasses[0];
cout << endl;
}
int main () {
srand(time(NULL));
classGradeGeneration();
cout << endl << endl;
}
Below is a sample output:
You may use range-based for with std::array since C++11
constexpr int NUM_CLASSES = 6, NUM_STUDENTS_PER_CLASS = 30;
std::array<std::array<int, NUM_STUDENTS_PER_CLASS>, NUM_CLASSES> arr;
for (/*const*/ auto& ln : arr) {
std::cout << "LINE" << std::endl;
for (/*const*/ auto& elem : ln) {
std::cout << "elem" << std::endl;
}
}
or for_each if you want
std::for_each(arr.begin(), arr.end(), [](/*const*/ auto& line) {
std::cout << "LINE" << std::endl;
std::for_each(line.begin(), line.end(), [](/*const*/ auto& elem) {
std::cout << "elem" << std::endl;
});
});
But I prefer range-based for in this case.
If you use c-style array then for_each arguments will be pointers, not iterators.
int arr[NUM_CLASSES][NUM_STUDENTS_PER_CLASS], classAverage[NUM_CLASSES];
std::for_each(std::begin(arr), std::end(arr), [](/*const*/ auto& line) {
std::cout << "LINE" << std::endl;
std::for_each(std::begin(line), std::end(line), [](/*const*/ auto& elem) {
std::cout << "elem" << std::endl;
});
});
So your code may look like this
constexpr int NUM_CLASSES = 6, NUM_STUDENTS_PER_CLASS = 30;
std::array<std::array<int, NUM_STUDENTS_PER_CLASS>, NUM_CLASSES> arr;
// set random values
for (auto& ln : arr) {
for (auto& elem : ln) {
elem = std::rand() % 100;
}
}
// calculate
float avgScore = 0.0F;
for (const auto& ln : arr) {
const auto avgGroupScore = std::accumulate(std::begin(ln), std::end(ln), 0.0F) / (std::end(ln) - std::begin(ln));
avgScore = std::max(avgScore, avgGroupScore);
std::cout << "avg group score=" << avgGroupScore << "; current avgScore=" << avgScore << std::endl;
}
am new in coding and am using c++ to create a program to find sum median maximum and minimum but i get the error expected primary-expression before ';' token in every place that has cout
#include <iostream>
using namespace std;
int main()
{
int array[10],maximum,minimum,sum=0,median;
cout<<"input ten integers,"<<;
for(int i=0; i<10; i++){
cin>> array[i];
sum=sum+array[i];
}
for(int i=0; i<10; i++){
if(maximum>array[i])
{
maximum=array[i];
}
else if( minimum<array[i])
{
maximum= array[i];
}
}
median=(array[4]+array[5])/2;
cout<<"maximum value is"<<maximum<<;
cout<<"minimum value is"<<minimum<<;
cout<<"sum is"<<sum<<;
cout<<"median is"<median<<;
Remove the << before the ; on every line that has it or replace <<; with <<'\n'; for a new line.
#include <iostream>
using namespace std;
int main()
{
int array[10], maximum = 0, minimum = 0, sum = 0, median = 0;
cout << "input ten integers: ";
for (int i = 0; i < 10; i++) {
cin >> array[i];
sum = sum + array[i];
}
for (int i = 0; i < 10; i++) {
if (maximum > array[i])
{
maximum = array[i];
}
else if (minimum < array[i])
{
maximum = array[i];
}
}
median = (array[4] + array[5]) / 2;
cout << "maximum value is " << maximum << '\n';
cout << "minimum value is " << minimum << '\n';
cout << "sum is " << sum << '\n';
cout << "median is " << median << '\n';
return 0;
}
Use the below dummy code to fix this issue for the new line:
dummy code
#include <iostream>
int main() {
int a = 5;
int b = 10;
std::cout << (a < b) << std::endl; // 1
std::cout << (a > b) << std::endl; // 0
return 0;
}
output
1
0
I wrote a program to accept 15 integer values in an array, then pass this array to a function which will multiply each even index value by 4.
Currently the program displays the initial array, but seems like it's getting hung up before it displays the modified array.
Please help me understand why the program is getting stuck here!
int main(){
const int SIZE = 15;
int quad[SIZE] = {};
void quadruple(int[], const int);
cout << "Enter 15 integer values into an array." << endl;
for (int i = 0; i < SIZE; i++) // Accept 15 int values
{
cout << i << ": ";
cin >> quad[i];
}
cout << "Before quadruple function is called: " << endl;
for (int i = 0; i < SIZE; i++)
{
cout << quad[i] << " ";
}
cout << endl;
quadruple(quad, SIZE);
cout << "After even index value multiplication: " << endl;
for (int i = 0; i < SIZE; i++)
{
cout << quad[i] << " ";
}
cout << endl;
return 0;
}
void quadruple(int values[], const int SZ){
for (int i = 0; i < SZ; i + 2) // Multiply even values by 4
{
if ((i % 2) == 0)
{
values[i] = values[i] * 4;
}
else // Keep odd values the same
{
values[i] = values[i] * 1;
}
}
}
for (int i = 0; i < SZ; i + 2)
"i + 2" doesn't do anything.
You probably meant "i += 2;".
Your homework assignment is to find some documentation about your system's debugger. And find where your rubber duck is, as it's been suggested in the comments.
Why do I get a program crash for large values but not small values for my program? If I input 1-3 the program does what it is supposed to but when I enter a number greater than that the program crashes and/or does not complete? Is it something to do with a pointer error or the way I've referenced something? I'm unsure so any help is appreciated. Thanks!
Code:
#include <iostream>
using namespace std;
void getData (int size, int *Arr){
cout << "\n\nEnter integer data one line at a time\n" << endl ;
for (int i=0; i < size; i++){
cin >> Arr[i];
}
}
void findMinAndMax(int array[], int size, int *min, int *max) {
int smallest = array[0];
int largest = array[0];
*min = smallest;
*max = largest;
for (int i = 1; i < size; i++)
{
if (array[i] > *max){
*max = array[i];
cout << "Max Value (loop): " << *max << endl;
}
if (array[i] < *min){
*min = array[i];
cout << "Min Value (loop): " << *max << endl;
}
}
// testing code
cout << "Min Value: " << *min << endl;
cout << "Max Value: " << *max << endl;
}
int *makeFrequency (int data[], int dSize, int *minDataValue, int *maxDataValue) {
cout << "Min Value Pre: " << *minDataValue << endl;// testing code
cout << "Max Value Pre: " << *maxDataValue << endl;// testing code
findMinAndMax(data, dSize, minDataValue, maxDataValue);
cout << "Min Value Post: " << *minDataValue << endl; // testing code
cout << "Max Value Post: " << *maxDataValue << endl;// testing code
int fSize = *minDataValue + *maxDataValue;
cout << "fSize: " << fSize << endl; // testing code
int *frequency;
frequency = new int [fSize];
// if frequency is 0, end
if (frequency == 0)
{
return 0;
}
// set all elements to 0 in array frequency
for (int i = 0; i <= fSize; i++) {
frequency[i] = 0;
}
for (int i = 0; i <= dSize; i++) {
int j = data[i] - (*minDataValue) + 1;
frequency[j] = frequency[j] + 1;
}
return frequency;
}
void makeHistogram (int *freq, int min, int max ){
cout << "Frequency Value HISTOGRAM: " << *freq << endl;
cout << "\n\n\n ----------- Histogram ----------------\n" << endl;
int size = min + max;
cout << "Size Value HISTOGRAM: " << size << endl;
for (int i = 0; i < size; i++){
if (freq[i] > 0) {
cout << "\n" << min + i - 1 << ": ";
for (int j = 0; j < freq[i]; j++) {
cout << '*';
}
}
}
cout << endl << endl;
}
int main() {
int dSize;
int *ArrayOfInts;
cout << "How many data values? ";
cin >> dSize;
ArrayOfInts = new int [dSize];
getData(dSize, ArrayOfInts);
int *frequency, min, max;
frequency = makeFrequency(ArrayOfInts, dSize, &min, &max);
if (frequency == 0) return -1;
cout << "Min Value MAIN: " << min << endl; // testing code
cout << "Max Value MAIN: " << max << endl; // testing code
cout << "Frequency Value MAIN: " << *frequency << endl;
makeHistogram(frequency, min, max);
delete [] frequency;
return 0;
}
One place where you have undefined behaviour which can cause crashes:
here you allocate fSize elements:
frequency = new int [fSize];
later you iterate it until fSize:
for (int i = 0; i <= fSize; i++) {
you should change to i < fSize, because there is no fSize element in your array. And the same problem with i <= dSize later on. Should be i < dSize.
btw. I dont see why only large values should cause crashes in your code, maybe this is just UB.
You're setting fSize incorrectly. It should be the difference between the maximum and minimum values, not the sum of them. Otherwise, if you have negative numbers in your list, the frequency array will be too small. And if absolute value of any of the negative numbers is larger than the highest number, fSize will be negative, which is not valid for the size of an array.
Then you need to add 1 to include both endpoints. So it should be:
int fSize = *maxDataValue - *minDataValue + 1;
Then, as the other answer pointed out, you need to fix your for loops. When the size of an array is N, the array indexes from from 0 to N-1. So it should be:
for (int i = 0; i < fSize; i++) {
using < as the loop test, not <=. If you try to write outside an array, you invoke undefined behavior, so anything can happen -- if you're lucky you get a crash, but that's not guaranteed.
You have a similar problem when you assign to frequency:
for (int i = 0; i <= dSize; i++) {
int j = data[i] - (*minDataValue) + 1;
frequency[j] = frequency[j] + 1;
}
There's no need to add 1 when subtracting *minDataValue, and doing so will cause you to go outside the array when data[i] is the maximum.