Home > Blockchain >  Find Largest Positive Even Number in C with help of Loops and Printing Relevant message if there is
Find Largest Positive Even Number in C with help of Loops and Printing Relevant message if there is

Time:07-27

Write a program to input 10 numbers and find the largest positive even number .In case no such number is present a relevant message should be printed. I'm stuck while writing the code for printing the relevant message (if there is no such number present). What to do ?

Here's how I tried...

#include <stdio.h>

int main(){
    int a,lar;
    printf("Enter the first number");
    scanf("%d",&a);
    lar = a;
    for (int i = 2; i <=10; i  )
    {
        printf("Number %d : ",i);
        scanf("%d",&a);
        if (a > 0 && (a % 2) == 0)
        {
            if (a > lar)
            {
                lar = a;
            }
        }
    }
    printf("The largest positive even number is : %d",lar);
}

Also the code is returning wrong value if I enter all odd numbers.

CodePudding user response:

You can use "lar" as a flag showing whether there was a positive even number in the input or not. To do that, you set it first to a negative number (e.g. -1). If there is even a single positive even number in the input, that number will overwrite lar and it won't be negative at the end of the loop.

#include <stdio.h>

int main(){
    int a,lar;
    lar = -1; 
    for (int i = 1; i <=10; i  )
    {
        printf("Number %d : ",i);
        scanf("%d",&a);
        if (a > 0 && (a % 2) == 0)
        {
            if (a > lar)
            {
                lar = a;
            }
        }
    }

    if(lar > 0)
    {
        printf("The largest positive even number is : %d",lar);
    }
    else
    {
        print("There are no positive even numbers.")
    }
}
  • Related