0

Can someone help me with this array excercise? I have an error in the sum part

/* Escribe un programa que defina un vector de numeros y calcule si existe algun numero en el vector cuyo valor equivale a la suma del resto de numeros del vector*/ #include<iostream> #include<conio.h> using namespace std; int main(){ int cant, suma=0, arr[100], mayor=0; cout<<"Ingrese la cantidad de digitos que va a tener el arreglo: "; cin>>cant; for(int i=0; i<cant; i++){ cout<<"Ingrese el valor # "<<i+1<<" del arreglo: "; cin>>arr[i]; if(arr[i]>mayor){ mayor=arr[i];}} cout<<"El numero mayor del arreglo es: "<<mayor<<endl; for(int i=arr[0]; i<arr[cant]; i++){ suma += arr[i];} cout<<"La suma es: "<<suma<<endl; if(suma==mayor){ cout<<"El numero mayor es igual a la suma de todos los demas numeros"<<endl; }else{ cout<<"El numero mayor no es igual a la suma de todos los demas numeros"<<endl; } getch(); return 0; }

13th Jul 2020, 5:57 PM
Daniel Valdez
Daniel Valdez - avatar
3 Answers
+ 1
Hello Daniel Valdez, In the sum part, you are using a for loop, which uses the condition i<arr[cant]... Where cant is the number of elements in arr... Now the first element is arr[0], and the second is arr[1] and so on.. the last element is therefor arr[cant - 1].. This is, why there is an segmentation error (access violation)... And then there is a logical error in the for loop... In this for loop, i represents the indices, so it should be starting at 0, and ending at cant - 1.. Furthermore arr[cant - 1] itself should also be taken into account, so you should check for <=... And last but not least, mayor should not be taken into suma... All in all, your for loop should be like: for(int i = 0; i <= (cant-1); i++){ if (arr[i] != mayor) { suma += arr[i]; } } Hope this helps...
13th Jul 2020, 7:27 PM
G B
G B - avatar
0
Maan, you're good. I only have a week learning to program. It's my first language. Now it runs, I've been struggling with this problem for two days https://code.sololearn.com/cjYiNT3i799b here's the link thank you man
14th Jul 2020, 4:41 AM
Daniel Valdez
Daniel Valdez - avatar