This C code calculates the sum of integers in an array and prints the result.
#include <stdio.h>
int main()
{
int numberArray[] = {1, 2, 3, 4, 5}; //15
int total = 0;
int lengthOfArray = sizeof(numberArray)/sizeof(numberArray[0]);
for (int x = 0; x < lengthOfArray; x++)
{
//printf("Total atm: %d \n", total);
total = total + numberArray[x];
printf("Total atm: %d \n", total);
}
printf("Total sum of all integers: %d", total);
return 0;
}
Result:
Total atm: 1
Total atm: 3
Total atm: 6
Total atm: 10
Total atm: 15
Total sum of all integers: 15
Process returned 0 (0x0) execution time : 0.031 s
Press any key to continue.
Explanation:
#include <stdio.h>
This line includes the standard input/output library, which provides functions for printing to the console.
int main()
{
int numberArray[] = {1, 2, 3, 4, 5}; //15
This line declares an integer array named numberArray
and initializes it with the values 1, 2, 3, 4, and 5.
int total = 0;
This line declares an integer variable named total
and initializes it to 0. This variable will be used to store the sum of the integers in the array.
int lengthOfArray = sizeof(numberArray)/sizeof(numberArray[0]);
This line calculates the length of the array by dividing the total size of the array (in bytes) by the size of one element in the array (also in bytes). This gives the number of elements in the array.
for (int x = 0; x < lengthOfArray; x++)
{
total = total + numberArray[x];
printf("Total atm: %d \n", total);
}
This is a loop that iterates over each element in the array, calculates the sum of all elements, and prints the current sum to the console after each iteration. The loop variable x
is used as an index to access each element in the array, and the total
variable is updated with each element as the loop progresses.
printf("Total sum of all integers: %d", total);
This line prints the final sum of all elements in the array to the console.
return 0;
}
This line ends the main function and returns 0 to indicate that the program has completed successfully.
No comments:
Post a Comment