Structure of C program, writing and
executing the first C program,
Before we study the basic building blocks of the C programming language,
let us look at a bare minimum C program structure so that we can take it as
a reference in the upcoming chapters.
Hello World Example
A C program basically consists of the following parts −
Preprocessor Commands
Functions
Variables
Statements & Expressions
Comments
Let us look at a simple code that would print the words “Hello World
#include <stdio.h>
int main() {
/* my first program in C */
printf("Hello, World! \n");
return 0;
}
Let us take a look at the various parts of the above program −
The first line of the program #include <stdio.h> is a preprocessor
command, which tells a C compiler to include stdio.h file before going
to actual compilation.
The next line int main() is the main function where the program
execution begins.
The next line /*…*/ will be ignored by the compiler and it has been put
to add additional comments in the program. So such lines are called
comments in the program.
The next line printf(…) is another function available in C which causes
the message “Hello, World!” to be displayed on the screen.
The next line return 0; terminates the main() function and returns the
value 0.
Compile and Execute C Program
Let us see how to save the source code in a file, and how to compile and run
it. Following are the simple steps −
Open a text editor and add the above-mentioned code.
Save the file as hello.c
Open a command prompt and go to the directory where you have
saved the file.
Type gcc hello.c and press enter to compile your code.
If there are no errors in your code, the command prompt will take you
to the next line and would generate a.out executable file.
Now, type a.out to execute your program.
You will see the output “Hello World” printed on the screen.
$ gcc hello.c
$ ./a.out
Hello, World!
Components of C language
You have seen the basic structure of a C program, so it will be easy to
understand other basic building blocks of the C programming language.
Tokens in C
A C program consists of various tokens and a token is either a keyword, an
identifier, a constant, a string literal, or a symbol. For example, the following
C statement consists of five tokens −
printf("Hello, World! \n");
The individual tokens are −
printf
(
"Hello, World! \n"
)
;
Semicolons
In a C program, the semicolon is a statement terminator. That is, each
individual statement must be ended with a semicolon. It indicates the end of
one logical entity.
Given below are two different statements −
printf("Hello, World! \n");
return 0;
Comments
Comments are like helping text in your C program and they are ignored by
the compiler. They start with /* and terminate with the characters */ as
shown below −
/* my first program in C */
You cannot have comments within comments and they do not occur within a
string or character literals.
Identifiers
A C identifier is a name used to identify a variable, function, or any other
user-defined item. An identifier starts with a letter A to Z, a to z, or an
underscore ‘_’ followed by zero or more letters, underscores, and digits (0 to
9).
C does not allow punctuation characters such as @, $, and % within
identifiers. C is a case-sensitive programming language.
Thus, Manpower and manpower are two different identifiers in C. Here are
some examples of acceptable identifiers −
mohd zara abc move_name a_123
myname50 _temp j a23b9 retVal
Keywords
The following list shows the reserved words in C. These reserved words may
not be used as constants or variables or any other identifier names.
auto else long switch
enu regist
break typedef
m er
exter
case return union
n
unsigne
char float short
d
const for signed void
continu
goto sizeof volatile
e
default if static while
_Packe
do int struct
d
double
Whitespace in C
A line containing only whitespace, possibly with a comment, is known as a
blank line, and a C compiler totally ignores it.
Whitespace is the term used in C to describe blanks, tabs, newline
characters and comments. Whitespace separates one part of a statement
from another and enables the compiler to identify where one element in a
statement, such as int, ends and the next element begins. Therefore, in the
following statement −
int age;
there must be at least one whitespace character (usually a space) between
int and age for the compiler to be able to distinguish them. On the other
hand, in the following statement −
fruit = apples + oranges; // get the total fruit
no whitespace characters are necessary between fruit and =, or between =
and apples, although you are free to include some if you wish to increase
readability
Standard I/O in C Language
When we say Input, it means to feed some data into a program. An input
can be given in the form of a file or from the command line. C programming
provides a set of built-in functions to read the given input and feed it to the
program as per requirement.
When we say Output, it means to display some data on screen, printer, or in
any file. C programming provides a set of built-in functions to output the
data on the computer screen as well as to save it in text or binary files.
The Standard Files
C programming treats all the devices as files. So devices such as the display
are addressed in the same way as files and the following three files are
automatically opened when a program executes to provide access to the
keyboard and screen.
Standard File
Device
File Pointer
Standard
stdin Keyboard
input
Standard
stdout Screen
output
Standard Your
stderr
error screen
The file pointers are the means to access the file for reading and writing
purpose. This section explains how to read values from the screen and how
to print the result on the screen.
The getchar() and putchar() Functions
The int getchar(void) function reads the next available character from the
screen and returns it as an integer. This function reads only single character
at a time. You can use this method in the loop in case you want to read more
than one character from the screen.
The int putchar(int c) function puts the passed character on the screen
and returns the same character. This function puts only single character at a
time. You can use this method in the loop in case you want to display more
than one character on the screen. Check the following example −
#include <stdio.h>
int main( ) {
int c;
printf( "Enter a value :");
c = getchar( );
printf( "\nYou entered: ");
putchar( c );
return 0;
}
When the above code is compiled and executed, it waits for you to input
some text. When you enter a text and press enter, then the program
proceeds and reads only a single character and displays it as follows −
$./a.out
Enter a value : this is test
You entered: t
The gets() and puts() Functions
The char *gets(char *s) function reads a line from stdin into the buffer
pointed to by s until either a terminating newline or EOF (End of File).
The int puts(const char *s) function writes the string ‘s’ and ‘a’ trailing
newline to stdout.
NOTE: Though it has been deprecated to use gets() function, Instead of
using gets, you want to use fgets().
#include <stdio.h>
int main( ) {
char str[100];
printf( "Enter a value :");
gets( str );
printf( "\nYou entered: ");
puts( str );
return 0;
}
When the above code is compiled and executed, it waits for you to input
some text. When you enter a text and press enter, then the program
proceeds and reads the complete line till end, and displays it as follows −
$./a.out
Enter a value : this is test
You entered: this is test
The scanf() and printf() Functions
The int scanf(const char *format, …) function reads the input from the
standard input stream stdin and scans that input according to
the format provided.
The int printf(const char *format, …) function writes the output to the
standard output stream stdout and produces the output according to the
format provided.
The format can be a simple constant string, but you can specify %s, %d, %c,
%f, etc., to print or read strings, integer, character or float respectively.
There are many other formatting options available which can be used based
on requirements. Let us now proceed with a simple example to understand
the concepts better −
#include <stdio.h>
int main( ) {
char str[100];
int i;
printf( "Enter a value :");
scanf("%s %d", str, &i);
printf( "\nYou entered: %s %d ", str, i);
return 0;
}
When the above code is compiled and executed, it waits for you to input
some text. When you enter a text and press enter, then program proceeds
and reads the input and displays it as follows −
$./a.out
Enter a value : seven 7
You entered: seven 7
Here, it should be noted that scanf() expects input in the same format as you
provided %s and %d, which means you have to provide valid inputs like
“string integer”. If you provide “string string” or “integer integer”, then it will
be assumed as wrong input. Secondly, while reading a string, scanf() stops
reading as soon as it encounters a space, so “this is test” are three strings
for scanf().