Read the age and weight of 5 people. Calculate the sum of the ages of people over
70 Kg

#include <stdio.h>
int i, age, weight, sum;
main()
{
for( i=0; i<5; i++)
{
printf("Age: ");
scanf("%d",&age);
printf("weight (ex: 92.5): ");
scanf("%d",&weight);
if(weight>70)
sum=sum+age;
}
printf("\age sum: %d", sum);

return(0);
}

Are you having specific problems?

  1. Avoid using globals like that.
  2. main is defined as int main(void). The int part is NOT optional.
  3. scanf is dangerous.
  4. Indent your code properly.

scanf is dangerous.

would you please explain why scanf is dangerous for getting input to numbers. if it is dangerous then what function should be used for getting input to numbers.

weight (ex: 92.5):

if So , then why don't you decalre weight as float type.

Would you please explain why scanf is dangerous for getting input to numbers.

Of course. http://c-faq.com/stdio/scanfprobs.html . I don't think they even bother to go into the different specifics that can happen, but they give a good overview.

what function should be used for getting input to numbers.

Sure, I wrote this a while ago (not that I'm not using globals, and int returns an integer like it should):

#include <stdio.h>
#include <string.h>

int
main(void)
{
    /* The name of the user. */
    char name[32];

    /* The age of the user. */
    int age;

    /* This will hold the string that the user enters for his age. */
    char age_buffer[32];

    printf("Name: ");

    /* fgets will saftly read up to sizeof(name) characters into name.
       It returns NULL if there is an error reading the name (for example,
       if stdin is somehow closed while the program is running).
       Note that this will also read in the newline character, unlike
       scanf. This is what was causing your problem. */
    if (fgets(name, sizeof(name), stdin) == NULL) {
        printf("ERROR: Cannot read name.");
        return 1;
    }

    /* Since we've read in the newline, we need to remove it so it
       prints nicely. */
    if (name[strlen(name) - 1] == '\n') {
        name[strlen(name) - 1] = '\0';
    }

    printf("Age: ");

    /* Same thing is going on here. Remember that it reads the age as a
       string however. We need to convert it into an integer. */
    if (fgets(age_buffer, sizeof(age_buffer), stdin) == NULL) {
        printf("ERROR: Cannot read age.");
        return 1;
    }

    /* sscanf is an easy way to do that. It returns the number of     
       arguments succesfully read. */
    if (sscanf(age_buffer, "%d", &age) != 1) {
        printf("ERROR: Age entered is not a number.");
        return 1;
    }

    printf("Hello %s, aged %d.\n", name, age);

    return 0;
}

You can read the returned value when using scanf or fscanf, to see if an appropriate value was 'scanned in':

http://developers-heaven.net/forum/index.php/topic,2022.0.html

int getValidInt( const char prompt[] )
{
    for( ; ; ) /* an example of a C/C++ forever loop ... until 'return' */
    {
        int numGood, testInt;
        fputs( prompt, stdout ); fflush( stdout );
        numGood = fscanf( stdin, "%d", &testInt );
        while( getchar() != '\n' ); /* 'flush' stdin ... as we go ... */
        if( numGood == 1 ) return testInt;
        /*else ...*/
        puts( "Invalid input! Integers only please ..." );
    }
}

Or ...

/* takeInValidInt.c  */ /* 2013-05-29 */

/* http://developers-heaven.net/forum/index.php/topic,46.0.html */

#include <stdio.h>
#include <ctype.h>

int takeInValidInt( const char prompt[] )
{
    for( ; ; ) /* an example of a C/C++ forever loop ... until 'return' */
    {
        int numGood, testInt;
        printf( prompt ); fflush( stdout );
        numGood = scanf( "%d", &testInt );

        if( getchar() == '\n' )
        {
            if( numGood == 1 ) return testInt;
            /*else ...*/
            puts( "Invalid input! Integers only please ..." );
        }
        else 
            puts( "Integers only please ... NO extra char's permitted at end." );

        while( getchar() != '\n' ); /* 'flush' stdin ... as we go ... */
    }
}

char takeInChar( const char* msg )
{
    char chr;
    printf( msg ); fflush( stdout );
    chr = getchar();
    if( chr != '\n' ) while( getchar() != '\n' ) ; /* flush stdin ... */
    return chr;
}


int more() /* defaults to 'true'/'yes'/'1' ... unless 'n' or 'N' entered */
{
    if( tolower( takeInChar( "\nMore (y/n) ? " )) == 'n' ) return 0;
    /* else ... */
    return 1;
}



int main()
{
    int count = 0;
    double sum = 0;
    double average = 0;

    do
    {
        int testInt = takeInValidInt( "Enter next integer to sum: " );

        printf( "You entered: %d, ", testInt );

        if( tolower( takeInChar( "Ok to accept (y/n) ? " )) == 'y' )
        {
            ++count;
            sum += testInt;
        }
        else printf( "\nAborted ... %d was NOT used here.\n", testInt );
    }
    while( more() ); /* make sure stdin is 'empty' before calling 'more()' */

    if( count ) average = sum/count;

    printf( "\nFor %d numbers entered, sum was %.0f and average was %.2f\n",
            count, sum, average );

    fputs( "\nPress 'Enter' to continue/exit ... ", stdout); fflush( stdout );
    getchar(); /* keep 'Window' open until 'Enter' key is pressed ... */

    return 0;
}

Actually ... I like this for 'simple student type validation' of keyboard user input of integers ...

int takeInValidInt( const char prompt[] )
{
    for( ; ; ) /* an example of a C/C++ forever loop ... until 'return' */
    {
        int numGood, extraChars, testInt;
        printf( prompt ); fflush( stdout );
        numGood = scanf( "%d", &testInt );
        extraChars = ( getchar() != '\n' );

        if( numGood == 1 && !extraChars ) return testInt;

        if( !numGood )
            puts( "Invalid input! Integers only please ..." );
        else if( extraChars )
            puts( "NO extra char's permitted at end." );

        while( getchar() != '\n' ); /* 'flush' stdin ... as we go ... */
    }
}
Member Avatar for atulgupta9

It looks everyone has got deviated from the original question posted by the user . Hey if you want to enter age and weight of 5 persons why don't you use the concept of arrays. It's simple
I will first provide you with the code

#include<stdio.h>
int main()
{
int age[5],weight[5];

//age and weight are integer arrays having 5 members each age[0],age[1]...age[4]

int i;

//INPUT AGE WEIGHT

for(i=0;i<5;i++)
{
 printf("\nEnter age of the person\n");
 scanf("%d",&age[i]);
 printf("\nEnter weight of the person\n");
 scanf("%d",&weight[i]);

 }
 //CHECK WEIGHT AND ADD AGE
 int sum=0;
 for(i=0;i<5;i++)
 {
  if(weight[i]>70)
  sum=sum+age[i];
  }
  printf("The sum of the ages of people over 70kg is %d",sum);
  return 0;
  }

Arrays are used to store elements having same datatype

I think using arrays would be a better choice as atulgupta suggested.

Hey if you want to enter age and weight of 5 persons why don't you use the concept of arrays.

if you read the question carefully , the OP want to calculate the total of ages of such who are having above 70kg weight.Here , The use of array is not required since it isn't necessary to store it in an array. And i'd say that in this case , don't use array because it will cover a chunk of memory which is larger than single weight and age variable.

your code will require 5*4=20bytes for age array and similarly 5*4=20bytes for weight array(Size of variable is compiler dependent , i think so).The same requirement can be fulfilled with single age and weight variable(4 byte each).In this case i prefer the way that the OP used.

you might also consider to use float for floating point values.therefore, use weight variable as float rather than integer.

I think using arrays would be a better choice as atulgupta suggested.

How ?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.