2

I'm quite new to C and I was wondering if it is possible to have a variable be defined by an input by the user. I've made a simple prime number counter which shows all the prime numbers from 1 to 100 and I was wondering if there is a library or a code which allows me to define a variable by the user input. Here's my code for better understanding.

#include <stdio.h>

int main(void)
{
    for (int i = 2; i < 101; i++) { //I would want the "101" to be a user defined variable
        for (int j = 2; j <= i; j++) {
            if (i == j) {
                printf("%d\n", i);
            }
            else if (i%j == 0) {
                break;
            }
        }
    }
}

Thanks in advance!

4
  • 1
    Google argc(argument count) & argv(argument vector) Commented Sep 3, 2017 at 10:52
  • 1
    Do you want to get your input from the command line or by displaying a prompt to the user? Commented Sep 3, 2017 at 10:53
  • 2
    Learning C by trial&error or questions about very specific, particular issues is a really bad idea. Reading a commaon line argument or reading from stdin is explained in every beginner's C book. Commented Sep 3, 2017 at 11:21
  • As others mentioned, argv should be used for passing in input strings, and argc should be used to count/validate number of input string that your code expects as input. Commented Sep 3, 2017 at 15:46

2 Answers 2

2
#include <stdio.h>

int main(void) {
   int num;
   scanf("%d",&num); //to take a user input
 for (int i=2; i<=num; i++) //I would want the "101" to be a user defined variable
 {
  for (int j=2; j<=i; j++)
  {
    if (i == j)
      printf("%d\n",i);
    else if (i%j == 0)
      break;
  }
 }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for the help!
1

Yes, using user input in this way is possible. (It had better be possible! Virtually all programs work on user input.)

In general, there are two main ways of doing it. (1) read from the command line. (2) read from a "file" -- which might just be the user's keyboard.

Let's look at both of these in turn.

1. Read from the command line.

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

int main(int argc, char *argv[]) {
 int max;
 if(argc <= 1)
 {
  fprintf(stderr, "usage: %s max\n", argv[0]);
  exit(1);
 }
 max = atoi(argv[1]);
 for (int i=2; i<max; i++)
 {
  for (int j=2; j<=i; j++)
  {
    if (i == j)
      printf("%d\n",i);
    else if (i%j == 0)
      break;
  }
 }
}

To read from the command line, we declare main with two arguments: argc and argv. When main gets called, argc will be a count of how many arguments there are, and argv will contain those arguments. argv is an array of strings, or more precisely, an array of pointers to char, or char *. Also, the first argument will always be the name of the program.

We want the user to type

name_of_the_program 200

to print primes up to 200. So we make sure that the user typed at least one argument, that is, we complain if argc isn't at leaast 2: one for the name of the program, 1 for the argument the user typed. Assuming the user did type an argument, it'll be in argv[1]. (argc[0] is the program name.) The command-line arguments are always passed as strings, but we want a number, an int. So we call atoi to convert the string on the command line (like "200") to an int (like 200).

2. Read from a file.

In this case, the "file" we're going to read from is stdin, the standard input, which by default is the user's keyboard.

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

int main(void) {
 int max;
 char input_line[100];
 printf("How high to go? "); fflush(stdout);
 fgets(input_line, 100, stdin);
 max = atoi(input_line);
 if(max == 0)
 {
  fprintf(stderr, "try typing a number next time\n");
  exit(1);
 }
 for (int i=2; i<max; i++)
  ...

We print a prompt to tell the user what we need him to type. We call

 fgets(input_line, 100, stdin);

to read one line of input -- that is, we expect the user to type some stuff, then hit RETURN. Since we declared input_line to be an array of 100 characters, it's important that we tell fgets how big it is, so that fgets can be sure not to put more than 100 characters into the array. (That could happen if the user, just to be ornery, typed 100 or more characters before hitting RETURN.)

Similarly to the command line case, we've read input_line as a line of text, a string. So we call atoi again, to convert that string to an int. Also, we make sure that the number is not 0. If the user types "abc" or something, that isn't even a number, atoi will return 0, and we catch that, since we'd never want to try to print prime numbers up to 0.

[P.S. As an alternative to the fgets plus atoi technique I've presented here, another popular method is the scanf function (as illustrated, in fact, in another answer to this question). You can use scanf, and it even seems pretty easy at first, but in the long run it's harder, and there are a bunch of things it doesn't handle at all well. So I recommend learning how to use fgets and friends as soon as you can.]

1 Comment

If no argument is provided on the command line, your first example could default to 100 as the limit (or any other suitable value), rather than demanding an argument. Both approaches are legitimate — it depends on what the program is used for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.