How can I add elements in a int arr using for loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How can I add elements in a int arr using for loop

done but not working https://code.sololearn.com/cAazl1B7H23E/?ref=app

5th Oct 2017, 6:08 AM
Sayantan Sinharay
Sayantan Sinharay - avatar
4 Answers
+ 17
First of all, thank you ChaoticDawg for your great illustration, as always thorough and beautiful. Just for the sake of clarification for our friend Sayantan, I'd like to add a short note about the necessity of using getline function instead of cin object. getline(cin, arr); // get the string before you attempt to get the length of it ChaoticDawg pointed out nicely "before you attempt to get the length" and you might wonder why. Imagine you want to get a paragraph text from the user, containing "space" (e.g. "Good morning"). In this situation cin object, incapable of reading the full length of that string and if you attempt to print out that by cout you get "Good" (which has the length of 4) as output, not "Good morning". So, Keep that in mind, if you happened to write such a program, use getline.
5th Oct 2017, 8:15 AM
Babak
Babak - avatar
+ 6
Your going beyond the limits of what you have assigned in your array. You set the array length to 100 and then set the first 11 values leaving the rest as junk. Instead you can use r the set the size of the array and then change your condition in the for loop to loop while the index value is less than the size of the array. This will prevent the output of garbage. #include <iostream> using namespace std; int main() { int r=10; int arr[r]; for(int t = 0; t < r; t++) { cin >> arr[t]; } for(int j = 0; j < r; j++) { cout << arr[j] << endl; } return 0; }
5th Oct 2017, 6:18 AM
ChaoticDawg
ChaoticDawg - avatar
+ 4
lol, looks like you changed your code.
5th Oct 2017, 6:18 AM
ChaoticDawg
ChaoticDawg - avatar
+ 4
This will fix your second attempt: #include <iostream> #include <string> using namespace std; int main() { string arr; getline(cin, arr); // get the string before you attempt to get the length of it int r = arr.length(); for(int j = 0; j < r; j++) { // change <= to < cout << arr[j] << endl; } return 0; }
5th Oct 2017, 6:22 AM
ChaoticDawg
ChaoticDawg - avatar