Varga Sándor Varga Sándor - 2 months ago 8
C Question

Need help breaking down code to smaller parts C

I'm pretty new to C so be gentle, somewhy my code doesn't work, be kind and help my figure it out why it doesn't, also if it's possible to make it shorter without making it too complicated, please help in that too.

main.c

#include <stdio.h>
#include <stdlib.h>
#include "swap.h"
#include "magic.h"

int main(int argc, char *argv[])
{
int i,j,count;
int min=atoi(argv[1]);
int max=atoi(argv[2]);

if(min>max)
{
swap(&min, &max);
}

if (min<0)
{
min=1;
}

if(argc<2 || argc>5){exit(EXIT_FAILURE);}
else
{
magic();
}

}


Magic.c

#include <stdlib.h>
#include <stdio.h>
#include magic.h

magic(char *argv[])
{
for(i = min; i<=max; i++)
{

count = 0;

for(j=2; j<=i/2; j++)
{
if(i%j==0)
{
count++;
break;
}
}

if(count==0 && i!= 1 && i!= 0)
printf("%d \n",i);
}

return 0;
}

Answer

this is as single file for simplicity

#include <stdio.h>
#include <stdlib.h>

void swap(int *a,int *b){
    int c=*a;
    *a=*b;
    *b=c;
}

void magic(int min, int max);

int main(int argc, char *argv[])
{
    int min,max;

    if(argc!=3) // (argc<2 || argc>5)
        exit(EXIT_FAILURE);

    min=atoi(argv[1]);
    max=atoi(argv[2]);

    if(min>max)
        swap(&min, &max);

    if (min<0)
        min=1;

    magic(min,max);

    return EXIT_SUCCESS;
}


void magic(int min, int max){
    int i,j,count;

    for(i = min; i<=max; i++){
        count = 0;

        for(j=2; j<=i/2; j++) {

            if(i%j==0){
                count++;
                break;
            }
        }

        if(count==0 && i!= 1 && i!= 0)
            printf("%d \n",i);
    }
}
Comments