Click here to Skip to main content
15,889,462 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
Read in an integer N. Then read in N numbers and print their maximum and
second maximum (do not use arrays use loops) in c languange


What I have tried:

#include<stdio.h>

    int main(){
    
    int n,max,min;
    printf("Enter n: ");
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        scanf("%d",&i);
        if(n>max){
            n=max;
        }else{
            n=min;
        }
        printf("Max= %d\n",max);
        printf("min= %d\n",min);
    }
    
    return 0;
}
Posted
Updated 25-May-21 3:11am
Comments
KarstenK 26-May-21 2:38am    
Do the print after the loop. (not in it)

This is homework, so I'll give you no code.

Create two variables : max1 and max2.
Set both of them to the minimum possible value: if you include the LIMITS.H header file, you will find it is defined as INT_MIN.
Inside your loop, compare the current value to max1. If it's greater, then set max2 to max1 and set max1 to the current value
Otherwise, compare the current value and max2. If it's greater, then set max2 to teh current value.
After the loop, you have the two biggest values in max1 and max2
 
Share this answer
 
Comments
Ajay Jarwal 25-May-21 6:40am    
no it is not a homework, I a beginner just practicing some ques, can you send code, not able to solve properly!
OriginalGriff 25-May-21 6:50am    
And what would that achieve?
You are a beginner, so what - exactly - would you learn from my writing code?
Would you learn how to do it yourself? Probably not.

Give it a try: this is a pretty simple exercise!
Ajay Jarwal 25-May-21 9:11am    
what is this header file LIMITS.H? I have tried this but result not coming!
OriginalGriff 25-May-21 10:39am    
See here:

https://www.tutorialspoint.com/c_standard_library/limits_h.htm
if you use the debugger you may have seen the missing if and buggy assigment.
C++
if(n>max){
    n=max;
}else if(n<min){
    min=n;
}
 
Share this answer
 
// find maximun and minimun in n numbers
#include<stdio.h>

    int main(){
    
    int a,min=5,max=0,i=0,n;
    printf("Enter n: ");
      scanf("%d",&n);

   for(i=0; i<n; i++){
       printf("enter the numbers: ");
      scanf("%d",&a);
   }
       if (a > max){ 
           max=a; 
       }
        else if(a < min) {
           min=a; 
       }
        printf("max=%d\n",max);
        printf("min=%d\n",min);
    
    return 0;
}
 
Share this answer
 
Comments
OriginalGriff 25-May-21 10:39am    
I'd strongly suggest two things:
1) Check your code with this set of numbers: {-6, -5, -3}
2) Read your homework question again carefully: pay attention to the bit which talks about print the "minimum" ... look closely at the specific wording.

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