[go: up one dir, main page]

0% found this document useful (0 votes)
7 views154 pages

Tutorial for C Language

This document serves as a comprehensive tutorial on the C programming language, detailing its history, features, and applications. Developed by Dennis Ritchie in 1972, C has evolved through various standards, with the latest being C11 introduced in 2018. The tutorial covers fundamental concepts, practical programming examples, and frequently asked questions to aid beginners in learning C.

Uploaded by

q9r27v5bxs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views154 pages

Tutorial for C Language

This document serves as a comprehensive tutorial on the C programming language, detailing its history, features, and applications. Developed by Dennis Ritchie in 1972, C has evolved through various standards, with the latest being C11 introduced in 2018. The tutorial covers fundamental concepts, practical programming examples, and frequently asked questions to aid beginners in learning C.

Uploaded by

q9r27v5bxs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 154

C PROGRAMMING 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.

C Language is a middle-level, structured programming language, that needs a compiler for


running the programs written in C language. Do not worry about these terms, we will cover all of
them in detail in this tutorial.

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 1989, the language was formalized by American National Standard Institute(ANSI).

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.

Why is C Language so popular?

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.

What will we learn in this tutorial series?

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.

1. What is 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).

2. What are the features of the C language?

C is one of the most popular programming languages. It has many features:

 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

3. What is the C language used for?

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.

C is a general-purpose programming language. It is used for enterprise applications, games,


graphics, and applications requiring calculations, or simple software, etc.

3|Page
4. Where is C used today?

C is used for developing operating systems and Kernel-level programs.

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.

Let's talk about all these features one by one.

1. Simple and Efficient

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.

Hence, we can say that the C language is portable.

3. Structured Programming 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.

5. Rich Standard Library

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.

These libraries are called Header files in C language.

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.

This makes compilation fast.

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

The C programming language brings together the best of both worlds.

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.

Hence, the C programming language is said to be a Middle-level programming Language, allows


manipulation of bits, bytes, and addresses, hence providing low-level access to the computer systems,
while being easy to use, portable, and supporting all other features of a High-level language, etc.

9. Syntax Based Language

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.

10. Format Free Language

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.

11. Compiled Language

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.

12. Case sensitive Language

In C, the uppercase and lowercase characters are different. That means if is not the same as IF in C
language.

Frequently Asked Questions(FAQ)

Here are some frequently asked questions, that beginners have when they learn about features of the
C language.

1. What are the main 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.

2. What is the main reason behind the popularity of the C language?

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.

3. Why is C considered a Powerful 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.

5. What are the advantages of C Language?

Given below are some of the advantages of the C language:

a) C is a Portable language.

b) It provides rich support of built-in functions.

c) It is a powerful and efficient 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.

FIRST C PROGRAM AND ITS STRUCTURE


In this tutorial, we will learn to create the first C program and then will understand its structure. First
of all, let's have a look at how to write a simple and most basic Hello World program in C language.
Let's get started.

Here is the program for printing "Hello World" in C language.

#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.

Understanding Structure of the C Program

Given below are some of the different parts of a C Program:

 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.

Similarly, we can include any number of header files.

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.

All header files will have .h extension.

10 | P a g e
3. The main() Function

The main() function is a function that must be there in every C program.

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.

We will learn what functions in C language are in upcoming tutorials.

4. The printf() 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.

How to write a C program on my Computer?

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.

Frequently Asked Questions (FAQ)

1. Name different preprocessors in C programming Language?

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.

2. What do you understand by the main() function in C language?

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.

3. How comments can be added to a C program?

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 */.

4. What is stdio.h in C program?

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.

COMPILE AND RUN C PROGRAM


To compile and run a C language program, you need a C compiler. A compiler is a software that is
used to compile and execute programs. To set up a C language compiler in your Computer/laptop,
there are two ways:

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

Using an IDE - Turbo C

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.

Step 5: Output is here.

Run C Program Without using any IDE

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.

Frequently Asked Questions(FAQ)

1. What do you understand by the process of compilation?

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.

2. Name the keys used in Turbo C to compile the code.

ALT + F9 is used in turbo C in order to compile the code.

3. How is a C program run?

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.

4. Where can I write and run the C program?

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.

C SOURCE CODE COMPILATION PROCESS


The C source code compilation process is a multi-step process, which involves pre-
processing, compiling of code, linking of libraries, etc. In this tutorial, we will learn how the C code
is compiled into object code.

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.

Step 0: Pre-processing of the source file

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:

 It will remove the comments from the source code.


 It will perform the Macro expansion if any Macro is used (Do not worry about Macros, we will
learn about them later)
 It will perform the expansion of the included header files.

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.

Some of the preprocessor directives are as follows:

1. #include

To include a particular header using the name of the header file into the C language program code.

2. #define

This is used to define a MACRO in the C language.

3. #error

This preprocessor command is used to print the error message.

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.

Frequently Asked Questions

Here are some frequently asked questions related to the C language compilation process.

Q1. What do you understand by the term Compiler?

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.

Q3. What is the other name of the .c file?

The C language code files which have extension .c are also called the source code file.

Q4. What is the role of Linker?

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.

Q5. What are the steps of compilation in the C Language?

Following are the steps of compilation in the C language:

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.

Let's take an example,

#include <stdio.h>

int main()

printf("Hello,World");

return 0;
21 | P a g e
}

In the above code, if we take the printf statement:

printf("Hello,World");

Then the tokens in this statement are: printf, (, "Hello,World", ) and ;.

So the C tokens are basically the building blocks of a C program.

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.

Statement ends with Semicolon (;)

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;

error: expected ';' before 'return'

return 0;
22 | P a g e
^

command terminated with exit code 1

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.

Adding Comments to Code

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.

Adding comments makes the code more readable.

There are two ways in which we can write comments.

1. Using //: This is used to write a single-line comment.


2. Using /* */: Anything enclosed within /* and */ , will treated as multi-line comments.

You can even comment out code using these two techniques and that statement or part of code will
not get compiled and executed.

Example of comments in C language:

Here is a simple program to show how to use comments:

/*

This is my first program.

I am very excited!

*/

#include <stdio.h>

int main()

23 | P a g e
{

// Printing Hello World

printf("Hello,World");

// printf("Useless piece of code.");

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.

More Syntax rules for the C Language

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.

 C is a case-sensitive language so all C instructions must be written in lower case


letters. main is not the same as MAIN.
 All C statements must end with a semicolon.
 Whitespace is used in C to add blank space and tabs.
 You do not have to worry about the indentation of the code.
 When we write a function, its body is enclosed in curly braces, like for the main() function. We
will learn this in detail when we cover functions.

The picture below shows you the structure of the C program.

Frequently Asked Questions (FAQ)

Here are some frequently asked questions related to the C language syntax.

Q1. What do you understand by tokens in C language?

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.

Q3. What is a Compilation Error?

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.

Q4. How to add comments in C?

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.

Q5. Can a program run without the main() function in C?

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.

C KEYWORDS AND IDENTIFIERS


Keywords and Identifiers in the C language are the building block of any program. Keywords are
predefined, which means the C language has a list of words that are Keywords, while an Identifier is
user-defined, which means you while writing the C language program can specify identifiers. Let's
see what these two are.

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.

What are Identifiers?

Identifiers are words or texts used to identify anything in the C language.

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.

There are a total of 32 keywords in the C language.

List of Keywords in C:

The following is a table of keywords available in the C language.

auto double int struct


break else long switch
case enum register typedef
const extern return union
char float short unsigned
continue for signed volatile
default goto sizeof void
do if static while

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.

The keywords added by C99 are:

_Bool _Imaginary restrict


_Complex inline

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.

Important Points to Note:

Here are some useful points to remember about Keywords.

 A keyword can not be used as an Identifier (remember this always).


 Keywords must be written in lower case. Apart from some C99 based keywords, all other
keywords are in lowercase.
 Keywords hold special meaning for the C compiler, so respect that, otherwise you will get a
compile-time error.

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

In the C language identifiers are the names given to variables,


constants, functions, structures, pointers, or any other user-defined data, to identify them.

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.

Rules for defining an Identifier:

 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.

Using Identifiers and Keywords:

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:

int myvariable = "Studytonight";

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.

Let's have another example,

int money;

28 | P a g e
double salary;

Example of Valid Identifiers:

Here are some valid identifiers,

total, avg1, difference_1;

Example of Invalid Identifiers:

Here are some invalid identifiers,

$myvar; // incorrect

x!y; // again incorrect

Using Keywords as Identifiers

What happens when we use keywords as identifiers?

#include <stdio.h>

int main() {

// using void as name of variable (identifier)

int void = 0;

return 0;

error: two or more data types in declaration specifiers

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).

Frequently Asked Questions

Here are some frequently asked questions related to keywords and identifiers.

Q1. What is the difference between Identifier and Variable?

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.

DATA TYPES IN C LANGUAGE


As the name suggests, a Datatype defines the type of data being used. Whenever we define a
variable or use any data in the C language program, we have to specify the type of the data, so that
the compiler knows what type of data to expect.

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

Primary Data types in C

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;

int d = -0.5; //invalid

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,

10. float a = 0.05;

11. float b = -0.005.

12. float c = 1; // it will become c = 1.000000 because of type-casting

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.

14. double a = 10.09;

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.

16. void function() {

17. //your code goes here

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.

int can be 2 bytes/4 bytes

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.

C Data type 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.

Following are the modifiers:

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.

C Data type Value Range

In the table below we have the range for different data types in the C language.

TYPE TYPICAL SIZE IN BITS MINIMAL RANGE FORMAT SPECIFIER


char 8 -127 to 127 %c
unsigned char 8 0 to 255 %c
signed char 8 -127 to 127 %c
int 16 or 32 -32,767 to 32,767 %d, %i
unsigned int 16 or 32 0 to 65,535 %u
signed int 16 or 32 Same as int %d, %i
35 | P a g e
short int 16 -32,767 to 32,767 %hd
unsigned short int 16 0 to 65,535 %hu
signed short int 16 Same as short int %hd
long int 32 -2,147,483,647 to 2,147,483,647 %ld, %li
long long int 64 -(263 - 1) to 263 - 1 (Added by C99 standard) %lld, %lli

signed long int 32 Same as long int %ld, %li


unsigned long int 32 0 to 4,294,967,295 %lu
unsigned long long int 64 264 - 1 (Added by C99 standard) %llu
float 32 1E-37 to 1E+37 with six digits of precision %f

double 64 1E-37 to 1E+37 with ten digits of precision %lf

long double 80 1E-37 to 1E+37 with ten digits of precision %Lf

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.

What happens if the value is out of Range?

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() {

// allowed value up to 65535

unsigned short int x = 65536;

return 0;

36 | P a g e
warning: large integer implicitly truncated to unsigned type [-Woverflow]

unsigned short int x = 65536;

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.

What does signed and unsigned means?

This is a little tricky to explain, but let's try.

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.

Derived Data types in C

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

Let's learn about each one of them one by one.

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,

char status = 'Y';

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.

// simple int value

int a = 100;

// negative value

38 | P a g e
a = -100;

// unsigned int value - with suffix U or u

int x = 1000U;

// long int value

long int long_val = 3500L;

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.

Let's see some examples for float value,

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 .

C VARIABLES (WITH EXAMPLES)


In this tutorial, we will be learning what are Variables, how to declare and define a variable in the C
language, and what are constants and literals in the C language.

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.

Syntax for using Variable:

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).

int marks = 10;

You can change the value of the variable, whenever you want. But make sure the value is of
correct data type.

// variable defined

int marks = 10;

// assign a new value

marks = 33;

Datatype of the Variable

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.

Let's take an example,

// char type variable

char status = 'Y';

// int type variable

int marks = 95;

// float type variable

float percentage = 94.6;

// double type variable

double long = 76.997429;

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() {

// assign incorrect value

int x = 10.58;

printf("Value is %d", x);

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.

Datatype cannot be changed

Once we define a variable with some datatype then we cannot change the datatype of that variable.

For example,

// int variable

int marks = 10;

float marks; // error

Rules to name a 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:

1. Variable name must not start with a digit.


2. The variable name can consist of alphabets, digits, and special symbols like underscore _.
3. Blank or spaces are not allowed in the variable name.
4. Keywords are not allowed as a variable name.
5. Upper and lower case names are treated as different, as C is case-sensitive, so it is suggested
to keep the variable names in lower case.

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

int var1; // correct

int my$var // incorrect - special characters not allowed

int my_var1; // correct

int my var; // incorrect - spaces not allowed

char else; // can't use Keywords

int count; // valid variable name

int Count; // new variable

int COUNT; // new variable

Creating a Variable - Behind the Scenes

Declaration of variables must be done before they are used in the program. The declaration does the
following things.

1. It tells the compiler what the variable name is.


2. It specifies what type of data the variable will hold.
3. Until the variable is defined the compiler doesn't have to worry about allocating memory space
to the variable.
4. The declaration is more like informing the compiler that there exists a variable with the
following datatype which is used in the program.
5. We can even declare a variable outside the main() function, using the extern keyword.

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;

Initializing a variable means providing it with a value.

int a = 10;

Difference between Variable and Identifier?

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.

In the language, literals can be of 5 types, they are:

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.

Integer literals are of 3 types:

1. Decimal Numer (base 10)


2. Octal Number (base 8) - Uses digits 0 up to 7. Number 10 is the same as 8 for the octal
system.
3. Hexadecimal Number (base 16) - Uses digits 0 up to 9, and alphabets A to F. (A, B, C, D, E, F
stands for 10, 11, 12, 13, 14, and 15)

For example,

Decimal: 7, -10 etc


47 | P a g e
Octal: 023, 045 etc

Hexadecimal: 0x2a, 0x521 etc

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,

3500L, 14l // long value

99U, 89u // unsigned int value

2. Floating-point Literals

Any valid floating-point value when used directly in a C program, is called a floating-point literal.

The floating-point numbers have a decimal part (fraction) or an exponential part.

For example,

100.50

0.000127

-0.77E-5

E-5 stands for 10-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,

127.7F, 40f etc.

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.

The character values are enclosed within a single quote.

For example,

'A', 'B', 'c', '#', etc.

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.

A string literal is a value with multiple characters enclosed within double-quotes.

For example,

"study", "tonight", "c programming", etc.

5. Backslash Character Literals

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.

'\'' \\ this is character with value '

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.

C CONSTANT VALUE VARIABLES - const KEYWORD


If you want to create a variable whose value cannot be changed, then you can use
the const keyword to create a constant value variable.

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.

Using const Keyword

Here is a simple example for using the const keyword,

const int totalmarks = 100;

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.

Change const Variable value

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() {

// initialize a constant variable

const int total_marks = 10;

// try changing value

total_marks = 80;

return 0;

error: assignment of read-only variable 'total_marks'

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.

C INPUT AND OUTPUT - printf()/scanf(), and more.


Input means to provide the program with some data to be used in it and Output means to display
data on the screen or write the data to a printer or a file.

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 (stdin)

 Standard Output (stdout)

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:

1. printf() function - Show Output


2. scanf() function - Take Input
3. getchar() and putchar() function

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.

1. The printf() function

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).

Following is how the printf() function is defined in the C stdio.h library.

int printf(const char *format, ...);

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.

printf() Code Examples

Let's start with a simple example.

1. Print a sentence

Let's print a simple sentence using the printf() function.

#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.

2. Print an Integer value

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()

printf("Value of x is: %d", x);

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.

3. Print a Character value

The %c format specifier is used to print character variable value using the printf() function.

#include <stdio.h>

int main() {

// using printf()

char gender = 'M';

printf("John's Gender is: %c", gender);

return 0;

John's Gender is: M

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 \'

4. Print a Float and a Double value

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()

float num1 = 15.50;

double num2 = 15556522.0978678;

printf("Value of num1 is: %f \n", num1);

printf("Value of num2 is: %lf", num2);

return 0;

Value of num1 is: 15.500000

Value of num2 is: 15556522.097868

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.

5. Print multiple outputs

We can use a single printf() function to display values of multiple variables.

#include <stdio.h>

int main() {

// using printf() for multiple outputs

int day = 20;

int month = 11;


56 | P a g e
int year = 2021;

printf("The date is: %d-%d-%d", day, month, year);

return 0;

The date is: 20-11-2021

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

2. The scanf() function

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.

Following is how the scanf() function is defined in the C stdio.h library.

int scanf(const char *format, ...);

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.

Here is the syntax for scanf():

scanf("%x", &variable);

where, %x is the format specifier.

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.

scanf() Code Examples

Let's start with a simple example.

1. Input Integer value

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);

printf("You entered: %d", user_input);

return 0;

Run Code →

Please enter a number: 7

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.

2. Input Float value

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);

printf("You entered: %f", user_input);

return 0;

Please enter a decimal number: 7.007

You entered: 7.007

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.

3. Input Character value

Let's see how we can take a simple character input from user.

#include <stdio.h>

int main() {

// using scanf()

char gender;

printf("Please enter your gender (M, F or O): ");

scanf("%c", &gender);

printf("Your gender: %c", gender);

return 0;
60 | P a g e
}

Please enter your gender (M, F or O): M

Your gender: M

4. Take Multiple Inputs from User

In the below code example, we are taking multiple inputs from the user and saving them into
different variables.

#include <stdio.h>

int main() {

// using scanf() for multiple inputs

char gender;

int age;

printf("Enter your age and then gender(M, F or O): ");

scanf("%d %c", &age, &gender);

printf("You entered: %d and %c", age, gender);

return 0;

Enter your age and then gender(M, F or O): 32 M

You entered: 32 and M

Return Value of printf() & scanf()

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");

printf("Value of i is: %d", i);

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.

Here is a list of all the format specifiers.

DATATYPE FORMAT SPECIFIER


int %d, %i
char %c
float %f
double %lf
short int %hd
unsigned int %u
long int %li
long long int %lli
unsigned long int %lu
unsigned long long int %llu
signed char %c
unsigned char %c
long double %Lf

3. getchar() & putchar() functions

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.

Here is the syntax for the getchar() function:

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.

Here is the syntax for the putchar() function:

int putchar(int character);

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");

/*

Take a character as input and

store it in variable c

*/

c = getchar();

/*

display the character stored


63 | P a g e
in variable c

*/

putchar(c);

Enter a character: Studytonight

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.

4. gets() & puts() functions

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.

Here is the syntax for the gets() function:

char* gets(char* str);

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.

Here is the syntax for the gets() function:

int puts(const char* str);

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];

printf("Enter a string: ");

gets(str);

puts(str);

getch();

return 0;

Enter a string: Studytonight

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.

The fgets() function

Here is the syntax for the fgets() function:

char* fgets(char* str, int num, FILE* stream);

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];

fgets(str, MAX, stdin);

printf("The string is: %s", str);

return 0;

abcdefghijkl

The string is: abcdefghij

Difference between scanf() and gets()

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.

Let's see the scanf() function in action:

#include <stdio.h>

int main() {

// using scanf()

char n1[50], n2[50];

printf("Please enter n1: ");

66 | P a g e
scanf("%s", n1);

printf("You entered: %s", n1);

return 0;

Please enter n1: study tonight

You entered: study

Now let's see the gets() function in action:

#include <stdio.h>

int main() {

// using scanf()

char n1[50], n2[50];

printf("Please enter n1: ");

gets(n1);

printf("You entered: %s", n1);

return 0;

Please enter n1: study tonight

You entered: study tonight

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.

C OPERATORS (WITH LIVE EXAMPLES)


The C language supports a rich set of built-in operators. An operator is a symbol that tells the
compiler to perform a certain mathematical or logical operations, based on the values provided to the
operator.

Operators are used in programs to manipulate data and variables.

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

C operators can be classified into the following types:

 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 C language supports all the basic arithmetic operators such


as addition, subtraction, multiplication, division, etc.

The following table shows all the basic arithmetic operators along with their descriptions.

Examples (where a and b are variables with some integer value)

OPERATOR DESCRIPTION EXAMPLE


+ adds two operands (values) a+b
- subtract second operands from first a-b
* multiply two operands a*b
/ divide numerator by the denominator, i.e. divide the operand on the left side with a/b
the operand on the right side
% This is the modulus operator, it returns the remainder of the division of two a%b
operands as the result
++ This is the Increment operator - increases integer value by one. This operator needs a++ or ++a
only a single operand.
-- This is the Decrement operator - decreases integer value by one. This operator --b or b--
needs only a single operand.

To learn in what order the arithemtic operators are executed, visit C Operator Precedence.

Example: Basic Arithmetic Operators

Let's see a code example to understand the use of the basic arithmetic operators in C programs.

#include <stdio.h>

int main() {

int a = 50, b = 23, result;

69 | P a g e
// addition

result = a+b;

printf("Addition of a & b = %d \n",result);

// subtraction

result = a-b;

printf("Subtraction of a & b = %d \n",result);

// multiplication

result = a*b;

printf("Multiplication of a & b = %d \n",result);

// division

result = a/b;

printf("Division of a & b = %d \n",result);

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 →

Example: Using Modulus Operator (%)

The modulus operator returns the remainder value after the division of the provided values.

#include <stdio.h>

int main() {

int a = 23, b = 20, result;

// Using Modulus operator

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() {

int a = 10, b = 20, c, d;

/*

Using increment operator

*/

printf("Incrementing value of a = %d \n", ++a);

/*

Using decrement operator

*/

printf("Decrementing value of b = %d \n", --b);

// first print value of a, then decrement a

printf("Decrementing value of a = %d \n", a--);

printf("Value of a = %d \n", a);

72 | P a g e
// first print value of b, then increment b

printf("Incrementing value of b = %d \n", b++);

printf("Value of b = %d \n", 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.

It returns 1 if the relationship checks pass, otherwise, it returns 0.

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.

Example: (a and b, where a = 10 and b = 11)

OPERATOR DESCRIPTION EXAMPLE

== Check if two operands are equal a == b, returns 0


!= Check if two operands are not equal. a != b, returns 1 because a is not equal to
b
> Check if the operand on the left is greater than the operand a > b, returns 0
on the right
< Check operand on the left is smaller than the right operand a < b, returns 1

>= 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.

Example: Relational Operators

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() {

int a = 10, b = 20, result;

74 | P a g e
// Equal

result = (a==b);

printf("(a == b) = %d \n",result);

// less than

result = (a<b);

printf("(a < b) = %d \n",result);

// greater than

result = (a>b);

printf("(a > b) = %d \n",result);

// less than equal to

result = (a<=b);

printf("(a <= b) = %d \n",result);

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

C language supports the following 3 logical operators.

Example:(a and b, where a = 1 and b = 0)

OPERATOR DESCRIPTION EXAMPLE


&& Logical AND a && b, returns 0
|| Logical OR a || b, returns 1
! Logical NOT !a, returns 0

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.

Example: Logical Operators

In the code example below, we have used the logical operators.

#include <stdio.h>

int main() {

int a = 1, b = 0, result;
76 | P a g e
// And

result = (a && b);

printf("a && b = %d \n",result);

// 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.

Operator Description Example


& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR (XOR)
~ One's complement (NOT)
>> Shift right
<< Shift left

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.

a b a&b a|b a^b


0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

Bitwise operators can produce any arbitrary value as result. It is not mandatory that the result will
either be 0 or 1.

Bitwise >> and << operators

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.

Bitwise One's Complement (~) Operator

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.

Example: Bitwise Left & Right shift Operators

Let's see an example to understand the bitwise operators in C programs.

#include <stdio.h>

int main() {

int a = 0001000, b = 2, result;

// <<

result = a<<b;

printf("a << b = %d \n",result);

// >>

79 | P a g e
result = a>>b;

printf("a >> b = %d \n",result);

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.

Operator Description Example(a and b are two variables,


with where a=10 and b=5)
= assigns values from right side a=b, a gets value 5
operand to left side operand
+= adds right operand to the left a+=b, is same as a=a+b, value of a
operand and assign the result to left becomes 15
operand
-= subtracts right operand from the left a-=b, is same as a=a-b, value of a
operand and assign the result to left becomes 5
operand
*= mutiply left operand with the right a*=b, is same as a=a*b, value of a
operand and assign the result to left becomes 50
operand

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.

Example: Using Assignment 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 →

C Ternary Operator (?)

The ternary operator, also known as the conditional operators in the C language can be used for
statements of the form if-then-else.

The basic syntax for using ternary operator is:

(Expression1)? Expression2 : Expression3;

Here is how it works:

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.

Example: Using Ternary Operator

Here is a code example to show how to use ternary operator.

#include <stdio.h>

int main() {

int a = 20, b = 20, result;

/* Using ternary operator

- If a == b then store a+b in result

- otherwise store a-b in result

*/

result = (a==b)?(a+b):(a-b);

printf("result = %d",result);

return 0;

83 | P a g e
}

result = 40

Run Code →

C Special Operator - &, *, sizeof, etc.

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.

Operator Description Example


sizeof returns the size(length in bytes) sizeof(x) will return size of the
of entity, for eg. a variable or an variable x
array, etc.
returns the memory address of &x will return address of the
&
the variable variable x
m = &x (memory address of
represents pointer to an object. variable x)
* The * operator returns the value
stored at a memory address. *m will return the value stored
at memory address m
If emp is a structure with an
used to access individual
element int age in it, then
. (dot) operator elements of a C structure or C
emp.age will return the value of
union.
age.
used to access structure or union If p is a pointer to the emp
-> (arrow) operator elements using a pointer to structure, then we can access
structure or union. age element using p->age
if arr is an array, then we can
access its values using
used to access array elements
[] operator arr[index], where index
using indexing
represents the array index
starting from zero

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.

Example: Using 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

printf("Size of a is: %d \n", sizeof(a));

printf("Size of b is: %d \n", sizeof(b));

printf("Size of c is: %d \n", sizeof(c));

// & operator

printf("Memory address of a: %d \n", &a);

return 0;

85 | P a g e
}

Size of a is: 4

Size of b is: 1

Size of c is: 8

Memory address of a: 1684270284

Run Code →

Frequently Asked Questions

Here are some frequently asked questions for C operators.

Q1. What are operators in C?

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.

Q2. What are the different types of operators C supports?

The C language supports the following type of operators:

 Arithmetic operators
 Relational operators
 Logical operators
 Bitwise operators
 Assignment operators
 Ternary operator
 Special operators like sizeof, &, *, . (dot) operator, -> (arrow) operator, [] (square bracket)
operator, etc.

Q3. What does * operator do in C?

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.

Q4. What does != mean in C?

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.

Q5. What is & and * operators in C?

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.

Q6. What does %d do in C?

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.

PRECEDENCE OPERATOR DESCRIPTION ASSOCIATIVITY


++, -- Suffix/postfix increment and decrement Left-to-right
() Function call
[] Array subscripting
1 . Structure and union member access
Structure and union member access through
->
pointer
(type){list} Compound literal(C99)
++, -- Prefix increment and decrement Right-to-left
+, - Unary plus and minus
!, ~ Logical NOT and bitwise NOT
2 (type) Cast
* Indirection (dereference)
& Address-of
sizeof Size-of
_Alignof Alignment requirement(C11)
3 *, /, % Multiplication, division, and remainder Left-to-right
4 +, - Addition and subtraction
5 <<, >> Bitwise left shift and right shift
6 <, <= For relational operators < and ? respectively

88 | P a g e
>, >= For relational operators > and ? respectively

7 ==, != For relational = and ? respectively


8 & Bitwise AND
9 ^ Bitwise XOR (exclusive or)
10 | Bitwise OR (inclusive or)
11 && Logical AND
12 || Logical OR
13 ?: Ternary conditional Right-to-left
= Simple assignment
+=, -= Assignment by sum and difference

*=, /=, %= Assignment by product, quotient, and remainder


14
<<=, >>= Assignment by bitwise left shift and right shift

&=, ^=, |= Assignment by bitwise AND, XOR, and OR


15 , Comma Left-to-right

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.

Precedence and associativity are independent from order of evaluation.

In C language, there is no left-to-right or right-to-left evaluation. Associativity is only for operators.

The expression sum() + difference() + remainder() is parsed as (sum() + difference()) +


remainder() because of left-to-right associativity of + operator but any of the three functions can be
evaluated first by the compiler.

Some basic rules around Operator Precedence

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.

For example, if we have the following expression,


89 | P a g e
10 > 1 + 9;

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.

Order of Precedence in Arithmetic Operators

There are many arithmetic operators in the C language, and the order of precedence is applicable for
them too.

1. ++ and -- (increment and decrement) operators hold the highest precedence.


2. Then comes - (unary minus) operator
3. Then comes *, / and % holding equal precedence.
4. And at last, we have the + and - operators used for addition and subtraction, with the lowest
precedence.

Operators on the same level of precedence are evaluated by the compiler from left to
right (associativity, remember).

We can use parentheses to change the order of the evaluation.

Let's see an example,

#include <stdio.h>

int main() {

// arithmetic operator precedence

int a = 10, b = 20, c = 30, result;

result = a * b + ++c;

printf("The result is: %d", result);

90 | P a g e
return 0;

The result is: 231

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.

Order of precedence in Relational/Logical Operators

In the case of the relational and logical operators, this order is followed:

1. The ! (logical NOT) operator holds the highest precedence.


2. Then comes > (greater than), >= (greater than or equal to), < (less than), and <= (less than or
equal to) with the same precedence.
3. Then we have the == and != operators.
4. After that comes the && (logical AND) operator
5. At last, we have the || (logical OR) operator with the lowest precedence.

For example, the expression !0 && 0 || 0, will give false as result.

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

 conditional operator statement (? : operator)

 goto statement

Decision making with if 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

3. Nested if....else statement

4. Using else if statement

Simple if statement

The general form of a simple if statement is,

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 )

printf("x is greater than y");

x is greater than y

if...else statement

The general form of a simple if...else statement is,

93 | P a g e
if(expression)

statement block1;

else

statement block2;

If the expression is true, the statement-block1 is executed, else statement-block1 is skipped


and statement-block2 is executed.

Example:

#include <stdio.h>

void main( )

int x, y;

x = 15;

y = 18;

if (x > y )

printf("x is greater than y");

94 | P a g e
else

printf("y is greater than x");

y is greater than x

Nested if....else statement

The general form of a nested if...else statement is,

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...");

scanf("%d%d%d",&a, &b, &c);

if(a > b)

if(a > c)

printf("a is the greatest");

else

{
96 | P a g e
printf("c is the greatest");

else

if(b > c)

printf("b is the greatest");

else

printf("c is the greatest");

else if ladder

The general form of else-if ladder is,

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)

printf("Divisible by both 5 and 8");

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.

5. Other than 0(zero), all other values are considered as true.

6. if(27)

printf("hello");

In above example, hello will be printed.

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;

Rules for using switch statement

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.

2. The case label values must be unique.

3. The case label must end with a colon(:)

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.

Example of switch statement

#include<stdio.h>

102 | P a g e
void main( )

int a, b, c, choice;

while(choice != 3)

/* Printing the available options */

printf("\n 1. Press 1 for addition");

printf("\n 2. Press 2 for subtraction");

printf("\n Enter your choice");

/* Taking users input */

scanf("%d", &choice);

switch(choice)

case 1:

printf("Enter 2 numbers");

scanf("%d%d", &a, &b);

c = a + b;

printf("%d", c);

break;

case 2:

103 | P a g e
printf("Enter 2 numbers");

scanf("%d%d", &a, &b);

c = a - b;

printf("%d", c);

break;

default:

printf("you have passed a wrong key");

printf("\n press any key to continue");

Difference between switch and if

 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?

The below diagram depicts a loop execution,

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.

Loops are broadly classified into two types:

1. Entry controlled loops

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.

2. Exit controlled loops

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

There are 3 types of Loop in C language, namely:

1. while loop

2. for loop

3. do while loop

105 | P a g e
1. while loop in C

The while loop is an entry controlled loop. It is completed in 3 steps.

 Variable initialization.(e.g int x = 0;)

 condition(e.g while(x <= 10))

 Variable increment or decrement ( x++ or x-- or x = x + 2 )

Syntax of while Loop:

variable initialization;

while(condition)

statements;

variable increment or decrement;

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.

Program to print your name n times using while loop

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;

printf("Enter the number of times you want to print your name:");

scanf("%d", &n);

char name[30];

printf("Enter your name:");

scanf("%s", name);

while(n) {

//here we are checking if n is non-zero

printf("%s\n", name);

n--; //decrementing n

return 0;

Enter the number of times you want to print your name:3

Enter your name:studytonight

studytonight

studytonight

studytonight

Run Code →

Let's dry run of the above code:

Firstly, we input n = 3, then name = studytonight?.

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.

Let's see another example.

Program to print first 10 natural numbers using while loop

#include<stdio.h>

void main( )

int x;

x = 1;

while(x <= 10)

printf("%d\t", x);

/* below statement means, do x = x+1, increment x by 1 */

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,

for(initialization; condition; increment/decrement)

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.

The for loop is executed as follows:

1. It first evaluates the initialization code.

2. Then it checks the condition expression.

3. If it is true, it executes the for-loop body.

4. Then it evaluate the increment/decrement condition and again follows from step 2.

5. When the condition expression becomes false, it exits the loop.

Following is a flowchart explaining how the for loop executes.

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.

Program to print your name n times using for loop

#include <stdio.h>

int main()

109 | P a g e
{

int n;

printf("Enter the number of times you want to print your name:");

scanf("%d", &n);

char name[25];

printf("Enter your name:");

scanf("%s", name);

for(int i = 1; i <= n; i++) { //here we are checking if n is non-


zero

printf("%s\n", name);

return 0;

Enter the number of times you want to print your name:4

Enter your name:studytonight

studytonight

studytonight

Run Code →

Let's dry run of the above code:

Firstly, we input n = 3, then name = studytonight.

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.

Program to print first 10 natural numbers using for loop

#include<stdio.h>

void main( )

int x;

for(x = 1; x <= 10; x++)

printf("%d\t", x);

1 2 3 4 5 6 7 8 9 10

3. Nested for loop in C

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,

for(initialization; condition; increment/decrement)

{
111 | P a g e
for(initialization; condition; increment/decrement)

statement ;

Program to print half Pyramid of numbers using Nested loops

#include<stdio.h>

void main( )

int i, j;

/* first for loop */

for(i = 1; i < 5; i++)

printf("\n");

/* second for loop inside the first */

for(j = i; j > 0; j--)

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.

Following is the flowchart for do-while 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.

Program to print your name N times using do-while loop

#include <stdio.h>

int main()

int n;

printf("Enter the number of times you want to print your name:");

scanf("%d", &n);

char name[25];

printf("\nEnter your name:");

scanf("%s", name);

do{

printf("%s\n", name);

n--;

}while(n < 0);

return 0;

Enter the number of times you want to print your name: 10

Enter your name: studytonight

studytonight

114 | P a g e
Run Code →

Dry run of the above code:

Firstly, we input n = 10, then name = studytonight.

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.

Program to print first 10 multiples of 5 using do-while loop

#include<stdio.h>

void main()

int a, i;

a = 5;

i = 1;

do

printf("%d\t", a*i);

i++;

while(i <= 10);

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.

Let's see a few examples of infinite loops in C:

#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.

Jumping Out of Loops in C

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.

Let's see a code example,

#include <stdio.h>

117 | P a g e
int main()

int n;

printf("Enter the number of times you want to print your name:");

scanf("%d", &n);

char name[25];

printf("\nEnter your name:");

scanf("%s", name);

for(int i = 1; i <= n; i++) {

if(i % 5 == 0)

break;

printf("%s\n", name);

return 0;

Enter the number of times you want to print your name:7

Enter your name:studytonight

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.

Let's see a code example,

#include <stdio.h>

int main()

int n;

printf("Enter the number of times you want to print your name:");

scanf("%d", &n);

char name[25];

printf("\nEnter your name:");

scanf("%s", name);

for(int i = 1; i <= n; i++) {

if(i % 2 == 0)

continue;

printf("%d : %s\n",i,name);

return 0;

119 | P a g e
}

Enter the number of times you want to print your name:5

Enter your name:studytonight

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.

Here the words,

 finite means data range must be defined.

 ordered means data must be stored in continuous memory addresses.

 homogenous means data must be of similar data type.

Some uses of Arrays in C

Following are some usecases where using an array will make things simpler:

 to store list of Employee or Student names,

 to store marks of students,

 or to store list of numbers or characters etc.

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];

Let's see some code example real quick,

121 | P a g e
/* Example of array declaration */

char a[5]; /* char type value array */

float ar[9]; /* float type value array */

int arr[10]; /* int type value array */

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 Array initialization in C

Compile time initialization of array means we provide the value for the array in the code, when we
create the array,

data-type array-name[size] = { list of values };

Let's see a few simple examples,

/* 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;

int arr[] = {2, 3, 4}; // Compile time array initialization

for(i = 0 ; i < 3 ; i++)

printf("%d\t",arr[i]);

2 3 4

Runtime Array initialization in C

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.

For example, to insert element at specific index,

scanf("%d", &arr[3]); // will insert element at index 3, i.e. 4th position

Let's suppose we have an array Arr of 10 elements of type int.

To insert elements at each index,

for(int i = 0; i < 10; i++)

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.

To insert elements at each index according to user, we can do the following,

for(int i = 0; i < 10; i++)

scanf("%d", &Arr[i]);

To insert elements at alternate index,

for(int i = 0; i < 10; i+=2)

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.

Accessing Array elements in C

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.

To print all elements,

for(int i = 0; i < 10; i++)

printf("%d", Arr[i]);

To access and print elements at specified index,

printf("%d", Arr[0]); //prints first element of the array

printf("%d", Arr[5]); //prints sixth element of the array

To access elements at alternate index,

for(int i = 0; i < 10; i+=2)

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

Let's see a few basic programs where we will be using arrays.

1. Calculate sum of all array elements


The following program is used to calculate the sum of all elements of an array.

#include<stdio.h>

void main(){

int arr[5];

printf("Enter array elements:"");

for(int i = 0; i < 5; i++)

scanf("%d", &arr[i]);

printf("Array elements are:"");

for(int i = 0; i < 5; i++)

printf("%d ", arr[i]);

int sum = 0;

for(int i = 0; i < 5; i++)

sum += arr[i];

printf("Sum =%d", sum);

125 | P a g e
Enter array elements:3 2 4 1 5

Array elements are:3 2 4 1 5

Sum =15

2. Copy data from one array to another


This program will copy all the elements of one array into another, we use a for loop.

#include <stdio.h>

int main()

float arr1[5] = {1.5, 2.1, 3.7, 4.2, 5.5}, arr2[5];

for(int i = 0; i < 5; i++)

arr2[i] = arr1[i];

for(int i = 0; i < 5; i++)

printf("%d ", arr2[i]);

return 0;

1.5 2.1 3.7 4.2 5.5

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.

Array1 = Array2; // error

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()

bool submitted[5] = {'0', '1', '1', '0', '1'};

printf("Submission details are:\n");

for(int i = 0; i < 5; i++)

printf("%d : %d\n",i + 1, submitted[i]);

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.

Two-dimensional arrays are declared as follows,

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];

Compile-time initialization of a two dimensional Array

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.

Let's see a few more examples,

int arr1[2][2] = {1, 2, 3, 4}; // equivalent to {{1, 2},{3, 4}}

int arr2[2][3] = {1, 2, 3, 4}; // equivalent to {{1, 2, 3},{4}}

int arr3[2][4] = {1, 2, 3, 4}; // equivalent to {{1,2,3,4}}

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.

Runtime initialization of a two dimensional Array

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;

printf("Enter array elements:\n");

for(i = 0; i < 3;i++)

for(j = 0; j < 4; j++)

scanf("%d", &arr[i][j]);

}
129 | P a g e
}

for(i = 0; i < 3; i++)

for(j = 0; j < 4; j++)

printf("%d", arr[i][j]);

Enter array elements:

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.

So, we have arr[0][0], then we increment j by 1 to access arr[0][1], then arr[0][2].

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.

To print the elements of different rows in different lines,


130 | P a g e
for(int i = 0; i < 3; i++)

for(int j = 0; j < 4; j++)

printf("%d", arr[i][j]);

printf(“\n”);

Using 2D Array in Program in C

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()

float marks[2][3], total[2];

for(int i = 0; i < 2; i++) {

for(int j = 0; j < 3; j++){

scanf("%f", &marks[i][j]);

131 | P a g e
}

for(int i = 0; i < 2; i++) {

float sum = 0;

for(int j = 0; j < 3; j++){

sum += marks[i][j];

total[i] = sum;

for(int i = 0; i < 2; i++)

printf("%d : %f\n", i + 1, total[i]);

return 0;

1.2 2.3 4.5 6.7 7.8

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.

String and Character Array


String is a sequence of characters that are treated as a single data item and terminated by a null
character '\0'. Remember that the C language does not support strings as a data type. A string is
actually a one-dimensional array of characters in C language. These are often used to create
meaningful and readable programs.

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.

Declaring and Initializing a string variables:

// valid

char name[13] = "StudyTonight";

char name[10] = {'c','o','d','e','\0'};

133 | P a g e
// Illegal

char ch[3] = "hello";

char str[4];

str = "hello";

String Input and Output:

 %s format specifier to read a string input from the terminal.


 But scanf() function, terminates its input on the first white space it encounters.
 edit set conversion code %[..] that can be used to read a line containing a variety of
characters, including white spaces.
 The gets() function can also be used to read character string with white spaces

char str[20];

printf("Enter a string");

scanf("%[^\n]", &str);

printf("%s", str);

char text[20];

gets(text);

printf("%s", text);

String Handling Functions:

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.

strlen() and strcmp() function:

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");

int i=strcmp("study ", "tonight");

printf("%d %d",j,i);

12 -1

strcpy() function:

It copies the second string argument to the first string argument.

Example of 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:

It is used to reverse the given string expression.

Code snippet for strrev():

#include <stdio.h>

137 | P a g e
int main()

char s1[50];

printf("Enter your string: ");

gets(s1);

printf("\nYour reverse string is: %s",strrev(s1));

return(0);

Enter your string: studytonight

Your reverse string is: thginotyduts

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.

The following storage classes are most oftenly used in C programming,

1. Automatic variables
138 | P a g e
2. External variables

3. Static variables

4. Register variables

Automatic variables: auto

Scope: Variable defined with auto storage class are local to the function block inside which they are
defined.

Default Initial Value: Any random value i.e garbage value.

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

auto int details; //Both are same

External or Global variable

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.

Default initial value: 0(zero).

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>

int number; // global variable

void main()

number = 10;

printf("I am in main function. My value is %d\n", number);

fun1(); //function calling, discussed in next topic

fun2(); //function calling, discussed in next topic

/* 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()

printf("\nI am in function fun2. My value is %d", number);

I am in function main. My value is 10

I am in function fun1. My value is 20

I am in function fun2. My value is 20

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.

Problem when extern is not used

int main()

{
141 | P a g e
a = 10; //Error: cannot find definition of variable 'a'

printf("%d", a);

Example using extern in same file

int main()

extern int x; //informs the compiler that it is defined somewhere


else

x = 10;

printf("%d", x);

int x; //Global variable x

Static variables

Scope: Local to the block in which the variable is defined

Default initial value: 0(Zero).

Lifetime: Till the whole program doesn't finish its execution.

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.

They are assigned 0 (zero) as default value by the compiler.

#include<stdio.h>
142 | P a g e
void test(); //Function declaration (discussed in next topic)

int main()

test();

test();

test();

void test()

static int a = 0; //a static variable

a = a + 1;

printf("%d\t",a);

1 2 3

Register variable

Scope: Local to the function in which it is declared.

Default initial value: Any random value i.e garbage value


143 | P a g e
Lifetime: Till the end of function/method block, in which the variable is defined.

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.

NOTE: We can never get the address of such variables.

Syntax :

register int number;

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.

Which storage class should be used and when

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

C functions can be classified into two categories,

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.

Benefits of Using Functions

1. It provides modularity to your program's structure.

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.

4. It makes the program more readable and easy to understand.

Function Declaration

General syntax for function declaration is,

returntype functionName(type1 parameter1, type2 parameter2,...);

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.

Time for an Example

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;

printf("Please enter 2 numbers you want to multiply...");

scanf("%d%d", &i, &j);

result = multiply(i, j); // function call

printf("The result of muliplication is: %d", result);

return 0;

int multiply(int a, int b)

return (a*b); // function defintion, this can be done in one


line

Function definition Syntax

147 | P a g e
Just like in the example above, the general syntax of function definition is,

returntype functionName(type1 parameter1, type2 parameter2,...)

// function body goes here

The first line returntype functionName(type1 parameter1, type2 parameter2,...) is known


as function header and the statement(s) within curly braces is called function body.

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.

 local variable declaration(if required).

 function statements to perform the task inside the function.

 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.

Passing Arguments to a function

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.

Returning a value from function

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

C functions can be classified into two categories,

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.

Benefits of Using Functions

1. It provides modularity to your program's structure.

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.

4. It makes the program more readable and easy to understand.

Function Declaration

General syntax for function declaration is,

returntype functionName(type1 parameter1, type2 parameter2,...);

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.

Time for an Example

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;

printf("Please enter 2 numbers you want to multiply...");

scanf("%d%d", &i, &j);

result = multiply(i, j); // function call

printf("The result of muliplication is: %d", result);

return 0;

int multiply(int a, int b)

return (a*b); // function defintion, this can be done in one


line

Function definition Syntax

152 | P a g e
Just like in the example above, the general syntax of function definition is,

returntype functionName(type1 parameter1, type2 parameter2,...)

// function body goes here

The first line returntype functionName(type1 parameter1, type2 parameter2,...) is known


as function header and the statement(s) within curly braces is called function body.

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.

 local variable declaration(if required).

 function statements to perform the task inside the function.

 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.

Passing Arguments to a function

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.

Returning a value from function

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

You might also like