Your First C Program

22.04.2016 |

Episode #2 of the course Getting started with C programming by Sudeshna Das

 

Let us start out with a basic C program and get to know what all the elements that go into making a C program are.

 

#include<stdio.h>
void main()
{
printf(“My first C program!”);
}

 

This is one of the simplest C programs you will come across. This program displays “My first C program!” when you run it. You can try it on your own on Codepad: http://codepad.org/CPtNE7LS

See the first line? The hash (#) symbol does not make it a Twitter hashtag! This line tells your computer to include something called stdio.h at the beginning of this code. So, when this code is executed, all the content present in a file called stdio.h is attached at the beginning of your program.

This particular file—stdio.h, or the Standard Input/Output Header File—contains the things you need to be able to use your program to accept an input and display an output. It is sort of like having a vocal cord. Without it, you cannot speak. Just the same way, if you don’t have stdio.h included in your programs, they will not be able to display any output (or accept any input).

The second line begins the main part of our program. All the stuff that we want to do must be written inside the curly braces (see third line and fifth line).

The line printf(“My first C program!”) tells your computer that you want to display whatever is written inside the double quotes. In our case, this would be My first C program!

See the semicolon at the end of the line? It is similar to a full stop (or period) in English. This semi-colon tells the computer that the line or statement has ended and whatever comes next is a different statement.

Let us now change the inside of the program and get this code to do something else.

 

#include<stdio.h>
void main()
{
printf(“%i”, 3+4);
}

[Try it for yourself: http://codepad.org/kROgOoqk]

 

See the fourth line? This line will display the result of 3+4. The %i tells your computer that the result you want to display is an integer. Try using printf(“3+4”); instead of this line on a fresh Codepad page and see what happens.

Now let us try the same program with a little bit of modification.

 

#include<stdio.h>
void main()
{
printf(“%i and %i”, 3+4, 3-4);
}

http://codepad.org/ldf2evVN

 

You probably know by now what the output will be, even without executing the program.

Just as addition and subtraction are done by using the operations + and , we use * for multiplication and / for division.

Try this out:

 

#include<stdio.h>
void main()
{
printf(“%i and %i and %i and %i”, 4+2, 4-2, 4*2, 4/2);
}

http://codepad.org/QqD7tW66

 

Tomorrow, we will learn all about constants and variables. Till then, happy coding!

 

Recommended book

“The C Programming Language” by Brian W. Kernighan

 

Share with friends