I just started learning programming. Got a problem:
Write a program that creates two eight-element arrays of double type and uses a loop to enter the values of the eight elements of the first array. The program should accumulate in the elements of the second array the sum of the first array with a cumulative total. For example, the fourth element of the second array should be equal to the sum of the first four elements of the first array, and the fifth element of the second array should be the sum of the first five elements of the first array. (This can be done using nested loops, but if we take into account the fact that the fifth element of the second array is equal to the fourth element of the second array plus the fifth element of the first array, you can avoid nested loops and use a single loop to solve the problem.) Finally, use the loop to output the contents of both arrays; the first array should be displayed in the first row, and each element of the second array should be placed directly under the corresponding element of the first array.
Here is the execution code:
#include <stdio.h> int main(void) { const int size=8; double mass1[size],mass2[size],mass3[size]; int i,j; //первый массив for(i=0;i<size;i++) //ввод значений пользователем в первый массив { printf("Give me %d num: ",i+1); scanf("%lf",&mass1[i]); } //второй массив //создание второго массива без помощи встроенного цикла for(i=0;i<size;i++) { mass2[i]=mass1[i]+mass2[i-1]; } //создание второго массива методом вложенного цикла //для этого создам еще 1 массив, для удобства вывода for(i=0;i<size;i++) { for(j=i;j>=0;j--) { mass3[i]+=mass1[j]; } } //нужен один цикл для вывода всех массивов //сделаю несколько т.к. не знаю пока как все сделать через 1 цилк for(i=0;i<size;i++) { printf("%.1lf |",mass1[i]); } printf("\n"); for(i=0;i<size;i++) { printf("%.1lf |",mass2[i]); } printf("\n"); for(i=0;i<size;i++) { printf("%.1lf |",mass3[i]); } printf("\n"); return 0; }
Question # 1 - the output of the second array is buggy from time to time (a million digits appear) - I assume that the expression: mass2 [i] = mass1 [i] + mass2 [i-1]; contains error because the value of mass2 [i-1] with i = 0 is unknown. Actually, I cannot understand in any way how to correctly make this cycle so that it correctly calculates according to the following scheme: mass2 [i] = mass1 [i] + mass2 [i-1] , but calculated correctly when i = 0.
Question number 2. How can I make a conclusion of both arrays, in which the elements of the second array are output under the corresponding order elements of the first array, via printf () using 1 cycle (you can nested)
It is worth noting, because This task is from the Stephen Prath textbook (Chapter 6 Exercise 14). Here you can use while, do while, for, and simple functions.