0

Program to print the number of elements of an array whose size is not defined and also to print the sum of the array elements

I have written a program for the above-mentioned problem as mentioned below. The program can be divided into two parts. (A) To Print the number of elements (B) To Find the sum of the array elements If I am writing only part A in the code i.e. I am only printing the number of elements of the array and not doing part B i.e. to print the sum, it gives an output of 6 as the number of elements in the array. But if write both the parts in the program, it gives me an output of 8 although the number of elements in the array is 6. It also shows garbage values, which results into the sum of the array elements being wrong. Can anyone please check the code and explain if there is anything wrong? Thanks in advance. #include <iostream> using namespace std; int main() { int sum = 0, n = 0; int myArray[] = {65, 76, 100, 89, 777, 90}; //Finding the number of elements cout << "The Array elements are: " << endl; do{ cout << myArray[n] << endl; ++n; }while(myArray[n] != '\0'); cout << "The number of elements is: " << endl; cout << n << endl; //Finding the sum of elements for (int i = 0; i<n; i++) { sum += myArray[i]; } cout << "The Sum of myArray elements is: " << sum << endl; return 0; }

31st Jul 2017, 3:18 AM
Kalliath Abdul Rasheed Shamil
Kalliath Abdul Rasheed Shamil - avatar
3 Respostas
+ 5
code is right i didn't find any error while compiling and its givings true output
31st Jul 2017, 3:43 AM
Mrunali
Mrunali - avatar
+ 1
Im pretty sure the issue is in your do-while loop, you are iterating over n, but the condition you are using to stop is (myArray != '\0'), intuitively this seems wrong because if you go beyond the size of your array the values dont become \0. Why dont you do the same thing you did later on with the for loop
31st Jul 2017, 3:40 AM
S C
0
Thank you for your replies. I have changed the do-while loop to for-loop with the same conditions as the do-while loop. Now the code is working. :) for (i = 0; myArray[i] != '\0'; i++) { cout << myArray[i] << endl; } n = i;
31st Jul 2017, 3:54 AM
Kalliath Abdul Rasheed Shamil
Kalliath Abdul Rasheed Shamil - avatar