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
Related
Link to the question:
https://www.codewars.com/kata/54d496788776e49e6b00052f/train/cpp
Guys could you please help me figure out why my solution worked completely fine in Visual Studio but not in Codewars?
The error in Codewars is as follows:
UndefinedBehaviorSanitizer:DEADLYSIGNAL
==1==ERROR: UndefinedBehaviorSanitizer: SEGV on unknown address 0x000000000000 (pc 0x000000425dce bp 0x000000000000 sp 0x7ffca477d200 T1)
==1==The signal is caused by a READ memory access.
==1==Hint: address points to the zero page.
==1==WARNING: invalid path to external symbolizer!
==1==WARNING: Failed to use and restart external symbolizer!
#0 0x425dcd (/workspace/test+0x425dcd)
#1 0x425a0a (/workspace/test+0x425a0a)
#2 0x42b951 (/workspace/test+0x42b951)
#3 0x429b5e (/workspace/test+0x429b5e)
#4 0x42958d (/workspace/test+0x42958d)
#5 0x42927b (/workspace/test+0x42927b)
#6 0x42e235 (/workspace/test+0x42e235)
#7 0x4287fd (/workspace/test+0x4287fd)
#8 0x7f833e965bf6 (/lib/x86_64-linux-gnu/libc.so.6+0x21bf6)
#9 0x404a29 (/workspace/test+0x404a29)
UndefinedBehaviorSanitizer can not provide additional info.
==1==ABORTING
*In Codewars,
the test ran fine, but the attempt didn't, the calculations were all correct, but when it went to question number 3, the error strikes and it doesn't continue on to solving questions anymore.
The code I used in Codewars:
#include <iostream>
#include <vector>
#include <string>
#include <tuple>
#include <chrono>
#include <thread>
//Sum by Factors(Finished)
//====================
using namespace std;
class SumOfDivided
{
vector<int> SuitablePrimeArray;
string getSumOfNumbersByPrimeFactorAndMakeBracket(int PrimeNumber, vector<int>& I);//for createBrackets
tuple<int, vector<int>> findSmallestNumberInArrayAndDeleteIt(vector<int> Numbers);//for sortAscendingly
public:
int findLargestNumberInArray(vector<int> Numbers);
vector<int> findPrimeNumbersTill(int End);
vector<int> findPrimeFactorsFromArray(vector<int> PrimeArr, vector<int> Numbers);
void printVectorArray(vector<int> array);
string executeKata(vector<int> Numbers);
string createBrackets(vector<int> FinalPrimeArr, vector<int>& Numbers);
vector<int> sortAscendingly(vector<int> input);
vector<int> generateRandomVector(int NumberCount, int minimum, int maximum);
int generateRandomNumber(int minimum, int maximum);
static string sumOfDivided(vector<int> &lst);
};
string SumOfDivided::sumOfDivided(vector<int> &lst){
SumOfDivided test;
return test.executeKata(lst);
}
string SumOfDivided::executeKata(vector<int> Numbers) {
cout << "The array: " << endl;
printVectorArray(Numbers);
cout << endl;
int TheLargestNumber = findLargestNumberInArray(Numbers);
cout << "The largest number from this array: " << endl << TheLargestNumber << endl;
cout << endl;
cout << "All the prime factors of this array: " << endl;
//printVectorArray(findFactorsFromArray(findPrimeNumbersTill(TheLargestNumber), Numbers));
SuitablePrimeArray = findPrimeFactorsFromArray(findPrimeNumbersTill(TheLargestNumber), Numbers);
printVectorArray(SuitablePrimeArray);
cout << endl;
string Answer = createBrackets(SuitablePrimeArray, Numbers);
cout << "Answer for the 4 kyu Kata(Sum by Factors): " << endl << Answer << endl;
return Answer;
}
int SumOfDivided::findLargestNumberInArray(vector<int> Numbers) {
int largest, i, pos;
largest = Numbers[0];
for (i = 1; i < Numbers.size(); i++) {
if (Numbers[i] > largest) {
largest = Numbers[i];
pos = i;
}
}
return largest;
}
vector<int> SumOfDivided::findPrimeNumbersTill(int End) {
vector<int> PrimeArr;
//PrimeArr.reserve(50);
int position = 0;
int n = 2;
while (position < End) {
bool isPrime = true;
for (int i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
isPrime = false; break;
}
}
//if (isPrime){PrimeArr[position] = n; position++;}
if (isPrime) {
PrimeArr.push_back(n);
position++;
}
n++;
}
/*
for (int i = 0; i < position; i++) {
cout << PrimeArr[i] << ",";
}
*/
//printVectorArray(PrimeArr);
//cout << endl;
return PrimeArr;
}
vector<int> SumOfDivided::findPrimeFactorsFromArray(vector<int> PrimeArr, vector<int> Numbers) {
/*
for (int i = 0; i < PrimeArr.size(); i++) {
cout << PrimeArr[i] << ", ";
}
*/
vector<int> FinalPrimeFactorArray;
int position = 0;
for (int i = 0; i < Numbers.size(); i++) {
for (int j = 0; j < PrimeArr.size(); j++) {
if (Numbers[i] % PrimeArr[j] == 0 && find(FinalPrimeFactorArray.begin(), FinalPrimeFactorArray.end(), PrimeArr[j]) == FinalPrimeFactorArray.end()) {
FinalPrimeFactorArray.push_back(PrimeArr[j]); position++;
}
}
}
return sortAscendingly(FinalPrimeFactorArray);;
}
void SumOfDivided::printVectorArray(vector<int> array) {
for (int i = 0; i < array.size(); i++) {
cout << array[i] << ",";
}
cout << endl;
}
//=======================the code below is from part of my codewar unfinished scripts
string SumOfDivided::createBrackets(vector<int> FinalPrimeArr, vector<int>& Numbers) {
string Answer;
vector<int> I;
for (int i = 0; i < Numbers.size(); i++) {
I.push_back(0);
I[i] = Numbers[i];
//cout << "push back x" << i + 1 << endl;
}
for (int i = 0; i < FinalPrimeArr.size(); i++) {
Answer += getSumOfNumbersByPrimeFactorAndMakeBracket(FinalPrimeArr[i], I);
}
return Answer;
}
string SumOfDivided::getSumOfNumbersByPrimeFactorAndMakeBracket(int PrimeNumber, vector<int>& I) {
int Sum = 0;
for (int i = 0; i < I.size(); i++) {
//add this number to the total if the current number is divisible by the prime number
if (I[i] % PrimeNumber == 0)Sum += I[i];
}
//cout << "The sum of numbers divisible by the prime number " << PrimeNumber << " is " << Sum << endl;
string temp = "(" + to_string(PrimeNumber) + " " + to_string(Sum) + ")";
//cout << temp << endl;
return temp;
}
//=====================SORT ASCENDINGLY
tuple<int, vector<int>> SumOfDivided::findSmallestNumberInArrayAndDeleteIt(vector<int> Numbers) {
int smallest, i, pos(0);
smallest = Numbers[0];
for (i = 1; i < Numbers.size(); i++) {
if (Numbers[i] < smallest) {
smallest = Numbers[i];
pos = i;
}
}
Numbers.erase(Numbers.begin() + pos);
return make_tuple(smallest, Numbers);
}
vector<int> SumOfDivided::sortAscendingly(vector<int> input) {
vector<int> output;
int CurrentLargestNumber;
int End = input.size();
for (int i = 0; i < End; i++) {
tie(CurrentLargestNumber, input) = findSmallestNumberInArrayAndDeleteIt(input);
//cout << CurrentLargestNumber << ", ";
output.push_back(CurrentLargestNumber);
}
return output;
}
//=============================RANDOM GENERATION
vector<int> SumOfDivided::generateRandomVector(int NumberCount, int minimum, int maximum) {
vector<int> vecRandomValues;
int i = 0, randValue = 0;
srand(time(NULL));
while (i < NumberCount) {
randValue = rand() % (maximum - minimum + 1) + minimum;
vecRandomValues.push_back(randValue);
i++;
}
return vecRandomValues;
}
int SumOfDivided::generateRandomNumber(int minimum, int maximum) {
return rand() % (maximum - minimum + 1) + minimum;
}
*And my code in Visual Studio, basically the same but with random number generation to randomly test it, I can run it 5000 times in 10 seconds and no error occurred.
The Code I used in Visual Studio:
//Sum by Factors(unFinished)
//====================
#include <iostream>
#include <vector>
#include <string>
#include <Windows.h>
#include "RandomNumber.h"
#include "Bubblesort.h"
/*
Sum by prime factors:
example:
list of number: 12, 15
answer: (2, 12), (3, 27), (5, 15)
explaination for generating answers:
( (all prime factors from the list of numbers in ascending order),(sum of all the nominators of this prime factor on the left) )
*/
using namespace std;
class SumOfDivided
{
vector<int> SuitablePrimeArray;
string getSumOfNumbersByPrimeFactorAndMakeBracket(int PrimeNumber, vector<int>& I);//for createBrackets
public:
int findLargestNumberInArray(vector<int> Numbers);
vector<int> findPrimeNumbersTill(int End);
vector<int> findPrimeFactorsFromArray(vector<int> PrimeArr, vector<int> Numbers);
void printVectorArray(vector<int> array);
string executeKata(vector<int> Numbers);
string createBrackets(vector<int> FinalPrimeArr, vector<int>& Numbers);
};
int main() {
vector<SumOfDivided> list;
for (int i = 0; i < 5000; i++) {
SumOfDivided test;
list.push_back(test);
cout << "attempt " << i + 1 << endl;
test.executeKata(RandomNumber::generateRandomVector(RandomNumber::generateRandomNumber(2, 10), 100, 1000));
cout << "=========================================" << endl;
cout << endl;
}
/*
for (int i = 0; i < 10; i++) {
SumOfDivided* test = new SumOfDivided;
RandomNumber* a = new RandomNumber;
cout << "attempt " << i + 1 << endl;
test->executeKata(a->generateRandomVector(a->generateRandomNumber(2, 10), 100, 1000));
cout << "=========================================" << endl;
cout << endl;
//delete test, a;
}
*/
//vector<vector<int>> Numbers = { { 12,15,24,18,2525 }, { 44,787,84,75,255,7543,373,6746,473 }, { 360,777,689,426,999 } };
//test.executeKata(Numbers[0]);
////std::this_thread::sleep_for(std::chrono::milliseconds(1000));
//cout << "============" << endl;
//test.executeKata(Numbers[1]);
////std::this_thread::sleep_for(std::chrono::milliseconds(1000));
//cout << "============" << endl;
//test.executeKata(Numbers[2]);
}
string SumOfDivided::executeKata(vector<int> Numbers) {
cout << "The array: " << endl;
printVectorArray(Numbers);
cout << endl;
int TheLargestNumber = findLargestNumberInArray(Numbers);
cout << "The largest number from this array: " << endl << TheLargestNumber << endl;
cout << endl;
cout << "All the prime factors of this array: " << endl;
//printVectorArray(findFactorsFromArray(findPrimeNumbersTill(TheLargestNumber), Numbers));
SuitablePrimeArray = findPrimeFactorsFromArray(findPrimeNumbersTill(TheLargestNumber), Numbers);
printVectorArray(SuitablePrimeArray);
cout << endl;
string Answer = createBrackets(SuitablePrimeArray, Numbers);
cout << "Answer for the 4 kyu Kata(Sum by Factors): " << endl << Answer << endl;
return Answer;
}
int SumOfDivided::findLargestNumberInArray(vector<int> Numbers) {
int largest;
unsigned i, pos;
largest = Numbers[0];
for (i = 1; i < Numbers.size(); i++) {
if (Numbers[i] > largest) {
largest = Numbers[i];
pos = i;
}
}
return largest;
}
vector<int> SumOfDivided::findPrimeNumbersTill(int End) {
vector<int> PrimeArr;
//PrimeArr.reserve(50);
int position = 0;
int n = 2;
while (position < End) {
bool isPrime = true;
for (int i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
isPrime = false; break;
}
}
//if (isPrime){PrimeArr[position] = n; position++;}
if (isPrime) {
PrimeArr.push_back(n);
position++;
}
n++;
}
/*
for (int i = 0; i < position; i++) {
cout << PrimeArr[i] << ",";
}
*/
//printVectorArray(PrimeArr);
//cout << endl;
return PrimeArr;
}
vector<int> SumOfDivided::findPrimeFactorsFromArray(vector<int> PrimeArr, vector<int> Numbers) {
/*
for (int i = 0; i < PrimeArr.size(); i++) {
cout << PrimeArr[i] << ", ";
}
*/
vector<int> FinalPrimeFactorArray;
unsigned position = 0;
for (unsigned i = 0; i < Numbers.size(); i++) {
for (unsigned j = 0; j < PrimeArr.size(); j++) {
if (Numbers[i] % PrimeArr[j] == 0 && find(FinalPrimeFactorArray.begin(), FinalPrimeFactorArray.end(), PrimeArr[j]) == FinalPrimeFactorArray.end()) {
FinalPrimeFactorArray.push_back(PrimeArr[j]); position++;
}
}
}
return Bubblesort::sortAscendingly(FinalPrimeFactorArray);;
}
void SumOfDivided::printVectorArray(vector<int> array) {
for (unsigned i = 0; i < array.size(); i++) {
cout << array[i] << ",";
}
cout << endl;
}
//=======================the code below is from part of my codewar unfinished scripts
string SumOfDivided::createBrackets(vector<int> FinalPrimeArr, vector<int>& Numbers) {
string Answer;
vector<int> I;
for (unsigned i = 0; i < Numbers.size(); i++) {
I.push_back(0);
I[i] = Numbers[i];
//cout << "push back x" << i + 1 << endl;
}
for (unsigned i = 0; i < FinalPrimeArr.size(); i++) {
Answer += getSumOfNumbersByPrimeFactorAndMakeBracket(FinalPrimeArr[i], I);
}
return Answer;
}
string SumOfDivided::getSumOfNumbersByPrimeFactorAndMakeBracket(int PrimeNumber, vector<int>& I) {
int Sum = 0;
for (unsigned i = 0; i < I.size(); i++) {
//add this number to the total if the current number is divisible by the prime number
if (I[i] % PrimeNumber == 0)Sum += I[i];
}
//cout << "The sum of numbers divisible by the prime number " << PrimeNumber << " is " << Sum << endl;
string temp = "(" + to_string(PrimeNumber) + " " + to_string(Sum) + ")";
//cout << temp << endl;
return temp;
}
*Lastly, when I checked the MSI afterburner, even solving 10000 solutions in a row doesn't use much ram, and it stays steady, not going up, so I don't think it's codewar running out of memory :)
The error message you receive comes form the undefined behavior sanitizer. This is an optional feature that can be enabled with compiler flags. It seems that it is enabled in the Codewars environment but not in your Visual Studio environment.
Your code may produce the correct result, but the crash indicates that this is merely a coincidence because you invoke undefined behavior somewhere.
Try narrowing it down before asking any more questions.
Usually, it will give a proper backtrace with filenames and line numbers, however, it seems that something is configured incorrectly and you only have addresses in the backtrace:
#0 0x425dcd (/workspace/test+0x425dcd)
#1 0x425a0a (/workspace/test+0x425a0a)
#2 0x42b951 (/workspace/test+0x42b951)
#3 0x429b5e (/workspace/test+0x429b5e)
#4 0x42958d (/workspace/test+0x42958d)
#5 0x42927b (/workspace/test+0x42927b)
#6 0x42e235 (/workspace/test+0x42e235)
#7 0x4287fd (/workspace/test+0x4287fd)
#8 0x7f833e965bf6 (/lib/x86_64-linux-gnu/libc.so.6+0x21bf6)
#9 0x404a29 (/workspace/test+0x404a29)
This part of the error message tells you what is wrong, not sure how to fix it though:
==1==WARNING: invalid path to external symbolizer!
==1==WARNING: Failed to use and restart external symbolizer!
I have a code that generates 10 random numbers and I need to calculate the sum and product of the non-zero numbers and display which numbers have been multiplied. I already have most of the code but I have no idea how to multiply numbers that are nonzero and then display them. Can someone help me?
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <windows.h>
using namespace std;
int main()
{
cout << "draws 10 numbers:" << endl;
Sleep(1000);
cout << endl;
srand(time(0));
int sum=0;
int product=1;
for(int i=0, value=0; i<10; i++, sum+=value, product*=value)
{
value = rand()%10+0;
Sleep(1000);
cout << value << endl;
}
Sleep(1000);
cout << "the sum is " << sum <<endl;
cout << "the product is " << product <<endl;
return 0;
}
To start, it is easier to read and understand if we move the addition and multiplication out of the for loop header.
int sum = 0;
int value = 1;
for(int i = 0; i < 10; i++)
{
int value = rand() % 10;
sum += value;
product *= value;
std::cout << value << std::::endl;
}
Next, we only want to do the multiplication if the value is not equal 0.
int sum = 0;
int value = 1;
for(int i = 0; i < 10; i++)
{
int value = rand() % 10;
sum += value;
if(value != 0)
{
product *= value;
}
std::cout << value << std::::endl;
}
So the whole program looks like this.
#include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
std::cout << "draws 10 numbers:" << std::endl;
srand(time(0));
int sum = 0;
int product = 1;
int multiplied = 0;
for(int i = 0; i < 10; i++)
{
int value = rand() % 10;
sum += value;
if(value != 0)
{
product *= value;
multiplied += 1;
}
std::cout << value << " ";
}
std::cout << std::endl;
std::cout << "the sum is " << sum << std::endl;
std::cout << "the product is " << product << std::endl;
std::cout << "numbers multiplied is " << multiplied << std::endl;
return EXIT_SUCCESS;
}
I want to find the factors of a product by using arrays to check whether they equal it or not
the values do not print
here is the code
#include <iostream>
using namespace std;
int main() {
int arr[5] = { 1,3,5,7,2 };
int arr1[5] = { 0,6,5,4,9 };
int X;
cout << "Please enter X:"; cin >> X;
for (int i = 0, j = 0; i < 5 && j < 5; ++i, ++j) {
if (arr[i]*arr[j]==X) {
cout << arr[i] << " ";
cout << arr1[j] << " ";
}
}
}
Use this nested loops
for (int i = 0; i < 5 ;++i) {
for(int j=0 ;j<5;++j){
if (arr[i]*arr1[j]==X) {
cout << arr[i] << " ";
cout << arr1[j] << " ";
}
}
}
Having trouble with the last for loop. Want the total of the array values.
#include<iostream>
using namespace std;
// Arrays
int main()
{
const int numEmploye = 6;
int horas[numEmploye];
int total = 0;
for (int i = 0; i < numEmploye; i++) {
cout << "entre las horas trabajadas por el empleado " << i + 1 << ": ";
cin >> horas[i];
}
for (int i = 0; i < numEmploye; i++) {
cout << horas[i] << endl;
}
for (int i = 0; i < numEmploye; i++){
cout << total += numEmploye[i];
}
system("Pause");
return 0;
}
You're outputting the return value of the += operator. You're also using the wrong variable for the array.
for (int i = 0; i < numEmploye; i++){
total += horas[i];
}
cout << total << endl; // endl flushes the buffer
Instead of using the following, which prints the value of total += numEmploye[i]; numEmploye times...
for (int i = 0; i < numEmploye; i++){
cout << total += numEmploye[i];
}
... calculate the total first and then print that.
for (int i = 0; i < numEmploye; i++){
total += horas[i];
}
cout << total;
Also, as of C++11 you can use one of these options:
#include <numeric>
...
int total = std::accumulate(std::begin(horas), std::end(horas), 0);
std::cout << total << std::endl;
or
for (int i : horas)
total += i;
std::cout << total << std::endl;
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;
}
}