Tutorial for C Language
Tutorial for C Language
Welcome to the tutorial series for C language. This is the best C language tutorial set on the Internet,
that will help you learn the C language.
C language was developed by Dennis Ritchie in 1972 at Bell Laboratories. In 1989, the C language
was standardized, where C language features were defined, also known as the 1989 ANSI
standard for C, and that is the reason, you will see C language also called C89, because of the 1989
ANSI standard.
The current latest version of the C language is C99, as some new features were added to the C
language in 1999.
You must be thinking, 1999 was more than 20 years ago, but the C language is still very
relevant and widely used although there are many other new languages like C++, Java, Python, C#,
etc. in the market.
History of C language
C language has evolved from three different structured languages ALGOL, BCPL, and B Language. It
uses many concepts from these languages while introduced many new concepts such
as datatypes, struct, pointer, etc.
BCPL was developed by Martin Richards, based on which the B language was created by Ken
Thompson. And then the B language was the language using which the C language was created.
In 1990, a version of the C language was approved by the International Standard Organisation(ISO),
and that version of C is also referred to as C89.
After the C language was accepted worldwide and programmers around the world started using it,
soon, to improve C language further, the work on the development of C++ language started.
The idea behind creating C language was to create an easy language that requires a simple
compiler (to translate the code from English to binary (0's and 1's that computer understands)) and
1|Page
to enable programmers to write complex programs in a language which is close to English because
earlier programmers had to write Machine instructions which were very difficult to remember.
C language compiler converts the readable C language code into machine instructions.
C language is a very good language to introduce yourself to the programming world, as it is a simple,
and easy-to-learn language that is capable of doing wonders.
Programs that are written in C language take very little time to execute and almost execute at
the speed of assembly language instructions. (Assembly level instructions are nothing but direct
commands to communicate with computer's hardware)
Initially, C language was mainly used for writing system-level programs, like designing Operating
Systems, because in the eighties (1980-89) the fight to make a stable, worldwide accepted operating
system was going on.
But C language can be used to develop other applications as well, like Text Editors, Compilers,
Network Drivers, many traditional PoS(Point of Sale) software like Restaurant Billing systems, etc.
Latest Version of C
The current latest version of the C language is C11, which was introduced in 2018. It is supported by
all the standard C language compilers, but many compilers still do not support this.
Many new features have been introduced in this version, and an overall attempt to improve the
compatibility of the C language with the C++ language has been made. We will learn about
the C11 edition once we are done with learning the C language towards the end of this tutorial series.
The most widely used version of the C language is still C89 and C99.
In this tutorial series, we will cover all the concepts of the C programming language with code
examples, simple explanations, and understanding the real-world use of the various concepts as we
learn them.
Apart from the tutorials, we provide you rich set of C programs and C Interview MCQs so that you
can test your knowledge parallelly.
You can also try writing C programs and run them in our online C Compiler, just log in and start
using it.
2|Page
Frequently Asked Questions
Here are some frequently asked questions, that beginners have when they start learning the C
language.
It is a computer programming language developed in the early 1970s by Ken Thompson and Dennis
Ritchie at Bell Laboratories.
It is a programming language that was developed to do system programming for the operating
system UNIX, but later it was used for developing software and programs for daily usage. It is still
being used to develop operating systems and for creating system-level programs, by big tech
companies (FAANG companies).
Modularity: It allows the reusability of modules. It has header files with readymade functions
that you can use.
Middle-Level language: It combines both the advantages of low-level and high-level
languages. (C arrays, C Pointers, etc.)
General-purpose programming language: It can be used to implement any kind of
application, just like Python. (Learn Python)
Portability: C program can be compiled or executed in any operating system (Unix, DOS,
Windows). You can compile the program in Windows and then run it on a Unix machine, it will
run without any issue.
Powerful programming language: It is a very efficient and powerful programming language.
It is best used for data structures and designing system software.
C is a case-sensitive language.
We have listed down all the features of the C language in the next tutorial - Features of C Language
It is amongst one of the most portable languages and is mainly used for creating system applications
that form a major part of Windows, UNIX, and Linux operating systems.
3|Page
4. Where is C used today?
It is used for the production of Compiler. We can develop desktop as well as mobile phone operating
systems with the help of C, for example Android.
Conclusion
This tutorial was all about an overview of the C language and its History. C was developed by Dennis
Ritchie in 1972 at AT and T's bell laboratories. In the next tutorial, we will learn about C language
features in detail.
FEATURES OF C LANGUAGE
Here we have listed all the major features of C language to give you more reasons to learn C
language.
The C programming language is a feature-rich programming language. It has all the required
features that a developer (beginner or expert) would want a programming language to have.
The C language was created from Basic Cambridge Programming Language(BCPL) and B
Language. But it is many times faster than BASIC and also has many more features which we will learn
in this tutorial.
Here is a simple chart to list down the main features of the C language.
The C Language is a simple language that is easy to learn even for a beginner and is super efficient to
use both in terms of the time of development and time of execution. Yes, if you want to create
software using C language you can do so in quite less time depending upon the size of the software
that you want to code.
2. Portability
4|Page
C Language program runs the same way everywhere. It means if you have written a simple C
program like a program to find sum of N numbers in C, on your Windows OS laptop or computer, and
then compiled it and run it, you can then take the compiled code and run it on any other operating
system or machine, like, Linux or macOS, etc., your C program will always return the same result.
If you have software written in the C language for Unix OS, and you now want to run it on Windows
OS, you can easily adapt the software for Windows OS, and that is the power of the C language.
C language is a structured programming language because we can create functions in the C language.
Using functions we can separate a particular operation from the main program and then use it again
and again.
A structured language is not just about having the ability to create functions, but it
supports loops, conditional statements, etc. All of this we will cover in detail in the upcoming
tutorials.
4. Powerful
C language is a very powerful programming language. It has a broad range of features like support
for many data types, operators, keywords, etc., allows structuring of code
using functions, loops, decision-making statements, then there are complex data-structures
like structures, arrays, etc., and pointers, which makes C quite resourceful and powerful, etc.
Using the C language you can easily read, write and create files. This may sound like a basic feature
today, but in the early 1990s, this was a game-changer.
C supports various inbuilt functions and libraries that create development fast. The standard library
support for the C language is superb and you will see that a lot of keywords or ready-made
operations that you will use while writing code in C language are already pre-defined. We just have to
use them, without worrying about how they work.
6. Libraries Support
5|Page
There is not just the standard library for C language but also a large ecosystem of 3rd party
libraries, which are created by developers/coders around the world, and anyone can use them.
Even you can write your own C language library and distribute it online through your Github profile.
You never know, people around the world might need your solution.
7. Separate Compilation
C language code is compiled and then it is run. We will learn how the C language code is compiled in
another tutorial. For now, just assume that the code is compiled. Obviously, the compilation of code
will take some time. A small piece of code will compile faster while a large code will take time to get
compiled.
In C language you can break your code and put it in multiple source code files. C language will
compile the files separately and then link them together for execution.
Another plus point of this is, multiple programmers/developers can work on different code files
while working on a single project.
8. Middle-Level Language
A Low-level language is generally fast, powerful but hard to understand and write code in. Whereas
a High-level Language is easy for us to understand and write code in, it is also highly portable, but it
is generally slow and is unable to directly talk to the system hardware.
Like most High-level languages, for example, Java, C++, C#, the C language has a syntax, there
are proper rules for writing the code, and the C language strictly follows it.
If you write anything that is not allowed, you will get a compile-time error, which happens when the
compiler is unable to compile your code because of some incorrect code syntax.
6|Page
The C language is a format-free language. There are no line numbers needed in the C language code,
or we can say that the line number holds no significance. There is no need to place statements on a
specified location on a line.
The C language uses a Compiler to compile the code into object code, which is nothing but machine
code that the computer understands. Hence to run a C language program we have to install a C
language compiler first.
In C, the uppercase and lowercase characters are different. That means if is not the same as IF in C
language.
Here are some frequently asked questions, that beginners have when they learn about features of the
C language.
The main features of the C language are, it is simple(easy to learn) yet powerful, Portable, Mid-
level language, which is structured and needs a Compiler for execution. The C language also has
a rich standard library with the support of extensive 3rd party libraries.
The main reason behind the popularity of the C language is that it has a rich feature set, making it a
suitable language for a wide range of use cases. You can create an operating system using C language
or any other simple software. The C language is a general-purpose programming language.
It is considered a powerful language because it provides a broad range of features like support for
many data types, operators, keywords, etc., allows structuring of code
using functions, loops, decision-making statements, then there are complex data-structures
like structures, arrays, etc., and pointers, which makes C quite resourceful and powerful, etc.
7|Page
4. Is C language Portable?
Yes, the C language code is portable. If you have software written in the C language for Unix OS, and
you now want to run it on Windows OS, you can easily adapt the software for Windows OS, and that
is the power of the C language.
a) C is a Portable language.
d) C language is a structured language, with features of both High-level language and Low-level
language.
Conclusion
In this tutorial, we covered the features of the C language, explaining every feature with an example
so that you understand what each feature means. Do not just learn the C language features but try to
understand the meaning of those features.
#include <stdio.h>
int main()
{
8|Page
printf("Hello World");
return 0;
Hello, World
Run Code →
To run the above code on your local machine, you will have to install a C language compiler on your
Computer/Laptop. We will learn how to do that in the next tutorial - Compile and Run C Code.
If you do not want to install the C compiler on your computer, don't worry. You can use our Online
Compiler to run C programs and Practice. Click on the Run Program button above to open the
compiler.
Pre-processor
Header file
main() function
Variables in C
Statements & expressions in C
All these are essential parts of a C language program. Don't worry about all this, we will learn about
everything one by one and will clear all your confusion.
Let's start with a basic introduction of various code statements that we used in the above Hello World
program.
1. Pre-processor
The #include is the first statement of any C program. It is known as a pre-processor. The task of a pre-
processor is to initialize the environment of the program, i.e. to link the program with the header files
required.
As its name suggests, this line of code is responsible for doing pre-processing, before the actual
code (logic) is executed.
9|Page
So, when we say #include<stdio.h>, it is to inform the compiler to include the stdio.h header file which
is the standard I/O library into the program before executing the program.
The standard I/O library lets you read input from the keyboard(i.e standard in) and then write the
output to the console screen (i.e. standard out) and it is an extremely useful library.
By Console screen, we mean CMD or command prompt in case of Windows OS and Terminal in case
you use Linux/Ubuntu/macOS.
The #include is not the only pre-processor. Whenever you see any piece of code starting with
a # symbol, that means it's a pre-processor in the C language. We will learn about pre-processors in
detail later.
2. Header file
A Header file is a set or collection of built-in(readymade) functions, which we can directly use in
our program.
Header files contain definitions of the functions which can be used in any C program by using pre-
processor #include statement along with the name of the header file.
There are some standard header files that come along with default C installation, like stdio.h header
file. There are many other such files, we will learn about them later.
With time, you will have a clear picture of what header files are, as of now consider them as a
readymade collection of functions that comes packaged with the C language and you can use them
without worrying about how they work, all you have to do is include the header file in your program.
To use any of the standard library functions, the appropriate header file must be included. This is
done at the beginning of the C source code.
For example, to use the printf() function in a C program, which is used to display anything on the
console screen, the line #include <stdio.h> is required, because the header file stdio.h contains
the printf() function definition.
10 | P a g e
3. The main() Function
Everything inside this function in a C program will be executed, hence the actual logic or the code is
always written inside the main() function.
As the name suggests, this is the main(of prime importance or center of attraction) function.
#include <stdio.h>
int main()
printf("Hello World");
return 0;
In the Hello World code example above, there was int written before the main() function, remember?
Well, that is the return type of the main() function. we will discuss it in detail later.
The curly braces { } just after the main() function enclose the body of the main() function.
The printf() is a function that is used to print(show) anything on the console as output. This function is
defined in the stdio.h header file, which we have included in our C program.
We will cover how to take input and show output in one of the next tutorials.
5. Return Statement
A return statement is used to return a response to the caller function. It is generally the last statement
of any C language function. Do not worry about this too, we will cover this statement when we learn
about functions in the C language.
11 | P a g e
6. Semicolon
It is important to note that every statement in C should end with a semicolon(;). If you miss adding
any semicolon, the compiler will give an error.
All the C programs can be written and edited in normal text editors like Notepad or Notepad++ and
must be saved with a file name and .c extension. For example, helloworld.c can be the file name for
the Hello World program.
If you do not add the extension .c then the compiler will not recognize it as a C language program
file.
Different preprocessors in the C language are #include, #if, #define, #ifdef, #undef, etc. and many more.
A pre-processor is a statement that is executed before the main code for the C program is executed.
The main() function in the C language acts as the entry point of any program or we can say that the
execution of the code starts from here. The source code which is inside the main() function gets
executed.
In order to add the single line comment, you can use slash // followed by the comment and for
multiline comments, you can use the following: /* comment here */.
The stdio stands for standard input and output and .h is the extension of the file indicating that it is
a header file.
The main use of this header file is, that it helps to get the input from the user(Keyboard) and return
the output result text to the monitor(screen). There are readymade functions in this header file that
12 | P a g e
we can use in our program, for example, printf() and scanf() functions are defined in
the stdio.h header file.
Conclusion
In this tutorial, we saw a simple Hello World program in the C language and covered its structure. In
the next tutorial, we will set up the C compiler on our local computer/laptop so that you can run this
program on your computer too.
1. Download a full-fledged IDE like Turbo C++ or Microsoft Visual C++ or DevC++, which comes
along with a C language compiler.
2. Or, you can use any text editor to edit the program files and download the C compiler
separately and then run the C program using the command line.
If you haven't already installed an IDE for the C language - Follow this step-by-step guide to Install
Turbo C++ for C Language
We will recommend you to use Turbo C or Turbo C++ IDE, which is the oldest IDE for C
programming. It is freely available over the internet and is good for a beginner.
Step 1: Open turbo C IDE(Integrated Development Environment), click on File and then click on New
Step 2: Write a Hello World program that we created in the previous article - C Hello World
program.
13 | P a g e
Step 3: Click on Compile menu and then on Compile option, or press the keys press Alt + F9 to
compile the code.
Step 4: Click on Run or press Ctrl + F9 to run the code. Yes, C programs are first compiled to
generate the object code and then that object code is Run.
If you do not wish to set up an IDE and prefer the old school way, then download the C compiler
which is called gcc from the GCC website https://gcc.gnu.org/install/
Once you have downloaded and installed the gcc compiler, all you have to do is, open any text
editor, copy and paste the C program code for C Hello World Program, and save it with the name
the helloworld.c like any other file you save with a name.
Now, Open Command prompt or Terminal(if you use Ubuntu or Mac OS), and go to the directory
where you have saved the helloworld.c program file.
Type the command gcc hello.c to compile the code. This will compile the code, and if there are no
errors then it will produce an output file with name a.out(default name)
Now, to run the program, type in ./a.out and you will see Hello, World displayed on your screen.
$ gcc hello.c
$ ./a.out
Hello, World
14 | P a g e
Difference between Compile and Run in C?
You must be thinking about why it is a 2 step process, first, we compile the code and then we run the
code. We did the same thing with Turbo C and the same is with the command line or Terminal too.
Well, the compilation is the process where the compiler checks whether the program is correct
syntax-wise, and there are no errors in the syntax, and if the code is fine converts the C language
source code into machine understandable object code.
When we run a compiled program, it is just the already compiled code that is run.
This difference is clear when we run a C program using the command line. When you compile the
code, a .out file is generated, which is then Run to execute the program.
Once a .out file is generated, and then you make any changes to your program in the source code
file, you will have to again compile the code, otherwise, the .out file will have the old source
code and will keep running the old program itself.
It is a process where the compiler checks whether the program is syntactically correct or not. If there
is any mistake found in the syntax then it will throw the errors. The error thrown at the time of
compilation is called a Compile-time error.
During the compilation and execution of the C program, the compiler generates output files with the
same name as that of the C program file but with different extensions. The .c extension file is called
the source file that keeps the code of the program. Now, when we compile the file, then
the C compiler looks for errors.
15 | P a g e
You can use an IDE to write and run the C program by following these steps:
Step 1: Open turbo C IDE(Integrated Development Environment), click on File and then click
on New.
Step 2: Write the C program code.
Step 3: Click on Compile or press Alt + F9 to compile the code.
Step 4: Click on Run or press Ctrl + F9 to run the code.
Step 5: And turbo C will open the console to show you the output of the program.
Conclusion
This tutorial was all about how to run and compile any C program using an IDE name Turbo C . We
have also covered how it can be done without using any IDE.
The process of converting the source code written in any programming language(generally, mid-
level or high-level language) into machine-level language that is understandable by the computer is
known as Compilation. The software that is used for this conversion is known as a Compiler.
In C language, through compilation, the C language source code is converted into object code.
The compiler takes the input which is the source code and provides the output in the form of object
code. The complete process of compilation in the C language is further divided into four phases:
1. Pre-processing,
2. Compiling,
3. Assembling, and
4. Linking
The compiler checks the source code for any syntax or structural errors and after checking, if the
source code is found error-free, it then generates the object code that has an extension .obj (for
Windows) or .o (for Linux).
Let us now take a look at the different stages of the compilation process in the C language.
Compilation Process
16 | P a g e
Like mentioned above, the different stages of the compilation process are as follows:
Pre-processing
Compiling
Assembling
Linking
In the flow chart below we have explained how the compilation process work and what are the
different stages of compiling the C language source code.
Let's discuss all these stages of the C language source code compilation in the order they are
performed.
In this phase, pre-processing of the source file is done. The Pre-processor is a program that accepts
the C source code file and then it performs the following tasks:
17 | P a g e
Step 1: Preprocessor
It is a program that processes the source program before passing them on to the compiler. At this
step the pre-processors used in any C program are handled and the source code is made ready for
compilation.
Each preprocessing statement must start with #, where # is called the preprocessor directive.
Each preprocessing directive is a single-line code statement.
The word after # is called the preprocessor command.
1. #include
To include a particular header using the name of the header file into the C language program code.
2. #define
3. #error
Just like the above three, there are many other preprocessors, we will cover them in detail in a
separate tutorial.
Hence, the preprocessor expands the source code(adds the required information) and then this
expanded source code is passed on to the compiler.
It gives the (.i) extension to the source code file which is initially with (.c) extension.
Step 2: Compiler
The expanded code by the preprocessor is then passed on to the compiler. As we know a compiler is
a program that converts the high-level language(or mid-level language) code to the assembly
code, which is then converted into the machine code, which the machine can understand.
Therefore the preprocessed code given by the preprocessor to the compiler is then converted into
assembly code by the compiler, which is then passed on to the Assembler.
The source file which got the (.i) extension in the previous step gets converted into (.s) extension by
the compiler.
18 | P a g e
Step 3: Assembler
The assembler converts the assembly code that it gets from the compiler into the object code. The
extension of the file in this step becomes (.obj).
Don't think that Assembler is a separate program generating the object code. The Assembler is part of
the compilation process of the C language source code.
When in laymen language, we say, the C code is compiled, it means the complete compilation
process, covering all these steps, is done.
Step 4: Linker
A linker is a tool that is used to link all the parts of a program together in order of execution. The
code after this stage becomes Executable Machine code.
There might be some situations when our program refers to the functions that are defined in some
other files. Or, if the code for some program is too big, we can break it into two files, which will be
compiled separately and then linked using the Linker.
In the C language compilation process, the Linker plays a very important role.
If your C program includes a header file, and you are using some function defined in that header file,
then the Linker will link the required object code for the function in the library, to the object code
of your program and package them together.
Similarly, if your program code is too big and you break it into two files, then both the source code
files will be converted into object code separately and then the Linker will link them and make the
code ready for execution. This is also called Separate Compilation.
Here are some frequently asked questions related to the C language compilation process.
It is a computer program that is used to translate the source code that is in a high-level programming
language or a mid-level programming language into machine code, which can be executed and the
machine can understand what to do.
19 | P a g e
Q2. What is a preprocessor?
The preprocessor is a directive used to instruct the compiler to preprocess the source code before the
start of the actual compilation. There are some parts of the C language program that can be specified
using the preprocessor, which is nothing but statements to be executed at the beginning of
compilation.
The C language code files which have extension .c are also called the source code file.
The linker is used to link all the parts of the program together in order for the execution.
If your C program includes a header file, and you are using some function defined in that header file,
then the Linker will link the required object code for the function in the library, to the object code
of your program and package them together.
Similarly, if your program code is too big and you break it into two files, then both the source code
files will be converted into object code separately and then the Linker will link them and make the
code ready for execution. This is also called Separate Compilation.
1. Preprocessor (preprocessing)
2. Compiler (compiling)
3. Assembler (assembly)
4. Linker (linking)
Conclusion
In this tutorial, we learned how the C language code that we will be writing in the upcoming tutorials
is compiled. What are the various steps followed in compilation and what happens in those steps?
If you are left confused after this, do not worry, just read it and as we move on with the tutorial, you
will understand everything.
20 | P a g e
C LANGUAGE BASIC SYNTAX RULES
The C language syntax specifies the rules for writing the code in the C language. In simple words,
these rules inform how to form statements in a C language program - How should the line of code
start, how it should end, where to use double quotes, where to use curly brackets, where to use
parenthesis, etc.
What is Syntax?
Any language, be it English or Hindi, or Spanish, has a grammar that defines the rules for using the
language, for example how to form a sentence, what different words mean, etc.
In a normal spoken language or a computer programming language, syntax means how to arrange
words, characters, special characters, to make a meaningful statement, or expression, etc.
If someone says there is a syntax error in the program, means you have not written the program
correctly, you might have missed some semicolon or some other general mistake in typing the code
for the program.
Having a syntax error doesn't mean your code's logic is incorrect, it means you have written it
incorrectly. Once the syntax is correct, then only the code is compiled and then run.
The C Tokens
The smallest individual unit in the C program is known as C Token. Tokens are either keywords or
identifiers, constants, variables, or any other symbol which has some meaning in C language. The C
program can also be called a collection of various tokens.
Hence the syntax for C language defines how to use these tokens together while writing the C
language code.
#include <stdio.h>
int main()
printf("Hello,World");
return 0;
21 | P a g e
}
printf("Hello,World");
The picture below shows token in the entire Hello World Program.
Now let's see some important syntax rules, which you must remember always while writing code in
the C language.
A semicolon ; is used to mark the end of a statement and the beginning of another statement in the C
language.
The absence of a semicolon at the end of any statement will mislead the compiler to think that this
statement is not yet finished and it will add the next consecutive statement after it, which may lead to
a compilation(syntax) error.
#include <stdio.h>
int main()
printf("Hello,World")
return 0;
return 0;
22 | P a g e
^
In the above program, we have omitted the semicolon from the printf("...") statement, hence the
compiler will think that starting from printf up untill the semicolon after return 0 statement is a single
statement and this will lead to compilation error.
Comments are plain simple text in a C program that is not compiled in the compilation process.
We can write comments in a program, to explain various parts of the program. Although writing
comments is not compulsory, but it is recommended to make your program more descriptive, and
easier for others to understand.
You can even comment out code using these two techniques and that statement or part of code will
not get compiled and executed.
/*
I am very excited!
*/
#include <stdio.h>
int main()
23 | P a g e
{
printf("Hello,World");
return 0;
As you can see in the above code, we have added comments, and have also, commented
a printf() statement, which will not get executed.
This is just the beginning, as we will learn more concepts in the C language, we will learn the syntax
for using all of them along with examples.
Everything has a way of writing and use when it comes to writing code, and that way is its syntax.
Here are some frequently asked questions related to the C language syntax.
24 | P a g e
The smallest individual unit in the C program is known as C Token. Tokens are either keywords or
identifiers, constants, variables, or any other symbol which has some meaning in C language. The C
program can also be called a collection of various tokens.
Q2. What will happen if we forgot to use a semicolon at the end of the statement in C?
If we forgot to put the semicolon at the end of any statement in the C language then it will lead to a
syntax error. In that case, an error message is issued by the compiler that a semicolon is expected.
A compilation error, or compile-time error, is the error returned by the compiler if the syntax of the C
program is incorrect. When you try to compile a program with some syntax mistake, then the
compiler will give an error, which is called a Compile-time error.
We can add single-line comments using the // at the starting of the comment text, and multi-line
comment by enclosing the text within /* and */ in the C program.
In the C language, the main() function defines the starting point of execution. If a C program doesn't
have a main() function then no code statement will be executed in that program. In most cases the
compiler gives an error, if it cannot find the main() function.
Conclusion
This tutorial was all about basic syntax rules in the C language. We have covered the importance of
semicolons, tokens in C, and how to write a single line and multiline comments in C.
25 | P a g e
What are Keywords?
Every programming language has some reserved words that are used internally and have some
meaning for the language, such words are called Reserved Keywords or just Keywords.
Taking an example from real-world, when someone says, Do you have my Laptop? You immediately
picture a Laptop computer, what if the person asking for his/her Laptop, has a dog named
Laptop(and is asking about the Dog), you won't understand until and unless you know that he/she
has a dog named Laptop. This can lead to confusion, right.
Hence, the words that any programming language like the C language uses internally for some
specific purpose, are not allowed to be used other than that purpose, otherwise, the language
compiler will get confused.
In the last tutorial, where we learned C language syntax, we learned that everything in the C program
is a Token.
Hence we can say that the words or Keywords are also tokens.
Just like you have a name, using which everyone calls you, it can be John, Ron, Scarlett, Monica, etc.,
similarly in the C language, when we define a variable or a function, or a structure, etc. we name them
so that it becomes easier for us to identify them and use them whenever required. These names are
called Identifiers.
Identifiers are also tokens. Again, because every meaningful symbol, word, etc. in the C language
are C Tokens, hence Identifiers are also tokens.
C Keywords
Now we know, that keywords are reserved words that have special meaning in the C language.
The meaning of C language keywords has already been described in the C compiler, which means the
C compiler knows what these words mean and what it has to do with them.
These meanings cannot be changed. Hence, keywords cannot be used as a variable name or a
function name (in short as an Identifier) because that would try to change the existing meaning of the
keyword, which is not allowed.
26 | P a g e
You cannot use Keywords as Identifiers. This means you cannot name your variable, function,
structure or pointer, or anything else, using a keyword.
List of Keywords in C:
All these keywords were defined in the C89 standard, which was the first version of the C language,
while some more keywords were added in the later C99 standard.
Each keyword has its own meaning attached to it, for example, the int keyword is used to define
an integer datatype value, if/else are used for defining conditional statements, and so on. We will
learn most of them as we progress in this tutorial.
27 | P a g e
The main() is not a keyword, but you should treat it as a keyword only. Because this function is a
special function. If you name any variable as main, you may confuse the Compiler.
C Identifiers
Because it's up to the user to define the Identifiers, hence there are some rules that one has to follow,
which are defined by the C language, to avoid unnecessary errors in the compiler.
An identifier can only have alphanumeric characters(a-z , A-Z , 0-9) and underscore(_).
The first character of an identifier can only contain alphabet(a-z, A-Z) or underscore (_).
Identifiers are case-sensitive in the C language. For example, name and Name will be treated
as two different identifiers.
Keywords are not allowed to be used as Identifiers.
No special characters, such as a semicolon, period, whitespaces, slash, or comma are
permitted to be used in or as an Identifier.
Let's see a few examples where we'll use keywords and identifiers. We will define a C variable, so do
not get confused, we will be learning about variables very soon.
When we declare a variable or any function in any C language program, to use it we must provide a
name to it, that name is then used throughout the program, for example:
Here myvariable is the name or identifier for the variable which stores the value "Studytonight" in it.
And int is the keyword. And all of them are tokens.
int money;
28 | P a g e
double salary;
$myvar; // incorrect
#include <stdio.h>
int main() {
int void = 0;
return 0;
int void = 0;
^
29 | P a g e
Run Code →
The C language compiler will think that we have mistakenly used two data types together and will
give an error. Because void is also a data type in the C language(hence it is a keyword).
Here are some frequently asked questions related to keywords and identifiers.
The identifier is just the name given to the variable, while a variable represents a memory field
where some data is stored based on its data type. It's just like what is the difference between you and
your name. Your name is just a word that people call you with, while you are a human being.
Conclusion
This tutorial was all about keywords and identifiers in C language. They both are parts of the token.
Tokens in C are defined as the smallest individual element in C and are the basic building blocks of
creating a program. We have covered keywords and identifiers in detail along with their valid syntax.
For example, you may want to use a number like 1, 2, 100, or a decimal point number
like 99.95, 10.5, or a text, like "Studytonight", all these values are handled differently by the C
language compiler, hence, we use data types to define the type of data used in any program.
Each data type occupies some memory, has a range of values and a set of operations it allows to be
performed on itself. In this tutorial, we have explained the different data types used in C language. For
code examples, checkout Using C Datatypes tutorial.
Data Types in C
Broadly, there are 5 different categories of data types in the C language, they are:
TYPE EXAMPLE
Basic character, integer, floating-point, double.
30 | P a g e
Derived Array, structure, union, etc.
Enumeration enums
Bool type true or false
void Empty value
The C language has 5 basic (primary or primitive) data types, they are:
1. Character: We use the keyword char for character data type. It is used to store single bit
characters and occupies 1 byte of memory. We can store alphabets from A-Z(and a-z) and 0-9
digits using char. For example,
2. char a = 'a';
3. char b = 'A';
4. char c = '0';
char d = 0; //error
31 | P a g e
For char datatype, it is necessary to enclose our data in single quotes. We can perform
addition and subtraction operations on char but the ASCII value should not exceed 127.
5. Integer: We use the keyword int for integer data type. The int data type is used to store non-
fractional numbers which includes positive, negative and zero values. The range of int is -
2,147,483,648 to 2,147,483,647 and it occupies 2 or 4 bytes of memory, depending on the
system you’re using. For example,
6. int a = 5550;
7. int b = -90,
8. int c = 0;
We can perform addition, subtraction, division, multiplication, bitwise and modulo operations
on int data type.
9. Floating-point: We use the keyword float for floating-point data type. float is used to
store decimal numbers. It occupies 4 bytes of memory and ranges from 1e-37 to 1e+37. For
example,
We can perform addition, subtraction, division, and multiplication operations on float data type.
13. Double: We use the keyword double for double data type. double is used to store decimal
numbers. It occupies 8 bytes of memory and ranges from 1e-37 to 1e+37.
double b = -67.9;
double has more precision than flaot so double gives more accurate results as compared to float.
We can perform addition, subtraction, division and multiplication operations on double data
type.
32 | P a g e
15. Void: This means no value. This data type is mostly used when we define functions.
The void data type is used when a function does not return anything. It occupies 0 bytes of
memory. We use the void keyword for void data type.
Each data type has a size defined in bits/bytes and has a range for the values that these data types
can hold.
33 | P a g e
Size of different Data types in C
The size for different data types depends on the compiler and processor types, in short, it depends on
the Computer on which you are running the C language and the version of the C compiler that you
have installed.
char is 1 byte
The char datatype is 1 byte in size or 8 bits. This is mostly the same and is not affected by the
processor or the compiler used.
There is a very easy way to remember the size for int datatype. The size of int datatype is usually equal
to the word length of the execution environment of the program. In simpler words, for a 16-bit
environment, int is 16 bits or 2 bytes, and for a 32-bit environment, int is 32 bits or 4 bytes.
float is 4 bytes
The float datatype is 4 bytes or 32 bits in size. It is a single-precision data type that is used to hold
decimal values. It is used for storing large values.
float is a faster data type as compared to double, because double data type works with very large
values, hence it is slow.
double is 8 bytes
The double datatype is 8 bytes or 64 bits in size. It can store values that are double the size of what
a float data type can store, hence it is called double.
In the 64 bits, 1 bit is for sign representation, 11 bits for the exponent, and the rest 52 bits are used
for the mantissa.
The double data type can hold approximately 15 to 17 digits, before the decimal and after the
decimal.
void is 0 bytes
The void data type means nothing, hence it doesn't have a size.
34 | P a g e
Before moving on to the range of values for these data types, there is one more important concept to
learn, which is Datatype modifiers.
In the C language, there are 4 datatype modifiers, that are used along with the basic data types to
categorize them further.
For example, if you say, there is a playground, it can be a park, a playground or a stadium, but if you
be more specific and say, there is a Cricket ground or a Football stadium, that would make it even
more precise.
Similarly, there are modifiers in the C language, to make the primary data types more specific.
1. signed
2. unsigned
3. long
4. short
As the name suggests, signed and unsigned are used to represent the signed(+ and -
) and unsigned(only +) values for any data type. And long and short affects the range of the
values for any datatype.
For example, signed int, unsigned int, short int, long int, etc. are all valid data types in the C
language.
long long num = 123456789987654321; // we cannot store a value this big value using int data type.
Now let's see the range for different data types formed as a result of the 5 primary data types along
with the modifiers specified above.
In the table below we have the range for different data types in the C language.
As you can see in the table above, with different combinations of the datatype and modifiers the
range of value changes.
When we want to print the value for any variable with any data type, we have to use a format
specifier in the printf() statement.
Well, if you try to assign a value to any datatype which is more than the allowed range of value, then
the C language compiler will give an error. Here is a simple code example to show this,
#include <stdio.h>
int main() {
return 0;
36 | P a g e
warning: large integer implicitly truncated to unsigned type [-Woverflow]
When a type modifier is used without any data type, then the int data type is set as the default
data type. So, unsigned means unsigned int, signed means signed int, long means long int,
and short means short int.
In simple words, the unsigned modifier means all positive values, while the signed modifier
means both positive and negative values.
When the compiler gets a numeric value, it converts that value into a binary number, which means a
combination of 0 and 1. For example, 32767 in binary is 01111111 11111111, and 1 in binary is 01
(or 0001), 2 is 0010, and so on.
In the case of a signed integer, the highest order bit or the first digit from left (in binary) is used as
the sign flag. If the sign flag is 0, the number is positive, and if it is 1, the number is negative.
And because one bit is used for showing if the number is positive or negative, hence there is one less
bit to represent the number itself, hence the range is less.
For signed int, 11111111 11111111 means -32,767 and because the first bit is a sign flag to mark it
as a negative number, and rest represent the number. Whereas in the case of unsigned
int, 11111111 11111111 means 65,535.
While there are 5 primary data types, there are some derived data types too in the C language which
are used to store complex data.
Derived data types are nothing but primary data types but a little twisted or grouped together like
an array, structure, union, and pointers. These are discussed in detail later.
Conclusion:
In the next tutorial, we will learn about variables and there you will learn the actual usage of data
types, with man code examples. So let's move on.
37 | P a g e
USING C DATATYPES (WITH EXAMPLES)
The Datatype defines the type of data being used. We have covered C datatypes in detail in the
previous tutorial.
The C language has 5 basic (primary or primitive) data types, they are:
1. Character - char
2. Integer - int
3. Floating-point - float
4. Double - double
5. Void - void
To learn about the size of data types, range of values for datatypes, and various type
modifiers like signed, unsigned, long, and short - Visit C datatypes in detail
1. char Datatype
The char datatype refers to character values, enclosed in single quotes, with a range of -127 to 127.
As it's clear from the range, we can even use small integer values in the char datatype.
For example,
2. int Datatype
The int datatype is used to store whole numbers, which are values without any decimal part or
exponent part.
The int datatype can store decimal (base 10), octal (base 8), and hexadecimal (base 16) values.
int a = 100;
// negative value
38 | P a g e
a = -100;
int x = 1000U;
With the value of int data type, we can use suffix U or u, to tell the compiler that the value is
for unsigned int data type and suffix L or l for a long int value.
Learn more about type identifiers(signed, unsigned, long, and short) and how they change the primary
datatypes when used with them - Visit C datatypes guide for beginners
3. float Datatype
The float data type is used to store real numbers which may have a decimal (fraction) part or an
exponential part. It is a single-precision number.
float x = 127.675;
// with suffix F or f
float y = 1000.5454F;
Just like int datatype, the float can also be used with type modifiers - Learn more about it, visit C
datatypes guide for beginners
4. double Datatype
39 | P a g e
The real numbers which are big enough that they cannot be stored in float datatype, is stored as
a double datatype. It is a double-precision number. A double datatype value can hold above 15 to 17
digits before the decimal point and 15 to 17 digits after the decimal point.
Here is an example,
double x = 424455236424564.24663224663322;
We should only use the double datatype when we need such large numbers, otherwise not, because
using double datatype makes the program slow.
Conclusion:
In this tutorial, we saw some examples for different data types available in the C language. To
understand about the C data types in detail, visit C datatypes guide for beginners .
Variable is like a container (storage space) with a name in which you can store data.
40 | P a g e
It's like your home has an address (House No./Flat No.) so whenever you order something online,
you just have to provide your home address and the delivery executive is able to find it.
In the C language, if we want to use some data value in our program, how can we do it? Well, it's
done using variable.
When we create a variable in a C program, the C compiler allocates a storage space, depending upon
the datatype of the variable(8 bits for char, 16/32 bits for int, etc.), and then that storage space is given
a name which is the variable name.
Once a variable is created, we can store value in it. We can change the value stored in a variable as
many times as we want, but we should make sure we store the correct data type value.
Here is how you can create or declare a new variable in the C language,
data_type var_name;
where, data_type is a valid data type (along with datatype modifiers, if required) and var_name is
the name of the variable.
41 | P a g e
For example,
int marks;
Here, marks is the name of the variable, and it can store values of int type.
Once we have declared or created the variable, then we can assign a value to it. This is called variable
definition.
// variable declaration
int marks;
// variable definition
marks = 10;
We can do declaration and definition in a single step too, like this (recommended).
You can change the value of the variable, whenever you want. But make sure the value is of
correct data type.
// variable defined
marks = 33;
A variable in C language must be given a type, which defines what type of data can be stored in the
variable. If you do not provide any datatype, then the C compiler will give compile-time error or
syntax error.
The datatype can be char, int, float, double, or short int, long int, etc. data type along with modifiers.
42 | P a g e
You can learn about C Datatypes to see the list of various data types supported in the C language.
If you try to assign an incorrect datatype value to a variable, then the compiler may giver error, or it
will automatically convert the value into the datatype of the variable.
For example,
#include <stdio.h>
int main() {
int x = 10.58;
43 | P a g e
return 0;
Value is 10
Run Code →
As you can see in the output, the C compiler removed the part after the decimal,
because int datatype can only store whole numbers.
We will learn about printf() function and %d (used to print the value of the int datatype) in the next
tutorial, with more code examples.
Once we define a variable with some datatype then we cannot change the datatype of that variable.
For example,
// int variable
When you create a variable, you should always give a meaningful name to the variable. And follow the
below rules for naming the variable:
Let's see a few examples for incorrect names as per the above rules:
44 | P a g e
int 1var; // incorrect - should not start with number
Declaration of variables must be done before they are used in the program. The declaration does the
following things.
extern int a;
extern float b;
45 | P a g e
extern double c, d;
Defining or Initializing a variable means the compiler has to now assign storage to the variable
because it will be used in the program.
We can even declare multiple variables of the same data type in a single line by using a comma to
separate them.
For example,
int a;
float b, c;
int a = 10;
An Identifier is a name given to any variable, function, structure, pointer, or any other entity in a
programming language. While a variable, as we have just learned in this tutorial is a named memory
location to store data that is used in the program.
IDENTIFIER VARIABLE
The identifier is the name given to a variable, function, While variable is used to name a memory location that
etc. stores data.
An identifier can be a variable, but not all identifiers are All variable names are identifiers.
variables.
Example: Example:
// studytonight is identifier for a variable // int variable
int studytonight; int a;
// studytonight is identifier for a function // float variable
int studytonight() { float a;
...
}
Another great analogy to understand the difference between Identifier and Variable is:
You can think of an Identifier int x to be a variable's name, but it can also be a function's name int x() {
} and still, be an identifier.
46 | P a g e
Just like Obama is the name of a person, but also the name of a foundation.
Conclusion
In this tutorial we learned about C Variables, how to create a variable, assign value to a variable and
what happens when a variable is created. We also learned about the importance of datatype while
creating a new variable.
C LITERALS/CONSTANTS
If we want to use some data value in a C program, we can also directly use a value, instead of
creating a variable to store the value. When we use a value directly in C program without creating a
variable, it is known as a Literal.
A literal is used when we want to use a fixed value in the program, hence literals are also
called Constants.
For example, 1, 100, 'Y', 10.5, etc. Whereas, when we use a variable in C, we can change the value
stored in the variable.
1. Integer Literal
2. Character Literal
3. Floating-point Literal
4. String Literals
5. Backslash Character Literals (Escape Sequences)
1. Integer Literal
Any numeric value without any decimal or exponential part, used in the C program is an integer literal.
For example,
In the C language, the octal number starts with a 0, and the hexadecimal number starts with a 0x.
You can also use type suffix with integer values to make it easier for the compiler to understand the
type of the integer value. If you follow the value with L, the compiler will treat it as a long value, if you
add U after the value, the compiler treats the value as unsigned.
For example,
2. Floating-point Literals
Any valid floating-point value when used directly in a C program, is called a floating-point literal.
For example,
100.50
0.000127
-0.77E-5
If we add a type suffix F or f after the value, then the compiler will treat the value as float type by
default.
For example,
3. Character Literals
48 | P a g e
A valid character datatype value when used directly in the C program is called a character literal.
For example,
4. String Literals
A sequence of characters is called a String. We will learn about C strings in detail in the later section
of this tutorial series.
For example,
Also known as Escape sequences, these combinations of characters with the backslash
character \ have special meaning for the C compiler.
A backslash character is used to escape characters with special meaning and make them normal
characters for the compiler.
For example, if you use a single quotation mark, the compiler will think that it is the starting or end of
a character value, but what if you want a single quote character.
In the example above the first and the last single quote marks the start and end of the character
value, whereas the backslash escape character informs the compiler to treat the single quotation after
it as a normal character.
CODE MEANING
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\" Double quote
49 | P a g e
\' Single quote
\\ Backslash
\v Vertical tab
\a Alert
\? Question mark
\N Octal contant
\xN Hexadecimal constant
The newline and horizontal tab code are quite commonly used, and you will be using them a lot as
you start coding in the C language. So remember \n is for newline and \t is for the horizontal tab.
Conclusion:
With this, we have covered all the Constants used in the C language which are also called Literals. Do
not ignore the backslash escape literals as they are also very important and widely used in the C
programs.
The variables which have type const, cannot be changed by the program. We can provide a value while
defining the variable, and then, throughout the program, that variable will hold the same value.
In the above code, we have defined a variable with name totalmarks and assigned it a value 100.
Because we have used the const keyword while defining the variable hence we cannot change the
value of the totalmarks variable.
If you will try to change the value of the const variable in the program after it has been defined, then
the compiler will give an error.
50 | P a g e
For example,
#include <stdio.h>
int main() {
total_marks = 80;
return 0;
total_marks = 80;
Run Code →
As you can see in the error message, the compiler says that the variable is a read-only variable,
hence its value cannot be changed.
Because const variables are read-only variables, the compiler can place these variables into the read-
only memory (ROM).
When we define a variable as const, then nothing in that program can change the value of that
variable.
51 | P a g e
Hence, if the value of the const variable changes, then you can say that something outside of the
program changed the value, it can be the hardware device or any external event.
Conclusion:
In this tutorial, we learned how to create constant value variables, which are the variable whose values
cannot be changed by the program.
The C programming language provides standard library functions to read any given input and display
output on the console.
Before moving forward with input and output in C language, check these topics to understand the
concept better :
C Syntax Rules
Compile and Run C Program
Data Types in C
Variables in C
While dealing with input-output operations in C, we use the following two streams:
Standard input or stdin is used for taking input and Standard output or stdout is used for giving
output. The functions used for standard input and output are present in the stdio.h header file.
Hence, to use those functions, we need to include the stdio.h header file in our program, as shown
below.
#include <stdio.h>
C language offers us several built-in functions for performing input/output operations. Following are
the functions used for standard input and output:
52 | P a g e
4. gets() and puts() function
In C Language, output devices like computer monitor, printer, etc. are treated as files and the same
process is followed to write output to these devices as would have been followed to write the output
to a file.
The printf() function is the most used function in the C language. This function is defined in
the stdio.h header file and is used to show output on the console (standard output).
It writes the C string pointed by the format pointer to the standard output (stdout). On success,
the total number of characters written is returned.
This function is used to print a simple text sentence or value of any variable which can be
of int, char, float, or any other datatype.
1. Print a sentence
#include <stdio.h>
int main() {
// using printf()
printf("Welcome to Studytonight");
return 0;
53 | P a g e
}
Welcome to Studytonight
Run Code →
We have seen many code examples like above, up until now in this tutorial series.
To understand the complete code and structure of a basic C language program, check Hello World
Program in C.
We can use the printf() function to print integer value coming from a variable using the %d format
specifier.
For example,
#include <stdio.h>
int main() {
int x = 10;
// using printf()
return 0;
Value of x is: 10
Run Code →
54 | P a g e
In the program, above we have used the %d format specifier, to specify the type of the value that will
be added there. The format specifiers %d and %i are used for integer value.
The %c format specifier is used to print character variable value using the printf() function.
#include <stdio.h>
int main() {
// using printf()
return 0;
Run Code →
Inside the printf() function we have used a single quotation, it will work fine because we have used
double quotation outside. We can also use backslash character to escape the single quote like this \'
In the code example below, we have used the printf() function to print values of
a float and double variable.
For float value we use the %f format specifier and for double value we use the %lf format specifier.
#include <stdio.h>
int main() {
55 | P a g e
// using printf()
return 0;
Run Code →
We have used the \n Escape sequence which is used for newline at the end of the
first printf() statement so that the next printf() statement output is shown in the next line.
#include <stdio.h>
int main() {
return 0;
Run Code →
As you can see in the code example above, we can do formatting as well while printing values of
multiple variables using the printf() function.
We can also perform some simple calculations inside printf(). Here is a simple example for that,
#include <stdio.h>
int main()
int a = 5, b = 6;
printf("%d", a + b);
return 0;
11
57 | P a g e
When we want to take input from the user, we use the scanf() function and store the input value into a
variable.
It reads data from stdin and stores it according to the parameter format into the locations pointed by
the additional arguments. On success, the function returns the number of items of the argument
list successfully filled.
The scanf() function can be used to take any datatype input from user, all we have to take care is that
the variable in which we store the value should have the same datatype.
scanf("%x", &variable);
Using the format specifier, we tell the compiler what type of data is in a variable and & is the address
operator which tells the compiler the address of the variable so that the compiler can assign the
variable with the value entered by the user.
If we have to take an integer value input from the user, we have to define an integer variable and then
use the scanf() function.
#include <stdio.h>
int main() {
// using scanf()
int user_input;
58 | P a g e
printf("Please enter a number: ");
scanf("%d", &user_input);
return 0;
Run Code →
You entered: 7
While running the code example above, there is a button for Input at top-right corner of editor, you
can click on it and provide custom value for input.
In the above code example, we have used %d format specifier to inform the scanf() function that user
input will be of type int.
And we have also used & symbol before the name of the variable, because &user_input refers to the
address of the user_input variable where the input value will be stored.
Just like integer value, we can take input for any different datatype. Let's see an example for float type
value.
#include <stdio.h>
int main() {
// using scanf()
float user_input;
59 | P a g e
printf("Please enter a decimal number: ");
scanf("%f", &user_input);
return 0;
We have used the %f format specifier and defined a float type variable. Try doing the same for taking
a double type value as user input. The format specifier for double is %lf.
Let's see how we can take a simple character input from user.
#include <stdio.h>
int main() {
// using scanf()
char gender;
scanf("%c", &gender);
return 0;
60 | P a g e
}
Your gender: M
In the below code example, we are taking multiple inputs from the user and saving them into
different variables.
#include <stdio.h>
int main() {
char gender;
int age;
return 0;
61 | P a g e
The printf() function returns the number of characters printed by it, and scanf() function returns the
number of characters read by it.
int i = printf("studytonight");
studytonightValue of i is: 12
In this program printf("studytonight"); will return 12 as result, which will be stored in the variable i,
because the word studytonight has 12 characters.
The first printf() statement will print the statement studytonight on the output too.
Format Specifiers
To print values of different data types using the printf() statement and while taking input using
the scanf() function, it is mandatory to use format specifiers.
It is a way to tell the compiler what type of data is in a variable. Some examples are %c, %d, %f, etc.
62 | P a g e
The getchar() function reads a character from the terminal and returns it as an integer. This function
reads only a single character at a time.
int getchar(void);
You can use this method in a loop in case you want to read more than one character.
The putchar() function displays the character passed to it on the screen and returns the same
character. This function too displays only a single character at a time.
In case you want to display more than one character, use putchar() method in a loop.
#include <stdio.h>
void main( )
int c;
printf("Enter a character");
/*
store it in variable c
*/
c = getchar();
/*
*/
putchar(c);
When you will compile the above code, it will ask you to enter a value. When you will enter the value,
it will display the value you have entered.
The gets() function reads a line from stdin(standard input) into the buffer pointed to by str pointer,
until either a terminating newline or EOF (end of file) occurs.
The puts() function writes the string str with a newline character ('\n') at the end to stdout. On success,
a non-negative value is returned.
str is the pointer to an array of chars where the C string is stored. (Don't worry if you are not able to
understand this now.)
#include <stdio.h>
void main()
64 | P a g e
/* character array of length 100 */
char str[100];
gets(str);
puts(str);
getch();
return 0;
Studytonight
When you will compile the above code, it will ask you to enter a string. When you will enter the string,
it will display the value you have entered.
The gets() function is considered dangerous to use and should be avoided. We get a warning when we
compile any code in which we have used gets() function. This is because the function doesn't know
how big the buffer is, so it continues reading until it finds a newline or encounters EOF, and may
overflow the bounds of the buffer it was given. We can use alternatives to gets() function, like
the fgets() function.
It reads characters and stores them as a C string into str until (num-1) characters have been read or
either a newline or the end-of-file is reached, whichever happens first. A newline character
makes fgets stop reading, but it is considered a valid character by the function and included in the
string copied to str. On success, the function returns the str.
For example,
65 | P a g e
#include <stdio.h>
#define MAX 10
int main()
char str[MAX];
return 0;
abcdefghijkl
The main difference between these two functions is that scanf() stops reading characters when it
encounters a space, but gets() reads space as a character too.
If you enter a name as Study Tonight using scanf() it will only read and store Study and will leave the
part of the string after space. But gets() function will read it completely.
#include <stdio.h>
int main() {
// using scanf()
66 | P a g e
scanf("%s", n1);
return 0;
#include <stdio.h>
int main() {
// using scanf()
gets(n1);
return 0;
67 | P a g e
Conclusion
In this tutorial we learned about Input and Output in the C language. With many code examples, we
understood how to use printf() function and scanf() function to show output to user and take input
from the user.
We also learned about a few other functions used for showing output and taking user input.
Before moving forward with Operators in C language, we recommend you learn about C variables and
datatypes:
C Variables
C Literals
C Datatypes
Using C Datatypes (Examples)
Compile and run C Program
C Operators
Arithmetic operators
Relational operators
Logical operators
Bitwise operators
Assignment operators
Conditional operators
Special operators
Let's understand each one of these operator types, one by one with working code examples.
What is an Operand?
An operand is a value on which any operator works. For example, when we say 4+5, here,
numbers 4 and 5 are operands whereas + is an operator.
68 | P a g e
Different operators work with different numbers of operands like the + operator requires two
operands or values.
C Arithmetic Operators
The following table shows all the basic arithmetic operators along with their descriptions.
To learn in what order the arithemtic operators are executed, visit C Operator Precedence.
Let's see a code example to understand the use of the basic arithmetic operators in C programs.
#include <stdio.h>
int main() {
69 | P a g e
// addition
result = a+b;
// subtraction
result = a-b;
// multiplication
result = a*b;
// division
result = a/b;
return 0;
Addition of a & b = 73
Subtraction of a & b = 27
70 | P a g e
Multiplication of a & b = 1150
Division of a & b = 2
Run Code →
The modulus operator returns the remainder value after the division of the provided values.
#include <stdio.h>
int main() {
result = a%b;
printf("result = %d",result);
return 0;
result = 3
Run Code →
71 | P a g e
Example: Using Increment and Decrement Operators
The increment operator is used to increase the value of any numeric value by 1, whereas the
decrement operator is used to decrease the value of any numeric value by 1.
#include <stdio.h>
int main() {
/*
*/
/*
*/
72 | P a g e
// first print value of b, then increment b
return 0;
Incrementing value of a = 11
Decrementing value of b = 19
Decrementing value of a = 11
Value of a = 10
Incrementing value of b = 19
Value of b = 20
Run Code →
In the code example above, we have used the increment operator as ++a and b++, while the
decrement operator as --b and a--.
When we use the increment and decrement operator as a prefix (means before the operand), then
first the increment operation is done and that value is used, like in the first two printf() functions, we
get the updated values of a and b.
Whereas when we use the increment and decrement operators as postfix (means after the operand),
then first the larger expression is evaluated which is printf() in this case and then the value of the
operand is updated.
C RELATIONAL OPERATORS
73 | P a g e
The relational operators (or comparison operators) are used to check the relationship between two
operands. It checks whether two operands are equal or not equal or less than or greater than, etc.
For example, if we have two numbers 14 and 7, if we say 14 is greater than 7, this is true, hence this
check will return 1 as the result with relationship operators. On the other hand, if we say 14 is less
than 7, this is false, hence it will return 0.
The following table shows all relational operators supported in the C language.
>= check left operand is greater than or equal to the right a >= b, returns 0
operand
<= Check if the operand on left is smaller than or equal to the a <= b, returns 1
right operand
To learn in what order the relational operators are executed, visit C Operator Precedence.
When we use relational operators, then based on the result of the comparison done, if it's true, then
the output is 1 and if it's false, then the output is 0. We will see the same in the example below.
#include <stdio.h>
int main() {
74 | P a g e
// Equal
result = (a==b);
printf("(a == b) = %d \n",result);
// less than
result = (a<b);
// greater than
result = (a>b);
result = (a<=b);
return 0;
(a == b) = 0
(a < b) = 1
75 | P a g e
(a > b) = 0
(a <= b) = 1
Run Code →
In the code example above, a has value 10, and b has value 20, and then different comparisons are
done between them.
In the C language, true is any value other than zero. And false is zero.
C Logical Operators
These operators are used to perform logical operations and used with conditional statements like C if-
else statements.
1. With AND operator, only if both operands are true, the result is true.
2. With the OR operator, if a single operand is true, then the result will be true.
3. The NOT operator changes true to false, and false to true.
#include <stdio.h>
int main() {
int a = 1, b = 0, result;
76 | P a g e
// And
// Or
result = (a || b);
printf("a || b = %d \n",result);
// Not
result = !a;
printf("!a = %d \n",result);
return 0;
(a && b) = 0
(a || b) = 1
(!a) = 0
Run Code →
Bitwise Operators in C
77 | P a g e
Bitwise operators perform manipulations of data at the bit level. These operators also perform
the shifting of bits from right to left. Bitwise operators are not applied
to float or double, long double, void, etc.(Learn about C float and double datatype).
The following table contains the bitwise operators. There are 6 bitwise operators in the C language.
The bitwise AND, OR, and NOT operator works the same way as the Logical AND, OR, and NOT
operators, except that the bitwise operators work bit by bit.
Below we have a truth table for showing how these operators work with different values.
Bitwise operators can produce any arbitrary value as result. It is not mandatory that the result will
either be 0 or 1.
The bitwise shift operator shifts the bit value, either to the left or right. The left operand specifies
the value to be shifted and the right operand specifies the number of positions that the bits in the
value have to be shifted. Both operands have the same precedence.
Understand, how bits shift from left to right and vice versa.
a = 00010000
b = 2
a << b = 01000000
78 | P a g e
a >> b = 00000100
In case of a << b, 2 bits are shifted to left in 00010000 and additional zeros are added to the opposite
end, that is right, hence the value becomes 01000000
And for a >> b, 2 bits are shifted from the right, hence two zeros are removed from the right and two
are added on the left, hence the value becomes 00000100
Please note, shift doesn't work like rotating, which means, the bits shifted are not added at the other
end. The bits that are shifted are lost.
The one's complement operator, will change all the 1's in the operand to 0, and all the 0's are set to 1.
For example, if the orginal byte is 00101100, then after one's complement it will become 11010011.
#include <stdio.h>
int main() {
// <<
result = a<<b;
// >>
79 | P a g e
result = a>>b;
return 0;
a << b = 2048
a >> b = 128
Run Code →
C Assignment Operators
The sssignment operators are used to assign value to a variable. For example, if we want to assign a
value 10 to a variable x then we can do this by using the assignment operator like: x =
10; Here, = (equal to) operator is used to assign the value.
In the C language, the = (equal to) operator is used for assignment however it has several other
variants such as +=, -= to combine two operations in a single statement.
You can see all the assignment operators in the table given below.
80 | P a g e
/= divides left operand with the right a/=b, is same as a=a/b, value of a
operand and assign the result to left becomes 2
operand
%= calculate modulus using two a%=b, is same as a=a%b, value of a
operands and assign the result to left becomes 0
operand
When we combine the arithmetic operators with the assignment operator =, then we get
the shorthand form of all the arthmetic operators.
Below we have a code example in which we have used all the different forms of assignment operator,
starting from the basic assignment.
#include <stdio.h>
int main() {
int a = 10;
// Assign
int result = a;
printf("result = %d \n",result);
// += operator
result += a;
printf("result = %d \n",result);
81 | P a g e
// -= operator
result -= a;
printf("result = %d \n",result);
// *= operator
result *= a;
printf("result = %d \n",result);
return 0;
result = 10
result = 20
result = 10
result = 100
Run Code →
The ternary operator, also known as the conditional operators in the C language can be used for
statements of the form if-then-else.
82 | P a g e
The question mark ? in the syntax represents the if part.
The first expression (expression 1) returns either true or false, based on which it is decided
whether (expression 2) will be executed or (expression 3)
If (expression 1) returns true then the (expression 2) is executed.
If (expression 1) returns false then the expression on the right side of : i.e (expression 3) is
executed.
#include <stdio.h>
int main() {
*/
result = (a==b)?(a+b):(a-b);
printf("result = %d",result);
return 0;
83 | P a g e
}
result = 40
Run Code →
Apart from arithmetic, relational, logical, assignment, etc. operators, C language uses some other
operator such as:
1. sizeof operator
2. & operator
3. * operator
4. The . (dot) and -> (arrow) operators
5. [] operator, etc.
sizeof to find size of any entity(variable, array, etc.), & operator to find address of a variable, etc. You
can see a list of such operators in the below table.
84 | P a g e
We will learn about *, dot operator, arrow operator and [] operator as we move on in this tutorial
series, for now let's see how to use the sizeof and & operators.
Here is a code example, try running in the live code compiler using the Run code button.
#include <stdio.h>
int main() {
int a = 20;
char b = 'B';
double c = 17349494.249324;
// sizeof operator
// & operator
return 0;
85 | P a g e
}
Size of a is: 4
Size of b is: 1
Size of c is: 8
Run Code →
Operators are symbols known to the C compiler, which are used to perform operations on data.
Operators can be used to perform operation directly on some value(C Literals) or on C variables. In
the C language we can perform arithmetic operations, logical and relational operations, bitwise
operations, etc. using the C operators on data.
Arithmetic operators
Relational operators
Logical operators
Bitwise operators
Assignment operators
Ternary operator
Special operators like sizeof, &, *, . (dot) operator, -> (arrow) operator, [] (square bracket)
operator, etc.
86 | P a g e
The * operator in the C language is a unary operator that returns the value of the object located at
the address, specified after the * operator. For example q = *m will store the value stored at memory
address m in the q variable, if m contains a memory address.
The * operator is also used to perform multiplication of two values, where it acts as an arithmetic
operator.
It is a symbol of not equal to(!=) operator and used to check whether two values are not equal to each
other or not. It is a relational operator and its opposite operator is an equal(==) operator which is
used to check equality between two values or variables.
If two values are not equal, then we will get 1 as the result of the comparison.
Both are special types of operators and are used to perform memory-related operations.
The & operator is used to get the address of a variable and the * operator is the complement of
the & operator and is used to get the value of the object for located at a memory address.
It is a format specifier that is used to print formatted output to the console. In the C language, it is
used with the printf() function(C Input Output) to display integer value to the console. To print float, C
provides %f, for char we use %c, for double we use %lf, etc.
Conclusion:
In this tutorial, we learned all about the C language operators in detail along with a lot of code
examples to see all the operators in action.
C Operators Precedence
There are so many operators in C language, and we can use multiple operators together as well. Do
you know how we manage multiple operators present in a single expression? Do we perform addition
first, or multiplication, how do we decide it?
Based on the Precendence of operators, the C compiler decides the order in which the operators are
evaluated.
87 | P a g e
For example, if we have three variables a, b and c, then for the expression a+b*c, the compiler will first
multiply b and c, and then add the result of the multiplication with a, because the * operator
has higher precedence than the + operator.
Not all operators can be used together in a single expression, there are many such combinations that
are treated as semantically invalid. For example, c = a < b ? a++ : a = b can not be parsed because of
this rule. But many compilers ignore this and parse it as c = (((a < b) ? (a++) : a) = b), and then give an
error.
The concept of operator precedence is only relevant for the operators that can be used together, and
they are:
1. Arithmetic operators
2. Relational operators
3. Logical operators
Order of Precedence
Following is the standard table of precedence of operators with 1 being the highest precedence.
88 | P a g e
>, >= For relational operators > and ? respectively
Associativity
Operators that are in the same block (in the table above) are of the same precedence and thus they
are evaluated in the given direction known as associativity. For example, the expression x-y-z is
parsed as (x-y)-z, and not as x-(y-z) because of left-to-right associativity.
While the table above, holds every operator, but in general usage we mostly use arithmetic, logical
and relational operators.
The arithmetic operators hold higher precedence than the logical and relational operators.
This will return false because first the arithmetic operator + will be evaluated and then the
comparison will be done. The above expression is treated as 10 > (1+9).
Hence, because 10 is not greater than 10, but it is equal, so the expression will return false.
There are many arithmetic operators in the C language, and the order of precedence is applicable for
them too.
Operators on the same level of precedence are evaluated by the compiler from left to
right (associativity, remember).
#include <stdio.h>
int main() {
result = a * b + ++c;
90 | P a g e
return 0;
Run Code →
In the above code, first, ++c is evaluated because the increment operator has the highest precedence
(value becomes 31), then a*b is evaluated because next in order of precedence is the multiplication
operator (value becomes 200), then the + operator is evaluated (200 + 31), hence the result is 231.
In the case of the relational and logical operators, this order is followed:
Because first the NOT operator gets evaluated, which gives us 1, then 1 && 0 will give us 0, and then
finally 0 || 0 will also give us 0, which is false.
Using Parentheses
We can control the order of execution by using parentheses in our expressions. Taking the last
example, if we write the expression like this !(0 && 0) || 0, then the result will become true. Because
then first the expression 0 && 0, which is inside the parentheses gets evaluated, then
the NOT operator, and then the OR operator.
We can change the order of the arithmetic operators too, using the parentheses.
If there are multiple parentheses, then the innermost is executed first, then the second innermost and
similarly we go on to the outer parentheses.
91 | P a g e
Conclusion:
In this tutorial, we learned the order of precedence of the different C language operators along with
learning associativity and how using parentheses can change that.
Decision making in C
Decision making is about deciding the order of execution of statements based on certain conditions
or repeat a group of statements until certain specified conditions are met. C language handles
decision-making by supporting the following statements,
if statement
switch statement
goto statement
The if statement may be implemented in different forms depending on the complexity of conditions
to be tested. The different forms are,
1. Simple if statement
2. if....else statement
Simple if statement
if(expression)
statement inside;
92 | P a g e
}
statement outside;
If the expression returns true, then the statement-inside will be executed, otherwise statement-
inside is skipped and only the statement-outside is executed.
Example:
#include <stdio.h>
void main( )
int x, y;
x = 15;
y = 13;
if (x > y )
x is greater than y
if...else statement
93 | P a g e
if(expression)
statement block1;
else
statement block2;
Example:
#include <stdio.h>
void main( )
int x, y;
x = 15;
y = 18;
if (x > y )
94 | P a g e
else
y is greater than x
if( expression )
if( expression1 )
statement block1;
else
statement block2;
95 | P a g e
else
statement block3;
if expression is false then statement-block3 will be executed, otherwise the execution continues and
enters inside the first if to perform the check for the next if block, where if expression 1 is true
the statement-block1 is executed otherwise statement-block2 is executed.
Example:
#include <stdio.h>
void main( )
int a, b, c;
printf("Enter 3 numbers...");
if(a > b)
if(a > c)
else
{
96 | P a g e
printf("c is the greatest");
else
if(b > c)
else
else if ladder
if(expression1)
statement block1;
97 | P a g e
}
else if(expression2)
statement block2;
else if(expression3 )
statement block3;
else
default statement;
The expression is tested from the top(of the ladder) downwards. As soon as a true condition is found,
the statement associated with it is executed.
Example :
#include <stdio.h>
void main( )
int a;
printf("Enter a number...");
scanf("%d", &a);
98 | P a g e
if(a%5 == 0 && a%8 == 0)
else if(a%8 == 0)
printf("Divisible by 8");
else if(a%5 == 0)
printf("Divisible by 5");
else
printf("Divisible by none");
Points to Remember
1. In if statement, a single statement can be included without enclosing it into curly braces { ... }
2. int a = 5;
99 | P a g e
3. if(a > 4)
printf("success");
No curly braces are required in the above case, but if we have more than one statement
inside if condition, then we must enclose them inside curly braces.
4. == must be used for comparison in the expression of if condition, if you use = the expression
will always return true, because it performs assignment not comparison.
6. if(27)
printf("hello");
Switch statement in C
When you want to solve multiple option type problems, for example: Menu like program, where one
value is associated with each option and you need to choose only one at a time,
then, switch statement is used.
Switch statement is a control statement that allows us to choose only one choice among the many
given choices. The expression in switch evaluates to return an integral value, which is then compared
to the values present in different cases. It executes that block of code which matches the case value. If
there is no match, then default block is executed(if present). The general form of switch statement is,
switch(expression)
case value-1:
block-1;
break;
case value-2:
block-2;
100 | P a g e
break;
case value-3:
block-3;
break;
case value-4:
block-4;
break;
default:
default-block;
break;
1. The expression (after switch keyword) must yield an integer value i.e the expression should be
an integer or a variable or an expression that evaluates to an integer.
4. The next line, after the case statement, can be any valid C statement.
Points to Remember
1. We don't use those expressions to evaluate switch case, which may return floating point values
or strings or characters.
2. break statements are used to exit the switch block. It isn't necessary to use break after each
block, but if you do not use it, then all the consecutive blocks of code will get executed after
the matching block.
101 | P a g e
3. int i = 1;
4. switch(i)
5. {
6. case 1:
7. printf("A"); // No break
8. case 2:
9. printf("B"); // No break
10. case 3:
11. printf("C");
12. break;
A B C
The output was supposed to be only A because only the first case matches, but as there is
no break statement after that block, the next blocks are executed too, until it a break statement
in encountered or the execution reaches the end of the switch block.
13. default case is executed when none of the mentioned case matches the switch expression. The
default case can be placed anywhere in the switch case. Even if we don't include the default
case, switch statement works.
14. Nesting of switch statements are allowed, which means you can have switch statements inside
another switch block. However, nested switch statements should be avoided as it makes the
program more complex and less readable.
#include<stdio.h>
102 | P a g e
void main( )
int a, b, c, choice;
while(choice != 3)
scanf("%d", &choice);
switch(choice)
case 1:
printf("Enter 2 numbers");
c = a + b;
printf("%d", c);
break;
case 2:
103 | P a g e
printf("Enter 2 numbers");
c = a - b;
printf("%d", c);
break;
default:
if statements can evaluate float conditions. switch statements cannot evaluate float conditions.
if statement can evaluate relational operators. switch statement cannot evaluate relational
operators i.e they are not allowed in switch statement.
Loops in C
During programming, sometimes we might need to execute a certain code statement again and
again. We can write the code statement as many times as we need it to execute but that would be
very inefficient, because what if you want a code statement to execute a 100 times? This is why we use
loops.
In any programming language including C language, loops are used to execute a single statement or
a set of statements, repeatedly, until a particular condition is satisfied.
104 | P a g e
How Loops in C works?
As per the above diagram, if the Test Condition is true, then the loop is executed, and if it
is false then the execution breaks out of the loop. After the loop is successfully executed the
execution again starts from the Loop entry and again checks for the Test condition, and this keeps on
repeating.
The sequence of statements to be executed is kept inside the curly braces { } known as the Loop
body. After every execution of the loop body, condition is verified, and if it is found to be true the
loop body is executed again. When the condition check returns false, the loop body is not executed,
and execution breaks out of the loop.
In this kind of loop, the condition is checked before executing the loop's body. So, if the condition is
never true, it won't execute even once. For example, for and while loop.
In this kind of loop, the condition is checked after the loop's body is executed, i.e., in the end. Hence,
even if the condition is not fulfilled, this loop will execute one time. The do-while loop is an example
of exit controlled loop.
Types of Loop in C
1. while loop
2. for loop
3. do while loop
105 | P a g e
1. while loop in C
variable initialization;
while(condition)
statements;
The following flowchart shows the flow of execution when we use a while loop.
Here, we can see that firstly, we initialize our iterator. Then we check the condition of while loop. If it
is false, we exit the loop and if it is true, we enter the loop. After entering the loop, we execute the
statements inside the while loop, update the iterator and then again check the condition. We do the
same thing unless the condition is false.
In this program we will use the while looop to print a word a given number of time.
#include <stdio.h>
int main()
106 | P a g e
int n;
scanf("%d", &n);
char name[30];
scanf("%s", name);
while(n) {
printf("%s\n", name);
n--; //decrementing n
return 0;
studytonight
studytonight
studytonight
Run Code →
107 | P a g e
Now, we reach the while loop so we check the condition; n = 3, which is nonzero, so we enter the
loop. We execute the printf() statement and print name on the console and then decrement n, so now
n = 2. We again check the condition; n = 2, which is nonzero, so we enter the loop and print name
and decrement n. Now n = 1. We check the condition again; n is 1 which is nonzero so we again enter
the loop and execute the statements. Now we have n = 0. We check the condition; n is zero now so
we don't enter the loop. We exit the loop and start executing the statements after it.
#include<stdio.h>
void main( )
int x;
x = 1;
printf("%d\t", x);
x++;
1 2 3 4 5 6 7 8 9 10
108 | P a g e
2. for loop in C
The for loop in C is used to execute a set of statements repeatedly until a particular condition is
satisfied. We can say it is an open ended loop. General format is,
statement-block;
In the for loop in C language, we have exactly two mandatory semicolons, one after initialization and
second after the condition. In this loop we can have more than one initialization or
increment/decrement as well, separated using comma operator. But it can have only one condition.
4. Then it evaluate the increment/decrement condition and again follows from step 2.
We first initialize our iterator. Then we check the condition of the loop. If it is false, we exit the loop
and if it is true, we enter the loop. After entering the loop, we execute the statements inside
the for loop, update the iterator and then again check the condition. We do the same thing unless the
test condition returns false.
#include <stdio.h>
int main()
109 | P a g e
{
int n;
scanf("%d", &n);
char name[25];
scanf("%s", name);
printf("%s\n", name);
return 0;
studytonight
studytonight
Run Code →
Now, we reach the for loop so we initialize i with 1. We check the condition; 1 <= 3, so we enter the
loop. We execute the printf() statement and print name on the console. We again reach the for loop.
We increment i by 1; so now i = 2. We again check the condition; 2 <= 3, so we enter the loop and
print name. Now i is incremented again to 3. We check the condition again; 3 <= 3, so we enter the
110 | P a g e
loop and execute the statements. Now we have i = 4. We check the condition; 4 > 3, so we don't enter
the loop. We exit the loop and start executing the statements after it.
#include<stdio.h>
void main( )
int x;
printf("%d\t", x);
1 2 3 4 5 6 7 8 9 10
We can also have nested for loops, i.e one for loop inside another for loop in C language. This type of
loop is generally used while working with multi-dimensional arrays. To learn more about arrays and
how for loops are used in arrays, check out our tutorial on arrays in C. Basic syntax for nested for loop
is,
{
111 | P a g e
for(initialization; condition; increment/decrement)
statement ;
#include<stdio.h>
void main( )
int i, j;
printf("\n");
printf("%d", j);
112 | P a g e
}
21
321
4321
54321
4. do while loop in C
In some situations it is necessary to execute body of the loop once before testing the condition. Such
situations can be handled with the help of do-while loop. The do statement evaluates the body of the
loop first and at the end, the condition is checked using while statement. It means that the body of
the loop will be executed at least once, even though the starting condition inside while is initialized to
be false. General syntax is,
do
.....
.....
while(condition)
Remember that the semicolon at the end of do-while loop is mandatory. It denotes end of the loop.
113 | P a g e
We initialize our iterator. Then we enter body of the do-while loop. We execute the statement and
then reach the end. At the end, we check the condition of the loop. If it is false, we exit the loop and if
it is true, we enter the loop. We keep repeating the same thing unless the condition turns false.
#include <stdio.h>
int main()
int n;
scanf("%d", &n);
char name[25];
scanf("%s", name);
do{
printf("%s\n", name);
n--;
return 0;
studytonight
114 | P a g e
Run Code →
Now, we enter the do-while loop because we check the condition only at the end. When we reach the
end, we check the condition; n = 10, which is greater than zero, so we exit the loop and start
executing the statements after it. Here we can see that even if the condition was always false, the
loop got executed once.
#include<stdio.h>
void main()
int a, i;
a = 5;
i = 1;
do
printf("%d\t", a*i);
i++;
115 | P a g e
5 10 15 20 25 30 35 40 45 50
Infinite Loops in C
We come across infinite loops in our code when the compiler does not know where to stop. It does
not have an exit. This means that either there is no condition to be checked or the condition is
incorrect. This is why an iterator is very important in our loops. And a proper condition that ends.
#include <stdio.h>
int main()
for(int i = 0; ; i++)
printf("Infinite loop\n");
return 0;
The above code has no condition in place, hence it will keep on executing.
#include <stdio.h>
int main()
int i = 0;
while(i == 0)
printf("Infinite loop\n");
return 0;
116 | P a g e
}
In the code above, we are not changing the value on i, hence the condition in the while loop will never
fail.
#include <stdio.h>
int main()
do{
printf("Infinite loop\n");
} while(1);
return 0;
Another example, with a constant value as condition, which is always true hence the code will keep on
executing.
Sometimes, while executing a loop, it becomes necessary to skip a part of the loop or to leave the
loop as soon as certain condition becomes true. This is known as jumping out of loop.
1. break statement in C
When break statement is encountered inside a loop, the loop is immediately exited and the program
continues to execute with the statements after the loop.
#include <stdio.h>
117 | P a g e
int main()
int n;
scanf("%d", &n);
char name[25];
scanf("%s", name);
if(i % 5 == 0)
break;
printf("%s\n", name);
return 0;
studytonight
studytonight
studytonight
studytonight
118 | P a g e
In the above code, as soon as we find an index which is divisible by 5, the loop breaks and control is
shifted out of the loop.
2. continue statement in C
It causes the control to go directly to the test-condition and then continue the loop execution. On
encountering continue, the execution leaves the current cycle of loop, and starts with the next cycle.
#include <stdio.h>
int main()
int n;
scanf("%d", &n);
char name[25];
scanf("%s", name);
if(i % 2 == 0)
continue;
printf("%d : %s\n",i,name);
return 0;
119 | P a g e
}
1 : studytonight
3 : studytonight
5 : studytonight
In the above example, whenever we come across an even index, we move on to the next index
because of the continue statement.
Conclusion
In this tutorial, we have learned about for, while and do-while loops in C and why they are important,
along with seeing them in action with multiple code examples. We also learnt
about break and continue statements.
Arrays in C
In C language, arrays are referred to as structured data types. An array is defined as finite ordered
collection of homogenous data, stored in contiguous memory locations.
Following are some usecases where using an array will make things simpler:
120 | P a g e
Since arrays provide an easy way to represent data, it is classified amongst the data structures in C.
Other data structures in c are structure, lists, queues, trees etc.
Array is a linear data structure which means that the elements in an array are stored in a continuous
manner in the memory. This makes accessing the elements easier. Array elements are indexed in an
order, starting from 0 to n-1, where n is the size of the array.
Suppose we have a classroom of 50 students. Our array will consist of 50 elements with indexes
from 0 to 49, where one place will be there for every student's data.
Arrays can be single or multi dimensional. The number of dimensions in an array is equal to the
number of indexing. A 2-D array (also called a matrix) has two indexes(one for row and other for
column) and so on.
Arrays make our work easy because instead of declaring 100 variables, we can declare an array of size
100.
Advantages of Arrays
In one go, we can initialise storage for more than one value. Because you can create an array of
10, 100 or 1000 values.
They make accessing elements easier by providing random access. By random access we mean
you can directly access any element in an array if you know its index.
Sorting and searching operations are easy on arrays.
Disadvantages of Arrays
Due to its fixed size, we cannot increase the size of an array during runtime. That means once
you have created an array, then it's size cannot be changed.
Insertion and deletion of elements can be costly, in terms of time taken.
Declaring Arrays in C
Like any other variable, arrays must be declared(created) before they are used. General form of array
declaration is,
data-type variable-name[size];
121 | P a g e
/* Example of array declaration */
In the code above, in the first line, char is the data type, a is the name of array and 5 is the size.
In the next line, float is the data type, ar is the name of the array and size of array is 9.
And in the last line of code, int is the data types, and arr is the name of the array and 10 is the size of
array. It means array arr can only contain 10 elements of int type.
The index of an array starts from 0 to size-1 i.e first element of any array will be stored
at arr[0] address and the last element will be at arr[size - 1].
Initialization of Array in C
After an array is declared it must be initialized. Otherwise, it will contain garbage value(any random
value). An array can be initialized at either compile time or at runtime. That means, either we can
provide values to the array in the code itself, or we can add user input value into the array.
Compile time initialization of array means we provide the value for the array in the code, when we
create the array,
/* Here are a few examples */ int marks[4] = { 67, 87, 56, 77 }; // integer array initialization float area[5]
= { 23.4, 6.8, 5.5 }; // float array initialization int marks[4] = { 67, 87, 56, 77, 59 }; // Compile time error
One important thing to remember is that when you will give more values(array elements) than the
declared array size than the compiler will give an error.
122 | P a g e
#include<stdio.h>
void main()
int i;
printf("%d\t",arr[i]);
2 3 4
An array can also be initialized at runtime using scanf() function. This approach is usually used for
initializing large arrays, or to initialize arrays with user specified values.
To input elements in an array, we can use a for loop or insert elements at a specific index.
123 | P a g e
Arr[i] = i;
Here i refers to the index of the elements, starting from 0 and ending at 9 which is less than 10. In
each element, we store the value of its index.
scanf("%d", &Arr[i]);
scanf("%d", &Arr[i]);
Notice that in the above example, we are incrementing i by 2 each time, i+=2 means i = i + 2. So we
input only even indexed elements like Arrr[0], Arr[2], and so on.
We already know how to access array elements. Yes, it is using the indexes. So let's see a few
examples where we will print entire arrays or some specific values, etc.
printf("%d", Arr[i]);
printf("%d", Arr[i]);
124 | P a g e
If we try to access elements, on index which is more than the size of an array or less than 0, we won't
get an error but we will get wrong output (some random garbage value).
Array Programs in C
#include<stdio.h>
void main(){
int arr[5];
scanf("%d", &arr[i]);
int sum = 0;
sum += arr[i];
125 | P a g e
Enter array elements:3 2 4 1 5
Sum =15
#include <stdio.h>
int main()
arr2[i] = arr1[i];
return 0;
If you were thinking that we can assign values from an array to another using an assignment
operator, like we do in variables, NO you can't.
126 | P a g e
We can also create boolean arrays in C. Unlike other data types, boolean arrays have only two values,
i.e., true(1) and false(0). Please note that in order to use bool, we use <stdbool.h> header file in our
code. Also, there is no format specifier for bool in C. We use %d for input/output.
Suppose a teacher wants to store the data of assignment submission of her class of 5 students. To do
so, she makes use of a boolean array where she inputs "yes" or "no" corresponding to the respective
roll numbers. Following is the code for this example.
#include <stdio.h>
#include <stdbool.h>
int main()
return 0;
1 : 0
2 : 1
3 : 1
4 : 0
5 : 1
127 | P a g e
Two dimensional Arrays
C language supports multidimensional arrays too. The simplest form of a multidimensional array is
the two-dimensional array. Here, we have a row index and a column index. Both the row's and
column's index begins from 0.
Just like a single-dimensional array, we can do Compile time initialization of two dimensional arrays or
runtime initialization of two dimensional arrays.
data-type array-name[row-size][column-size]
Please note and remember, the first [] holds row count and second [] holds column count.
double arr[5][5];
int a[3][4];
If you want to do Compile time initialization of two dimensional array, then here is an example,
int arr[][3] = {
{0,0,0},
{1,1,1}
};
char a[][2] = {
{'a', 'b'},
{'c', 'd'}
};
128 | P a g e
Note: We have not assigned any row value to our arrays in the above example. It means we can
initialize any number of rows. But, we must always specify number of columns, else it will give a
compile time error. Here, a 2*3 multi-dimensional matrix is created.
As you can see in the example above, first the values are stored in columns, and then if there is any
extra value, it goes to next row.
Now let's see how we can initialize a two dimensional array at runtime.
#include<stdio.h>
void main()
int arr[3][4];
int i, j, k;
scanf("%d", &arr[i][j]);
}
129 | P a g e
}
printf("%d", arr[i][j]);
1 2 3 4 5 6 7 8 9 10 11 12
1 2 3 4 5 6 7 8 9 10 11 12
Using the first for loop, we first access the row of the matrix(2D array) and in that particular row, we
traverse each column using the inner for loop.
Understanding how we access elements in a 2-D array can be tricky. Let us suppose we have an array
arr[2][3] with 2 rows and 3 columns.
We use i to access the rows of our matrix. In the outer loop(line 7), we initialize i as 0 which means we
are accessing the first row currently. Now in this for loop, we have an inner loop(line 9) which iterates
over j and is used to access columns. So for i = 0 (the first row), we traverse across j (from 0 to 2).
When we enter the inner loop, we have already fixed the value of i as 0 and now we iterate over j and
keep incrementing the values.
On line 12, we come out of the inner loop when j = number of columns. We check the condition of
the outer loop. If i = number of rows, we exit the loop otherwise we enter it again with an
incremented i. In the similar way, we access all elements of a matrix.
printf("%d", arr[i][j]);
printf(“\n”);
Let's suppose we want to calculate the total marks of all students in a class. We can do it by using a
matrix. Here, the number of rows will represent the number of students and the number of columns
will represent the subjects.
So first we'll input marks for the first student in all 3 subjects, then the second and so on. We'll sum
the marks rowwise and store it in a separate array.
#include <stdio.h>
int main()
scanf("%f", &marks[i][j]);
131 | P a g e
}
float sum = 0;
sum += marks[i][j];
total[i] = sum;
return 0;
1 : 8.000000
2 : 17.900002
Similarly, we can reverse an array, find out the maximum and minimum in an array and perform many
other operations.
If you want to learn about string and char arrays, click here.
132 | P a g e
You can find more programs for array in C to practice.
If you don't know what an array in C means, you can check the C Array tutorial to know about Array in
the C language. Before proceeding further, check the following articles:
C Function Calls
C Variables
C Datatypes
C Syntax Rules
For example: The string "home" contains 5 characters including the '\0' character which is
automatically added by the compiler at the end of the string.
// valid
133 | P a g e
// Illegal
char str[4];
str = "hello";
char str[20];
printf("Enter a string");
scanf("%[^\n]", &str);
printf("%s", str);
char text[20];
gets(text);
printf("%s", text);
C language supports a large number of string handling functions that can be used to carry out many
of the string manipulations. These functions are packaged in the string.h library. Hence, you must
include string.h header file in your programs to use these functions.
134 | P a g e
The following are the most commonly used string handling functions.
Method Description
strcat() It is used to concatenate(combine) two strings
strlen() It is used to show the length of a string
strrev() It is used to show the reverse of a string
strcpy() Copies one string into another
strcmp() It is used to compare two string
strcat() function in C:
Syntax:
strcat("hello", "world");
strcat() will add the string "world" to "hello" i.e ouput = helloworld.
135 | P a g e
strlen() will return the length of the string passed to it and strcmp() will return the ASCII difference
between first unmatching character of two strings.
int j = strlen("studytonight");
printf("%d %d",j,i);
12 -1
strcpy() function:
#include<stdio.h>
#include<string.h>
int main()
136 | P a g e
char s1[50], s2[50];
strcpy(s1, "StudyTonight");
strcpy(s2, s1);
printf("%s\n", s2);
return(0);
StudyTonight
strrev() function:
#include <stdio.h>
137 | P a g e
int main()
char s1[50];
gets(s1);
return(0);
Related Tutorials:
C Array
C Functions
C Pointers
C Structures
Storage classes in C
In C language, each variable has a storage class which decides the following things:
scope i.e where the value of the variable would be available inside a program.
default initial value i.e if we do not explicitly initialize that variable, what will be its default
initial value.
lifetime of that variable i.e for how long will that variable exist.
1. Automatic variables
138 | P a g e
2. External variables
3. Static variables
4. Register variables
Scope: Variable defined with auto storage class are local to the function block inside which they are
defined.
Lifetime: Till the end of the function/method block where the variable is defined.
A variable declared inside a function without any storage class specification, is by default
an automatic variable. They are created when a function is called and are
destroyed automatically when the function's execution is completed. Automatic variables can also be
called local variables because they are local to a function. By default they are assigned garbage
value by the compiler.
#include<stdio.h>
void main()
int detail;
// or
139 | P a g e
Scope: Global i.e everywhere in the program. These variables are not bound by any function, they are
available everywhere.
Lifetime: Till the program doesn't finish its execution, you can access global variables.
A variable that is declared outside any function is a Global Variable. Global variables remain available
throughout the program execution. By default, initial value of the Global variable is 0(zero). One
important thing to remember about global variable is that their values can be changed by any
function in the program.
#include<stdio.h>
void main()
number = 10;
/* This is function 1 */
fun1()
number = 20;
140 | P a g e
printf("I am in function fun1. My value is %d", number);
/* This is function 1 */
fun2()
Here the global variable number is available to all three functions and thus, if one function changes the
value of the variable, it gets changed in every function.
Note: Declaring the storage class as global or external for all the variables in a program can waste a
lot of memory space because these variables have a lifetime till the end of the program. Thus,
variables, which are not needed till the end of the program, will still occupy the memory and thus,
memory will be wasted.
extern keyword
The extern keyword is used with a variable to inform the compiler that this variable is declared
somewhere else. The extern declaration does not allocate storage for variables.
int main()
{
141 | P a g e
a = 10; //Error: cannot find definition of variable 'a'
printf("%d", a);
int main()
x = 10;
printf("%d", x);
Static variables
A static variable tells the compiler to persist/save the variable until the end of program. Instead of
creating and destroying a variable every time when it comes into and goes out of scope, static variable
is initialized only once and remains into existence till the end of the program. A static variable can
either be internal or external depending upon the place of declaration. Scope of internal
static variable remains inside the function in which it is defined. External static variables remain
restricted to scope of file in which they are declared.
#include<stdio.h>
142 | P a g e
void test(); //Function declaration (discussed in next topic)
int main()
test();
test();
test();
void test()
a = a + 1;
printf("%d\t",a);
1 2 3
Register variable
Register variables inform the compiler to store the variable in CPU register instead of memory.
Register variables have faster accessibility than a normal variable. Generally, the frequently used
variables are kept in registers. But only a few variables can be placed inside registers. One application
of register storage class can be in using loops, where the variable gets used a number of times in the
program, in a very short span of time.
Syntax :
Note: Even though we have declared the storage class of our variable number as register, we cannot
surely say that the value of the variable would be stored in a register. This is because the number of
registers in a CPU are limited. Also, CPU registers are meant to do a lot of important work. Thus,
sometimes they may not be free. In such scenario, the variable works as if its storage class is auto.
To improve the speed of execution of the program and to carefully use the memory space occupied
by the variables, following points should be kept in mind while using storage classes:
We should use static storage class only when we want the value of the variable to remain same
every time we call it using different function calls.
We should use register storage class only for those variables that are used in our program very
oftenly. CPU registers are limited and thus should be used carefully.
We should use external or global storage class only for those variables that are being used by
almost all the functions in the program.
If we do not have the purpose of any of the above mentioned storage classes, then we should
use the automatic storage class.
Functions in C
A function is a block of code that performs a particular task.
144 | P a g e
There are many situations where we might need to write same line of code for more than once in a
program. This may lead to unnecessary repetition of code, bugs and even becomes boring for the
programmer. So, C language provides an approach in which you can declare and define a group of
statements once in the form of a function and it can be called and used whenever required.
These functions defined by the user are also know as User-defined Functions
1. Library functions
2. User-defined functions
Library functions are those functions which are already defined in C library,
example printf(), scanf(), strcat() etc. You just need to include appropriate header files to use these
functions. These are already declared and defined in C libraries.
A User-defined functions on the other hand, are those functions which are defined by the user at the
time of writing program. These functions are made for code reusability and for saving time and space.
2. It makes your code reusable. You just have to call the function by its name to use it, wherever
required.
3. In case of large programs with thousands of code lines, debugging and editing becomes easier
if you use functions.
Function Declaration
145 | P a g e
Like any variable or an array, a function must also be declared before its used. Function declaration
informs the compiler about the function name, parameters is accept, and its return type. The actual
body of the function can be defined separately. It's also called as Function Prototyping. Function
declaration consists of 4 parts.
returntype
function name
parameter list
terminating semicolon
returntype
When a function is declared to perform some sort of calculation or any operation and is expected to
provide with some result at the end, in such cases, a return statement is added at the end of function
body. Return type specifies the type of value(int, float, char, double) that function is expected to return
to the program which called the function.
Note: In case your function doesn't return any value, the return type would be void.
functionName
Function name is an identifier and it specifies the name of the function. The function name is any valid
C identifier and therefore must follow the same naming rules like other variables in C language.
parameter list
The parameter list declares the type and number of arguments that the function expects when it is
called. Also, the parameters in the parameter list receives the argument values when the function is
called. They are often referred as formal parameters.
Let's write a simple program with a main() function, and a user defined function to multiply two
numbers, which will be called from the main() function.
#include<stdio.h>
146 | P a g e
int multiply(int a, int b); // function declaration
int main()
int i, j, result;
return 0;
147 | P a g e
Just like in the example above, the general syntax of function definition is,
Note: While defining a function, there is no semicolon(;) after the parenthesis in the function header,
unlike while declaring the function or calling the function.
functionbody
The function body contains the declarations and the statements(algorithm) necessary for performing
the required task. The body is enclosed within curly braces { ... } and consists of three parts.
a return statement to return the result evaluated by the function(if return type is void, then no
return statement is required).
Calling a function
When a function is called, control of the program gets transferred to the function.
functionName(argument1, argument2,...);
In the example above, the statement multiply(i, j); inside the main() function is function call.
148 | P a g e
Arguments are the values specified during the function call, for which the formal parameters are
declared while defining the function.
It is possible to have a function with parameters but no return type. It is not necessary, that if a
function accepts parameter(s), it must return a result too.
While declaring the function, we have declared two parameters a and b of type int. Therefore, while
calling that function, we need to pass two arguments, else we will get compilation error. And the two
arguments passed should be received in the function definition, which means that the function
header in the function definition should have the two parameters to hold the argument values. These
received arguments are also known as formal parameters. The name of the variables while declaring,
calling and defining a function can be different.
A function may or may not return a result. But if it does, we must use the return statement to output
the result. return statement also ends the function execution, hence it must be the last statement of
any function. If you write any statement after the return statement, it won't be executed.
The datatype of the value returned using the return statement should be same as the return type
mentioned at function declaration and definition. If any of it mismatches, you will get compilation
error.
In the next tutorial, we will learn about the different types of user defined functions in C language and
the concept of Nesting of functions which is used in recursion.
Functions in C
A function is a block of code that performs a particular task.
There are many situations where we might need to write same line of code for more than once in a
program. This may lead to unnecessary repetition of code, bugs and even becomes boring for the
149 | P a g e
programmer. So, C language provides an approach in which you can declare and define a group of
statements once in the form of a function and it can be called and used whenever required.
These functions defined by the user are also know as User-defined Functions
1. Library functions
2. User-defined functions
Library functions are those functions which are already defined in C library,
example printf(), scanf(), strcat() etc. You just need to include appropriate header files to use these
functions. These are already declared and defined in C libraries.
A User-defined functions on the other hand, are those functions which are defined by the user at the
time of writing program. These functions are made for code reusability and for saving time and space.
2. It makes your code reusable. You just have to call the function by its name to use it, wherever
required.
3. In case of large programs with thousands of code lines, debugging and editing becomes easier
if you use functions.
Function Declaration
150 | P a g e
Like any variable or an array, a function must also be declared before its used. Function declaration
informs the compiler about the function name, parameters is accept, and its return type. The actual
body of the function can be defined separately. It's also called as Function Prototyping. Function
declaration consists of 4 parts.
returntype
function name
parameter list
terminating semicolon
returntype
When a function is declared to perform some sort of calculation or any operation and is expected to
provide with some result at the end, in such cases, a return statement is added at the end of function
body. Return type specifies the type of value(int, float, char, double) that function is expected to return
to the program which called the function.
Note: In case your function doesn't return any value, the return type would be void.
functionName
Function name is an identifier and it specifies the name of the function. The function name is any valid
C identifier and therefore must follow the same naming rules like other variables in C language.
parameter list
The parameter list declares the type and number of arguments that the function expects when it is
called. Also, the parameters in the parameter list receives the argument values when the function is
called. They are often referred as formal parameters.
Let's write a simple program with a main() function, and a user defined function to multiply two
numbers, which will be called from the main() function.
#include<stdio.h>
151 | P a g e
int multiply(int a, int b); // function declaration
int main()
int i, j, result;
return 0;
152 | P a g e
Just like in the example above, the general syntax of function definition is,
Note: While defining a function, there is no semicolon(;) after the parenthesis in the function header,
unlike while declaring the function or calling the function.
functionbody
The function body contains the declarations and the statements(algorithm) necessary for performing
the required task. The body is enclosed within curly braces { ... } and consists of three parts.
a return statement to return the result evaluated by the function(if return type is void, then no
return statement is required).
Calling a function
When a function is called, control of the program gets transferred to the function.
functionName(argument1, argument2,...);
In the example above, the statement multiply(i, j); inside the main() function is function call.
153 | P a g e
Arguments are the values specified during the function call, for which the formal parameters are
declared while defining the function.
It is possible to have a function with parameters but no return type. It is not necessary, that if a
function accepts parameter(s), it must return a result too.
While declaring the function, we have declared two parameters a and b of type int. Therefore, while
calling that function, we need to pass two arguments, else we will get compilation error. And the two
arguments passed should be received in the function definition, which means that the function
header in the function definition should have the two parameters to hold the argument values. These
received arguments are also known as formal parameters. The name of the variables while declaring,
calling and defining a function can be different.
A function may or may not return a result. But if it does, we must use the return statement to output
the result. return statement also ends the function execution, hence it must be the last statement of
any function. If you write any statement after the return statement, it won't be executed.
The datatype of the value returned using the return statement should be same as the return type
mentioned at function declaration and definition. If any of it mismatches, you will get compilation
error.
In the next tutorial, we will learn about the different types of user defined functions in C language and
the concept of Nesting of functions which is used in recursion.
154 | P a g e