954,505 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Error in output

Q.Write a function to accept upto 25 numbers and display highest and lowest number along with all the numbers.

Solution I tried

#include<stdio.h>
#include<conio.h>
void main()
{
int array[25],low,high;
int i;
clrscr();
do
{
  printf("Enter a number(0 to terminate)\n");
  scanf("%d",&array[i]);
}while(array[i]!=0);
i=0;
low=high=array[0];
while(array[i]!=0)
{
 if (low>array[i])
  low=array[i];
 else if(high<array[i])
  high=array[i];
 i++;
}
for(i=0;array[i]!=0;i++)
 printf("Numbers are %d",array[i]);
printf("Highest is %d,lowest is %d",high,low);
}


Problem is that I am not getting the desired output. For every input I tried, I got the output as highest is 0, lowest is 0.HELP!!!:sad: :!:

IwalkAlone
Light Poster
31 posts since Feb 2007
Reputation Points: 17
Solved Threads: 0
 

Some points:

1. Use code tags to post your indented code so that it is more readable.

2. The loop you use for input can easily cause buffer overflows if zero is not entered by the user. If you know the array size in advance, replace all the cumbersome while loops with the for loops and repost your updated code.

3. You did a mistake in placing the logic for finding out the highest in the else block. Place it in a seperate if block.

4. Initializing your variables will save you a lot of head banging in the future. Always initialize your variables before using them in such situations.

~s.o.s~
Failure as a human
Administrator
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
 

I made the following changes

[inlinecode][/inline code]
{
#include
#include
void main()
{
int array[5],low,high;
int i=0;
clrscr();
for(i=0;i<5;i++)
{
printf("Enter a number\n");
scanf("%d",&array[i]);
}
low=high=array[0];
while(array[i]!=0)
{
if (low>array[i])

low=array[i];

if(high

IwalkAlone
Light Poster
31 posts since Feb 2007
Reputation Points: 17
Solved Threads: 0
 

I still see a while loop in your code. On top of that the while loop uses the value of i which is 5 when the while block is entered (since you never reset it after the for loop).

Stop checking for the occurance of zero in the loop. Just make it like the loop you used for accepting user input.

~s.o.s~
Failure as a human
Administrator
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
 

Ya git it!! Thnx a lot!!!!

IwalkAlone
Light Poster
31 posts since Feb 2007
Reputation Points: 17
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You