how to take input in C
To take input in C, you can use the scanf
function. Here's how you can do it:
Include the necessary header file at the beginning of your program:
c #include <stdio.h>
Declare variables to store the input:
c int num; char name[20];
Use the
scanf
function to read input from the user: ```c printf("Enter a number: "); scanf("%d", &num);
printf("Enter your name: "); scanf("%s", name); ```
In the above code, %d
is the format specifier for an integer, and %s
is the format specifier for a string. The &
operator is used to get the address of the variable where the input should be stored.
- You can now use the input in your program as needed:
c printf("You entered: %d\n", num); printf("Your name is: %s\n", name);
The printf
function is used to display the input back to the user.
That's it! You have successfully taken input in C using the scanf
function. Remember to include error handling and validation for user input to ensure your program behaves as expected.