Click here to Skip to main content
15,914,323 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 ...

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

#define MAX_ITEM 8

int main()
{
	double x[MAX_ITEM],
		sum;
		
	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);
Posted
Comments
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?
—SA

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



Thanks
Hariharasudhan C
 
Share this answer
 
v2
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:
C++
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
 
Comments
Member 12202551 29-Dec-15 23:43pm    
thanks

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