C Tutorial Part 5- User Input

C Tutorial Part 5- User Input

Welcome back to Cercomp's C tutorial post series (also being the first) but without further ado, let's get started with today's tutorial.

Now, you all must be thinking what is the function of variables if they are being used to only print answers, and that too, within the code. SO Today I bring you one of the main components of creating a fully fledged program, user input. User input is by far one of the most interesting things you ever learn in any programming language. It actually allows the program to interact with the user and perform functions to the user's requirement. So let us learn how to take user input.


1. First of all, began your program with the header and main statements like you always do.
NOTE- I won't be repeating this in succeeding blogs as you might have grown quite familiar with it.

2. Now create any variable you like. (in this post, I will be taking both character and numeric variables seperately)



3. Print a line for user to see.
example- printf ("enter a number ");


PS- The extra space after 'number' is included so that the user input does not stick to 'number'.

4. Now that we have requested the user to enter a number, let us understand how to take in a number, or any variable, as the matter of fact.

The syntax for user input is known and written as scanf. It is quite similar to the printf syntax as-

  • It also has ("").
  • It also uses variable representations for variables like- %d for numeric variables,%c for character variables and %s for string variables.
A scanf statement for taking in a number is as follows-:
scanf ("%d", &a);

First is the syntax, scanf.
Next, we %d under the inverted commas, which is a representation of the variable 'a' after the inverted commas. It is compulsory to add '&' before any variable during the scanf command. It has its ending with a semicolon as it is a function. Refer to the screenshot below. Tap or click on it for better view.


5. So once the user has given input and you have a value for variable a, show the user his or her input in the next line. Consider anything, like - printf ("The number you entered is %d\n",a); and end the program with return 0;


PS- The scanf command automatically leaves a line.

6. Now save and compile the program.
Below is a clip of it running-


If you have any queries or wish to donate, go to - https://cercomp.blogspot.com/p/cercomp-contact-info.html

Comments

Popular Posts