Can anyone please explain me the following:

1. First Example:

int i = get_int ("Integer:");  
printf ("hello,%i"\n", i);

In this example near the % operator we use the declared variable "i". The "i" variable stores data and prints the stored data instead of "%i".

1. Second Example:

int x = get_int("x: ");  
int y = get_int("y: ");  
printf("%i  plus  %i  is  %i\n",  x, y, x+y );

Here @ 47: 05, near the % sign, we also use a variable, but it is not declared: In this example declared only 2 variables x and y, but not "i". But near the % operator we use not declared variable "i". Why we are not using here the declared variables x and y, as in the first example?

  1. Can we use near the % operator only declared variables?
  2. If yes, why we are using in the second example something, that is not declared previously ?

Thank you in advance


Great question.

When you call the printf function, it takes in a string format as a parameter. The % within this string tells the printf function what datatype to look for and to print.

See https://reference.cs50.net/stdio/printf where it explains how the %i, %c and other datatypes can be referenced in a printf function.

So to give an example:

When you declare a variable i and call printf:

int i = 1;
printf("%i\n", i);

The %i is not related to the name of the variable you declared. The i after your comma, would refer to your declared variable i. %i refers to the datatype integer.

You could have easily declared:

int num = 1000;
printf("%i\n", num);

Thus, in your example of x & y, everytime you are going to print a variable, you use %i to tell the printf function to insert an integer - which could be a variable or a manual entry of a number (ie. 1001), or in your latter case, the sum of two integer variables x + y.

  • wlh is right. Think of it this way. Each % followed by a letter (or multiple letters and numbers, you'll learn later) is a placeholder for a variable. The placeholders correspond, in sequence, to the variable names that follow. The simplest forms are %i, %c, %f, etc. They can also contain numbers and other qualifiers that will define how the variable will be displayed. In other words, they are formatting characters.
    – Cliff B
    Mar 24 '18 at 2:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .