Click here to Skip to main content
15,886,258 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I'm new and we've got an assignment to make a program that will accept 10 int and prints the sum of all odd nos and product of even nos. entered. My problem output error occurs everytime I enter a 2 digit number and 2 digit number with zero. Here's the code my friend and I did.
Note: we use turbo c
C++
#include<stdio.h>
#include<conio.h>
void main()
{
    int a[50],i,even[50],odd[50],sum=0,prod=1;
    clrscr();
    printf("Enter 10 integers:");
    for(i=0;i<10;i++)
    {
        scanf("%d",&a[i]);
    }
    
    for(i=0;i<10;i++)
    {
        if(a[i]%2==0)
        {
           even[i]=a[i];
           prod=prod*even[i];
        }
    }
   
    for(i=0;i<10;i++)
    {
        if(a[i]%2!=0)
        {
            odd[i]=a[i];
            sum=sum+odd[i];
        }
     }
     printf("\nSum of odd numbers is %d\n",sum);
     printf("\nproduct of even numbers is %d\n",prod);

     getch();
}
Posted
Updated 27-Sep-15 6:26am
v2

I run it, it works.
I run it with zeros: it works
I run it with double digit numbers - it works.

So what is the problem? The only hassle I can see is that your output are a bit odd: your array collections of odd and even numbers are unnecessary and not good since you only set the indexes where you meet them.
By the way: you don't need three loops: You can use two, or even one.
C++
void main()
{
    i,value,sum=0,prod=1;
    clrscr();
    printf("Enter 10 integers:");
    for(i=0;i<10;i++)
    {
        scanf("%d",&value);
        if(value % 2 == 0)
        {
           prod=prod*value;
        }
        else
        {
            sum=sum+value;
        }
     }
     printf("\nSum of odd numbers is %d\n",sum);
     printf("\nproduct of even numbers is %d\n",prod);
 
     getch();
}
 
Share this answer
 
The first question is, why do you store the numbers in an array? Is that a requirement? If not, why not simply decide if the number is even or odd when the input is made and based on that calculate intermediate result for either sum or product.

Another thing is that if you use arrays the probability is that the indexer for even array is different from indexer of a. For example if a would be 1,2,3,4 then indexer for a would be 0 to 3 while the indexer for even would be 0 to 1 (if filled in order).

Otherwise looks good unless the product grows too much so that a long integer would be required along with ld in formatting of printf.
 
Share this answer
 
v2

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