Click here to Skip to main content
15,792,870 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
i want to scan 8 values from screen like - 1 2 3 4 5 6 7 8 and i want to print the sum of those 8 values and have to use array ...

#include "stdafx.h"
#include <stdio.h>
#include <math.h>

#define MAX_ITEM 8

int main()
	double x[MAX_ITEM],
	int i;
	printf("enter 8 number seprated by blank ");
	scanf_s("%lf", &x[0]);
	sum = 0;
	for (i = 0; i <= MAX_ITEM; i++);
	sum += x[i];

	printf("sum  = %lf \n", &sum);
Sergey Alexandrovich Kryukov 28-Dec-15 23:26pm    
"Like" does not define what and how you want to "scan". An example is not the definition.
What's the problem?

Hi, I feel removing semicolon (;) at the end of for should work.
for (i = 0; i <= MAX_ITEM; i++)
	sum += x[i];

Hariharasudhan C
Share this answer
The problem is that you only ever initialise the value of one element of your array. You should scan each value in turn inside your loop, ensuring that your loop ends when i is equal to MAX_ITEM. You also need to flush the input stream after each number, to clear the line end characters. So you should end up with something like:
int i;
sum = 0.0; // clear the sum
for (i = 0; i < MAX_ITEM; i++) // ensure loop ends after MAX_ITEM elements
    printf("enter a number: ");
    scanf_s("%lf", &x[i]);     // get next value
    fflush(stdin);             // clear the input buffer
    sum += x[i];               // add to the sum
printf("sum  = %lf \n", sum);

As you can see the array x is not really necessary in this case as it is never used after reading a value. A single variable would do the job.
Share this answer
Member 12202551 29-Dec-15 23:43pm    

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900