+ 2

Problem based on array

You have been given an array of positive integers A1,A2,...,An with legnth N and you have to print an array of same legnth(N) where the values in the new array are the sum of every number in the array, except the number at that index. #include<stdio.h> #define MAX 10 int main() { int n; int a[MAX]; int b[MAX]; printf("Enter the no of arr elements: "); scanf("%d", &n); printf("Enter the arr elements:\n"); for(int i = 0; i < n; i++) { printf("A[%d]: ", i); scanf("%d", &a[i]); } for(int i = 0; i<n; i++) { for(int j = 0; j<n; j++) { while(i != j) { b[j] += a[i]; } } } for(int i = 0; i<n; i++) { printf("\n%d", b[i]); } return 0; } Please help and let me know what's wrong with my logic!

14th Oct 2021, 6:00 AM
Harshit Rao
6 odpowiedzi
+ 4
Harshit Rao Here's the logic for the second loop for(int i = 0; i<n; i++) { b[i] = 0; for(int j=0; j<n; j++){ if(i!=j){ b[i] += a[j]; } } }
14th Oct 2021, 6:20 AM
Kashyap Kumar
Kashyap Kumar - avatar
+ 2
Can you provide sample inputs and outputs
14th Oct 2021, 6:04 AM
Kashyap Kumar
Kashyap Kumar - avatar
+ 1
Sample Input: 5 //no of array elements 12 // array elements 4 6 8 9 Sample Output: 27 35 33 31 30
14th Oct 2021, 6:11 AM
Harshit Rao
+ 1
Unfortunately you pasted the snippet as raw text. There's no way to point line numbers this way. You see the `while` in the nested for loop? replace that by `if` And make sure all elements of array <b> has value zero before modifying their values. Next time please, attach a code bit link so we can easily refer line numbers. https://www.sololearn.com/post/75089/?ref=app
14th Oct 2021, 6:19 AM
Ipang
+ 1
Harshit Rao To be more efficient and aviod the second loop being executed n times: sum = 0; for(int i=0; i< n; i++) { sum += a[i]; for(int i=0; i<n ;i++) { b[i] = sum - a[i]; }
14th Oct 2021, 11:06 AM
Paul K Sadler
Paul K Sadler - avatar
+ 1
Thanks you everyone!
14th Oct 2021, 6:39 PM
Harshit Rao