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; }