Sunday 22 September 2013

Input/Output Constructs

The second most important feature to know about in while learning any programming language. Input/Output is the way through which we will be interacting with the user. And this forms an integral part of any program that we write. We will be seeing the two most basic constructs in this post. scanf and printf. scanf is for taking input from the user using the standard input device, generally the keyboard and printf is for printing output on the console output. In most cases this is the screen of your machine, but it can be routed to your printer or a file too.

scanf


scanf stands for scan formatted string. It is the most commonly used method for input in C. Using scanf, we can accept any type of input. The syntax for input is as so:



In this the format string depends on the type of input that we want to accept from the user. A list of format strings is shown below.



The format strings can be nested. That is we can accept multiple variables in the same scanf statement.

Some examples of scanf are as so:



Note: Whenever accepting a variable from the user you need to put the & operator (address of operator -- we will be learning more about it) before the variable name. This passes the address to the scanf function so that it can store the value that was input by the user in that address. You don't need to put that when accepting a string because the name of the string is the name of an array and the name of an array stores a pointer to the address of the first element on the array. None of this should make sense to you right now. It will make much more sense when we get started on pointers.

printf

The most common way to print things on the screen for the user to read. It works in a very similar way to scanf. printf stands for print formatted string. And the format strings are the same. Here while printing a variable you don't need to put the ampersand before it. Not for variables and not for arrays.

Some examples are shown below:



In this post, we looked at the basic I/O constructs that C provides. Now, we are well equipped to write a program of basic utility. And we will start up on the coding! Yippee!

No comments:

Post a Comment