+ 2

how to use cin inside for loop?

#include <iostream> using namespace std; int main() { int n,a,b,i,sum,arr [i]; cout << "Please enter amout of number"; cin >> n; for (i=0;i<n;i++){ cout << "please enter number to sum"; cin >> a; //i try to use cin //but i can't. arr[i]=a; } while (i<n){ sum+=arr[i]; cout << sum; } cout << "sum of number is " << sum; return 0; } https://code.sololearn.com/cW2RN4Wf

6th Sep 2017, 12:55 PM
wachirut chaiwong
wachirut chaiwong - avatar
3 Respostas
+ 3
now i re write code and has new problem i can't use the dereference operator *sum and i don't know why. T_T #include <iostream> using namespace std; int main() { int n,a,b,i,j; int *sum=nullptr; sum = new int; sum = 0; int *arr =nullptr; arr = new int[20]; cin >> n; for (i=0;i<n;i++){ cin >> a; //i try to use cin //but i can't. arr[i]=a; cout << arr[i] << endl ; } for (j=0;j<n;j++){ sum+=arr[j]; } cout << "sum of number is " << sum; //can't use *sum; return 0; }
7th Sep 2017, 1:01 PM
wachirut chaiwong
wachirut chaiwong - avatar
+ 1
the problen is within arr[i] i assume, not within cin statement. when you declare an array, you have to give it a static length. for example, make int arr[n] after the cin>>n; this will create an array of int s with the lenght of N. then make a loadup and thell me how it goes
6th Sep 2017, 1:10 PM
Paul
0
Somebody pls. ans. this becoz I have the same doubt
4th Oct 2020, 5:43 AM
Sambit Kar
Sambit Kar - avatar