Home > Mobile >  Void function usage issue, I'm new to C
Void function usage issue, I'm new to C

Time:07-01

the task is to print ascending order numbers using only void function. Any insight on what's wrong with the code? Explanation too would be appreciated

#include<stdio.h>
void listNumbersAsc(int start, int end);
int main()
{
    int x,y;
    printf("Enter the range of numbers maintaining start at first and end at second:");
    scanf("%d%d",&x,&y);
    
   listNumbersAsc(x, y);
}
void listNumbersAsc(int start, int end){
    
    int i,s,e;
    
    if(start>=end){
        s=start;
        e=end;
    }
    else{
        s=end;
        e=start;
    }
    
    for(i=s; i<=e; i  ){
        printf("%d",i);
    }
}

CodePudding user response:

This should work:

#include<stdio.h>
void listNumbersAsc(int start, int end);
int main()
{
    int x,y;
    printf("Enter the range of numbers maintaining start at first and end at second:");
    scanf("%d %d",&x,&y);

   listNumbersAsc(x, y);
}
void listNumbersAsc(int start, int end){
    
    int i,s,e;
    
    if(start<=end){
        s=start;
        e=end;
    }
    else{
        s=end;
        e=start;
    }

    for(i=s; i<=e; i  ){
        printf("%d ",i);
    }
}

You if statement in listNumbersAsc function wasn't correct.

Also added a space between two %d in scanf("%d %d",&x,&y) to separate two numbers.

CodePudding user response:

The problem of the function is that this for loop

for(i=s; i<=e; i  ){
    printf("%d",i);
}

can be executed inly once if initially start is specified equal to end due to this if statement

if(start>=end){
    s=start;
    e=end;
}
else{
    s=end;
    e=start;
}

That is due to this if statement start can not be less than end.

Also there are redundant variables in the function

The function can be defined the following way

void listNumbersAsc( int start, int end )
{
    if ( end < start )
    {
        int tmp = start;
        start = end;
        end = tmp;
    }

    do
    {    
        printf( "%d ", start );
    } while ( start   != end );
    putchar( '\n' );
}

Pay attention to that this loop

for(i=s; i<=e; i  ){

shown in your question and in the other answer is in general wrong. If the user will specify the value INT_MAX for the parameter end then the loop can be infinite.

  • Related