0% found this document useful (0 votes)
25 views

C Programs Notes

C is a procedural, mid-level programming language that is widely used for system applications that interact directly with hardware like drivers and kernels. It was developed in the 1970s by Dennis Ritchie at Bell Labs to be used for the Unix operating system. C provides features like simple syntax, structured programming, pointers, and dynamic memory allocation that make it suitable for systems programming. It serves as the base for many other popular languages today.

Uploaded by

sawnkumar0007
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

C Programs Notes

C is a procedural, mid-level programming language that is widely used for system applications that interact directly with hardware like drivers and kernels. It was developed in the 1970s by Dennis Ritchie at Bell Labs to be used for the Unix operating system. C provides features like simple syntax, structured programming, pointers, and dynamic memory allocation that make it suitable for systems programming. It serves as the base for many other popular languages today.

Uploaded by

sawnkumar0007
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 108

C Programming Language

C language Tutorial with programming approach for beginners and professionals, helps you
to understand the C language tutorial easily. Our C tutorial explains each topic with
programs.

The C Language is developed by Dennis Ritchie for creating system applications that directly
interact with the hardware devices such as drivers, kernels, etc.

C programming is considered as the base for other programming languages, that is why it is
known as mother language.

It can be defined by the following ways:

1. Mother language
2. System programming language
3. Procedure-oriented programming language
4. Structured programming language
5. Mid-level programming language

1) C as a mother language
C language is considered as the mother language of all the modern programming languages
because most of the compilers, JVMs, Kernels, etc. are written in C language, and most
of the programming languages follow C syntax, for example, C++, Java, C#, etc.

It provides the core concepts like the array, strings, functions, file handling, etc. that are being
used in many languages like C++, Java, C#, etc.

2) C as a system programming language


A system programming language is used to create system software. C language is a system
programming language because it can be used to do low-level programming (for example
driver and kernel). It is generally used to create hardware devices, OS, drivers, kernels, etc.
For example, Linux kernel is written in C.

It can't be used for internet programming like Java, .Net, PHP, etc.

3) C as a procedural language
A procedure is known as a function, method, routine, subroutine, etc. A procedural language
specifies a series of steps for the program to solve the problem.

A procedural language breaks the program into functions, data structures, etc.

C is a procedural language. In C, variables and function prototypes must be declared before


being used.

4) C as a structured programming language


A structured programming language is a subset of the procedural language. Structure means
to break a program into parts or blocks so that it may be easy to understand.

In the C language, we break the program into parts using functions. It makes the program
easier to understand and modify.

5) C as a mid-level programming language


C is considered as a middle-level language because it supports the feature of both low-level
and high-level languages. C language program is converted into assembly code, it supports
pointer arithmetic (low-level), but it is machine independent (a feature of high-level).

A Low-level language is specific to one machine, i.e., machine dependent. It is machine


dependent, fast to run. But it is not easy to understand.

A High-Level language is not specific to one machine, i.e., machine independent. It is easy
to understand.

C Program
In this tutorial, all C programs are given with C compiler so that you can quickly change the
C program code.

File: main.c

1. #include <stdio.h>
2. int main() {
3. printf("Hello C Programming\n");
4. return 0;
5.[1.]
History of C Language

History of C language is interesting to know. Here we are going to discuss a brief history of
the c language.

C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of


AT&T (American Telephone & Telegraph), located in the U.S.A.

Dennis Ritchie is known as the founder of the c language.

It was developed to overcome the problems of previous languages such as B, BCPL, etc.

Initially, C language was developed to be used in UNIX operating system. It inherits many
features of previous languages such as B and BCPL.

Let's see the programming languages that were developed before C language.

Language Year Developed By

Algol 1960 International Group

BCPL 1967 Martin Richard

B 1970 Ken Thompson

Traditional C 1972 Dennis Ritchie

K&RC 1978 Kernighan & Dennis Ritchie

ANSI C 1989 ANSI Committee

ANSI/ISO C 1990 ISO Committee

C99 1999 Standardization Committee


Features of C Language

C is the widely used language. It provides many features that are given below.

1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible

1) Simple
C is a simple language in the sense that it provides a structured approach (to break the
problem into parts), the rich set of library functions, data types, etc.

2) Machine Independent or Portable


Unlike assembly language, c programs can be executed on different machines with some
machine specific changes. Therefore, C is a machine independent language.

3) Mid-level programming language


Although, C is intended to do low-level programming. It is used to develop system
applications such as kernel, driver, etc. It also supports the features of a high-level
language. That is why it is known as mid-level language.

4) Structured programming language


C is a structured programming language in the sense that we can break the program into
parts using functions. So, it is easy to understand and modify. Functions also provide code
reusability.
5) Rich Library
C provides a lot of inbuilt functions that make the development fast.

6) Memory Management
It supports the feature of dynamic memory allocation. In C language, we can free the
allocated memory at any time by calling the free() function.

7) Speed
The compilation and execution time of C language is fast since there are lesser inbuilt
functions and hence the lesser overhead.

8) Pointer
C provides the feature of pointers. We can directly interact with the memory by using the
pointers. We can use pointers for memory, structures, functions, array, etc.

9) Recursion
In C, we can call the function within the function. It provides code reusability for every
function. Recursion enables us to use the approach of backtracking.

10) Extensible
C language is extensible because it can easily adopt new features.
How to install C
There are many compilers available for c and c++. You need to download any one. Here, we
are going to use Turbo C++. It will work for both C and C++. To install the Turbo C
software, you need to follow following steps.

1. Download Turbo C++


2. Create turboc directory inside c drive and extract the tc3.zip inside c:\turboc
3. Double click on install.exe file
4. Click on the tc application file located inside c:\TC\BIN to write the c program

1) Download Turbo C++ software


You can download turbo c++ from many sites.

2) Create turboc directory in c drive and extract the


tc3.zip
Now, you need to create a new directory turboc inside the c: drive. Now extract the tc3.zip
file in c:\truboc directory.

3) Double click on the install.exe file and follow steps


Now, click on the install icon located inside the c:\turboc
It will ask you to install c or not, press enter to install.

Change your drive to c, press c.


Press enter, it will look inside the c:\turboc directory for the required files.

Select Start installation by the down arrow key then press enter.
Now C is installed, press enter to read documentation or close the software.

4) Click on the tc application located inside c:\TC\BIN


Now double click on the tc icon located in c:\TC\BIN directory to write the c program.
In windows 7 or window 8, it will show a dialog block to ignore and close the application
because fullscreen mode is not supported. Click on Ignore button.

Now it will showing following console.


First C Program
Before starting the abcd of C language, you need to learn how to write, compile and run the
first c program.

To write the first c program, open the C console and write the following code:

1. #include <stdio.h>
2. int main(){
3. printf("Hello C Language");
4. return 0;
5. }

#include <stdio.h> includes the standard input output library functions. The printf()
function is defined in stdio.h .

int main() The main() function is the entry point of every program in c language.

printf() The printf() function is used to print data on the console.

return 0 The return 0 statement, returns execution status to the OS. The 0 value is used for
successful execution and 1 for unsuccessful execution.

How to compile and run the c program


There are 2 ways to compile and run the c program, by menu and by shortcut.

By menu

Now click on the compile menu then compile sub menu to compile the c program.

Then click on the run menu then run sub menu to run the c program.

By shortcut

Or, press ctrl+f9 keys compile and run the program directly.

You will see the following output on user screen.


You can view the user screen any time by pressing the alt+f5 keys.

Now press Esc to return to the turbo c++ console.

Compilation process in c
What is a compilation?
The compilation is a process of converting the source code into object code. It is done with
the help of the compiler. The compiler checks the source code for the syntactical or structural
errors, and if the source code is error-free, then it generates the object code.

The c compilation process converts the source code taken as input into the object code or
machine code. The compilation process can be divided into four steps, i.e., Pre-processing,
Compiling, Assembling, and Linking.

The preprocessor takes the source code as an input, and it removes all the comments from the
source code. The preprocessor takes the preprocessor directive and interprets it. For example,
if <stdio.h>, the directive is available in the program, then the preprocessor interprets the
directive and replace this directive with the content of the 'stdio.h' file.

The following are the phases through which our program passes before being transformed
into an executable form:

 Preprocessor
 Compiler
 Assembler
 Linker

Preprocessor

The source code is the code which is written in a text editor and the source code file is given
an extension ".c". This source code is first passed to the preprocessor, and then the
preprocessor expands this code. After expanding the code, the expanded code is passed to the
compiler.

Compiler

The code which is expanded by the preprocessor is passed to the compiler. The compiler
converts this code into assembly code. Or we can say that the C compiler converts the pre-
processed code into assembly code.
Assembler

The assembly code is converted into object code by using an assembler. The name of the
object file generated by the assembler is the same as the source file. The extension of the
object file in DOS is '.obj,' and in UNIX, the extension is 'o'. If the name of the source file is
'hello.c', then the name of the object file would be 'hello.obj'.

Linker

Mainly, all the programs written in C use library functions. These library functions are pre-
compiled, and the object code of these library files is stored with '.lib' (or '.a') extension. The
main working of the linker is to combine the object code of library files with the object code
of our program. Sometimes the situation arises when our program refers to the functions
defined in other files; then linker plays a very important role in this. It links the object code of
these files to our program. Therefore, we conclude that the job of the linker is to link the
object code of our program with the object code of the library files and other files. The output
of the linker is the executable file. The name of the executable file is the same as the source
file but differs only in their extensions. In DOS, the extension of the executable file is '.exe',
and in UNIX, the executable file can be named as 'a.out'. For example, if we are using printf()
function in a program, then the linker adds its associated code in an output file.

Let's understand through an example.

hello.c

1. #include <stdio.h>
2. int main()
3. {
4. printf("Hello javaTpoint");
5. return 0;
6. }

Now, we will create a flow diagram of the above program:


In the above flow diagram, the following steps are taken to execute a program:

 Firstly, the input file, i.e., hello.c, is passed to the preprocessor, and the preprocessor
converts the source code into expanded source code. The extension of the expanded source
code would be hello.i.
 The expanded source code is passed to the compiler, and the compiler converts this
expanded source code into assembly code. The extension of the assembly code would be
hello.s.
 This assembly code is then sent to the assembler, which converts the assembly code into
object code.
 After the creation of an object code, the linker creates the executable file. The loader will
then load the executable file for the execution.

printf() and scanf() in C


The printf() and scanf() functions are used for input and output in C language. Both functions
are inbuilt library functions, defined in stdio.h (header file).

printf() function

The printf() function is used for output. It prints the given statement to the console.

The syntax of printf() function is given below:

1. printf("format string",argument_list);

The format string can be %d (integer), %c (character), %s (string), %f (float) etc.

scanf() function

The scanf() function is used for input. It reads the input data from the console.

1. scanf("format string",argument_list);

Program to print cube of given number

Let's see a simple example of c language that gets input from the user and prints the cube of
the given number.

1. #include<stdio.h>
2. int main(){
3. int number;
4. printf("enter a number:");
5. scanf("%d",&number);
6. printf("cube of number is:%d ",number*number*number);
7. return 0;
8. }
Output

enter a number:5
cube of number is:125

The scanf("%d",&number) statement reads integer number from the console and stores the
given value in number variable.

The printf("cube of number is:%d ",number*number*number) statement prints the cube


of number on the console.

Program to print sum of 2 numbers

Let's see a simple example of input and output in C language that prints addition of 2
numbers.

1. #include<stdio.h>
2. int main(){
3. int x=0,y=0,result=0;
4.
5. printf("enter first number:");
6. scanf("%d",&x);
7. printf("enter second number:");
8. scanf("%d",&y);
9.
10. result=x+y;
11. printf("sum of 2 numbers:%d ",result);
12.
13. return 0;
14. }

Output

enter first number:9


enter second number:9
sum of 2 numbers:18

Variables in C
A variable is a name of the memory location. It is used to store data. Its value can be
changed, and it can be reused many times.

It is a way to represent memory location through symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

1. type variable_list;

The example of declaring the variable is given below:


1. int a;
2. float b;
3. char c;

Here, a, b, c are variables. The int, float, char are the data types.

We can also provide values while declaring the variables as given below:

1. int a=10,b=20;//declaring 2 variable of integer type


2. float f=20.8;
3. char c='A';

Rules for defining variables


 A variable can have alphabets, digits, and underscore.
 A variable name can start with the alphabet, and underscore only. It can't start with a digit.
 No whitespace is allowed within the variable name.
 A variable name must not be any reserved word or keyword, e.g. int, float, etc.

Valid variable names:

1. int a;
2. int _ab;
3. int a30;

Invalid variable names:

1. int 2;
2. int a b;
3. int long;

Types of Variables in C
There are many types of variables in c:

1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable

Local Variable

A variable that is declared inside the function or block is called a local variable.

It must be declared at the start of the block.

1. void function1(){
2. int x=10;//local variable
3. }

You must have to initialize the local variable before it is used.

Global Variable

A variable that is declared outside the function or block is called a global variable. Any
function can change the value of the global variable. It is available to all the functions.

It must be declared at the start of the block.

1. int value=20;//global variable


2. void function1(){
3. int x=10;//local variable
4. }

Static Variable

A variable that is declared with the static keyword is called static variable.

It retains its value between multiple function calls.

1. void function1(){
2. int x=10;//local variable
3. static int y=10;//static variable
4. x=x+1;
5. y=y+1;
6. printf("%d,%d",x,y);
7. }

If you call this function many times, the local variable will print the same value for each
function call, e.g, 11,11,11 and so on. But the static variable will print the incremented
value in each function call, e.g. 11, 12, 13 and so on.

Automatic Variable

All variables in C that are declared inside the block, are automatic variables by default. We
can explicitly declare an automatic variable using auto keyword.

1. void main(){
2. int x=10;//local variable (also automatic)
3. auto int y=20;//automatic variable
4. }

External Variable

We can share a variable in multiple C source files by using an external variable. To declare
an external variable, you need to use extern keyword.

myfile.h
1. extern int x=10;//external variable (also global)

program1.c

1. #include "myfile.h"
2. #include <stdio.h>
3. void printValue(){
4. printf("Global variable: %d", global_variable);
5. }

Data Types in C
A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.

There are the following data types in C language.

Types Data Types

Basic Data Type int, char, float, double

Derived Data Type array, pointer, structure, union

Enumeration Data Type enum

Void Data Type void

Basic Data Types


The basic data types are integer-based and floating-point based. C language supports both
signed and unsigned literals.

The memory size of the basic data types may change according to 32 or 64-bit operating
system.
Let's see the basic data types. Its size is given according to 32-bit architecture.

Data Types Memory Size Range

char 1 byte −128 to 127

signed char 1 byte −128 to 127

unsigned char 1 byte 0 to 255

short 2 byte −32,768 to 32,767

signed short 2 byte −32,768 to 32,767

unsigned short 2 byte 0 to 65,535

int 2 byte −32,768 to 32,767

signed int 2 byte −32,768 to 32,767

unsigned int 2 byte 0 to 65,535

short int 2 byte −32,768 to 32,767

signed short int 2 byte −32,768 to 32,767

unsigned short int 2 byte 0 to 65,535

long int 4 byte -2,147,483,648 to 2,147,483,647

signed long int 4 byte -2,147,483,648 to 2,147,483,647

unsigned long int 4 byte 0 to 4,294,967,295

float 4 byte

double 8 byte

long double 10 byte

Keywords in C
A keyword is a reserved word. You cannot use it as a variable name, constant name, etc.
There are only 32 reserved words (keywords) in the C language.
A list of 32 keywords in the c language is given below:

auto break case char const continue default do

double else enum extern float for goto if

int long register return short signed sizeof static

struct switch typedef union unsigned void volatile while

We will learn about all the C language keywords later.

C Identifiers
C identifiers represent the name in the C program, for example, variables, functions, arrays,
structures, unions, labels, etc. An identifier can be composed of letters such as uppercase,
lowercase letters, underscore, digits, but the starting letter should be either an alphabet or an
underscore. If the identifier is not used in the external linkage, then it is called as an internal
identifier. If the identifier is used in the external linkage, then it is called as an external
identifier.

We can say that an identifier is a collection of alphanumeric characters that begins either with
an alphabetical character or an underscore, which are used to represent various programming
elements such as variables, functions, arrays, structures, unions, labels, etc. There are 52
alphabetical characters (uppercase and lowercase), underscore character, and ten numerical
digits (0-9) that represent the identifiers. There is a total of 63 alphanumerical characters that
represent the identifiers.

Rules for constructing C identifiers


 The first character of an identifier should be either an alphabet or an underscore, and
then it can be followed by any of the character, digit, or underscore.
 It should not begin with any numerical digit.
 In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say
that identifiers are case sensitive.
 Commas or blank spaces cannot be specified within an identifier.
 Keywords cannot be represented as an identifier.
 The length of the identifiers should not be more than 31 characters.
 Identifiers should be written in such a way that it is meaningful, short, and easy to
read.

Example of valid identifiers

1. total, sum, average, _m _, sum_1, etc.

Example of invalid identifiers

1. 2sum (starts with a numerical digit)


2. int (reserved word)
3. char (reserved word)
4. m+n (special character, i.e., '+')

Types of identifiers
 Internal identifier
 External identifier

Internal Identifier

If the identifier is not used in the external linkage, then it is known as an internal identifier.
The internal identifiers can be local variables.

External Identifier

If the identifier is used in the external linkage, then it is known as an external identifier. The
external identifiers can be function names, global variables.

Differences between Keyword and Identifier


Keyword Identifier
Keyword is a pre-defined word. The identifier is a user-defined word
It can be written in both lowercase and uppercase
It must be written in a lowercase letter.
letters.
Its meaning is pre-defined in the c
Its meaning is not defined in the c compiler.
compiler.
It is a combination of alphabetical
It is a combination of alphanumeric characters.
characters.
It does not contain the underscore
It can contain the underscore character.
character.

Let's understand through an example.

1. int main()
2. {
3. int a=10;
4. int A=20;
5. printf("Value of a is : %d",a);
6. printf("\nValue of A is :%d",A);
7. return 0;
8. }

Output

Value of a is : 10
Value of A is :20
The above output shows that the values of both the variables, 'a' and 'A' are different.
Therefore, we conclude that the identifiers are case sensitive.

C Operators
An operator is simply a symbol that is used to perform operations. There can be many types
of operations like arithmetic, logical, bitwise, etc.

There are following types of operators to perform different types of operations in C language.

 Arithmetic Operators
 Relational Operators
 Shift Operators
 Logical Operators
 Bitwise Operators
 Ternary or Conditional Operators
 Assignment Operator
 Misc Operator

Precedence of Operators in C
The precedence of operator species that which operator will be evaluated first and next. The
associativity specifies the operator direction to be evaluated; it may be left to right or right to
left.

Let's understand the precedence by the example given below:

1. int value=10+20*10;

The value variable will contain 210 because * (multiplicative operator) is evaluated before +
(additive operator).

The precedence and associativity of C operators is given below:

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative * / % Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right


Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

Comments in C
Comments in C language are used to provide information about lines of code. It is widely
used for documenting code. There are 2 types of comments in the C language.

1. Single Line Comments


2. Multi-Line Comments

Single Line Comments


Single line comments are represented by double slash \\. Let's see an example of a single line
comment in C.

1. #include<stdio.h>
2. int main(){
3. //printing information
4. printf("Hello C");
5. return 0;
6. }

Mult Line Comments


Multi-Line comments are represented by slash asterisk \* ... *\. It can occupy many lines of
code, but it can't be nested. Syntax:

1. /*
2. code
3. to be commented
4. */

Let's see an example of a multi-Line comment in C.

1. #include<stdio.h>
2. int main(){
3. /*printing information
4. Multi-Line Comment*/
5. printf("Hello C");
6. return 0;
7. }

C Format Specifier
The Format specifier is a string used in the formatted input and output functions. The format
string determines the format of the input and output. The format string always starts with a
'%' character.

The commonly used format specifiers in printf() function are:

Format
Description
specifier
It is used to print the signed integer value where signed integer means that the
%d or %i
variable can hold both positive and negative values.
It is used to print the unsigned integer value where the unsigned integer means
%u
that the variable can hold only positive value.
It is used to print the octal unsigned integer where octal integer value always
%o
starts with a 0 value.
It is used to print the hexadecimal unsigned integer where the hexadecimal
%x integer value always starts with a 0x value. In this, alphabetical characters are
printed in small letters such as a, b, c, etc.
It is used to print the hexadecimal unsigned integer, but %X prints the
%X
alphabetical characters in uppercase such as A, B, C, etc.
It is used for printing the decimal floating-point values. By default, it prints the
%f
6 values after '.'.
%e/%E It is used for scientific notation. It is also known as Mantissa or Exponent.
It is used to print the decimal floating-point values, and it uses the fixed
%g precision, i.e., the value after the decimal in input would be exactly the same as
the value in the output.
%p It is used to print the address in a hexadecimal form.
%c It is used to print the unsigned character.
%s It is used to print the strings.
%ld It is used to print the long-signed integer value.

Let's understand the format specifiers in detail through an example.

 %d
1. int main()
2. {
3. int b=6;
4. int c=8;
5. printf("Value of b is:%d", b);
6. printf("\nValue of c is:%d",c);
7.
8. return 0;
9. }

In the above code, we are printing the integer value of b and c by using the %d specifier.

Output

 %u

1. int main()
2. {
3. int b=10;
4. int c= -10;
5. printf("Value of b is:%u", b);
6. printf("\nValue of c is:%u",c);
7.
8. return 0;
9. }

In the above program, we are displaying the value of b and c by using an unsigned format
specifier, i.e., %u. The value of b is positive, so %u specifier prints the exact value of b, but it
does not print the value of c as c contains the negative value.

Output
 %o

1. int main()
2. {
3. int a=0100;
4. printf("Octal value of a is: %o", a);
5. printf("\nInteger value of a is: %d",a);
6. return 0;
7. }

In the above code, we are displaying the octal value and integer value of a.

Output

 %x and %X

1. int main()
2. {
3. int y=0xA;
4. printf("Hexadecimal value of y is: %x", y);
5. printf("\nHexadecimal value of y is: %X",y);
6. printf("\nInteger value of y is: %d",y);
7. return 0;
8. }

In the above code, y contains the hexadecimal value 'A'. We display the hexadecimal value of
y in two formats. We use %x and %X to print the hexadecimal value where %x displays the
value in small letters, i.e., 'a' and %X displays the value in a capital letter, i.e., 'A'.

Output

 %f

1. int main()
2. {
3. float y=3.4;
4. printf("Floating point value of y is: %f", y);
5. return 0;
6. }

The above code prints the floating value of y.

Output
 %e

1. int main()
2. {
3. float y=3;
4. printf("Exponential value of y is: %e", y);
5. return 0;
6. }

Output

 %E

1. int main()
2. {
3. float y=3;
4. printf("Exponential value of y is: %E", y);
5. return 0;
6. }

Output

 %g
1. int main()
2. {
3. float y=3.8;
4. printf("Float value of y is: %g", y);
5. return 0;
6. }

In the above code, we are displaying the floating value of y by using %g specifier. The %g
specifier displays the output same as the input with a same precision.

Escape Sequence in C
An escape sequence in C language is a sequence of characters that doesn't represent itself
when used inside string literal or character.

It is composed of two or more characters starting with backslash \. For example: \n represents
new line.

List of Escape Sequences in C


Escape Sequence Meaning
\a Alarm or Beep
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Tab (Horizontal)
\v Vertical Tab
\\ Backslash
\' Single Quote
\" Double Quote
\? Question Mark
\nnn octal number
\xhh hexadecimal number
\0 Null

Escape Sequence Example


1. #include<stdio.h>
2. int main(){
3. int number=50;
4. printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");
5. return 0;
6. }
ASCII value in C
What is ASCII code?
The full form of ASCII is the American Standard Code for information interchange. It is
a character encoding scheme used for electronics communication. Each character or a special
character is represented by some ASCII code, and each ascii code occupies 7 bits in memory.

In C programming language, a character variable does not contain a character value itself
rather the ascii value of the character variable. The ascii value represents the character
variable in numbers, and each character variable is assigned with some number range from 0
to 127. For example, the ascii value of 'A' is 65.

In the above example, we assign 'A' to the character variable whose ascii value is 65, so 65
will be stored in the character variable rather than 'A'.

Let's understand through an example.

We will create a program which will display the ascii value of the character variable.

1. #include <stdio.h>
2. int main()
3. {
4. char ch; // variable declaration
5. printf("Enter a character");
6. scanf("%c",&ch); // user input
7. printf("\n The ascii value of the ch variable is : %d", ch);
8. return 0;
9. }

In the above code, the first user will give the character input, and the input will get stored in
the 'ch' variable. If we print the value of the 'ch' variable by using %c format specifier, then it
will display 'A' because we have given the character input as 'A', and if we use the %d format
specifier then its ascii value will be displayed, i.e., 65.

Output
The above output shows that the user gave the input as 'A', and after giving input, the ascii
value of 'A' will get printed, i.e., 65.

Now, we will create a program which will display the ascii value of all the characters.

1. #include <stdio.h>
2. int main()
3. {
4. int k; // variable declaration
5. for(int k=0;k<=255;k++) // for loop from 0-255
6. {
7. printf("\nThe ascii value of %c is %d", k,k);
8. }
9. return 0;
10. }

Constants in C
A constant is a value or variable that can't be changed in the program, for example: 10, 20, 'a',
3.4, "c programming" etc.

There are different types of constants in C programming.

List of Constants in C
Constant Example

Decimal Constant 10, 20, 450 etc.

Real or Floating-point Constant 10.3, 20.2, 450.6 etc.

Octal Constant 021, 033, 046 etc.

Hexadecimal Constant 0x2a, 0x7b, 0xaa etc.

Character Constant 'a', 'b', 'x' etc.

String Constant "c", "c program", "c in javatpoint" etc.

2 ways to define constant in C


There are two ways to define constant in C programming.

1. const keyword
2. #define preprocessor

1) C const keyword
The const keyword is used to define constant in C programming.

1. const float PI=3.14;

Now, the value of PI variable can't be changed.

1. #include<stdio.h>
2. int main(){
3. const float PI=3.14;
4. printf("The value of PI is: %f",PI);
5. return 0;
6. }

Output:

The value of PI is: 3.140000

If you try to change the the value of PI, it will render compile time error.

1. #include<stdio.h>
2. int main(){
3. const float PI=3.14;
4. PI=4.5;
5. printf("The value of PI is: %f",PI);
6. return 0;
7. }

Output:

Compile Time Error: Cannot modify a const object

2) C #define preprocessor
The #define preprocessor is also used to define constant. We will learn about #define
preprocessor directive later.

What are literals?


Literals are the constant values assigned to the constant variables. We can say that the literals
represent the fixed values that cannot be modified. It also contains memory but does not have
references as variables. For example, const int =10; is a constant integer expression in which
10 is an integer literal.

Types of literals
There are four types of literals that exist in C programming:

 Integer literal
 Float literal
 Character literal
 String literal

Integer literal

It is a numeric literal that represents only integer type values. It represents the value neither in
fractional nor exponential part.

It can be specified in the following three ways:

Decimal number (base 10)

It is defined by representing the digits between 0 to 9. For example, 45, 67, etc.

Octal number (base 8)

It is defined as a number in which 0 is followed by digits such as 0,1,2,3,4,5,6,7. For


example, 012, 034, 055, etc.

Hexadecimal number (base 16)

It is defined as a number in which 0x or 0X is followed by the hexadecimal digits (i.e., digits


from 0 to 9, alphabetical characters from (a-z) or (A-Z)).

An integer literal is suffixed by following two sign qualifiers:

L or l: It is a size qualifier that specifies the size of the integer type as long.

U or u: It is a sign qualifier that represents the type of the integer as unsigned. An unsigned
qualifier contains only positive values.

Note: The order of the qualifier is not considered, i.e., both lu and ul are the same.

Let's look at a simple example of integer literal.

1. #include <stdio.h>
2. int main()
3. {
4. const int a=23; // constant integer literal
5. printf("Integer literal : %d", a);
6. return 0;
7. }

Output

Integer literal : 23
Float literal

It is a literal that contains only floating-point values or real numbers. These real numbers
contain the number of parts such as integer part, real part, exponential part, and fractional
part. The floating-point literal must be specified either in decimal or in exponential form.
Let's understand these forms in brief.

Decimal form

The decimal form must contain either decimal point, exponential part, or both. If it does not
contain either of these, then the compiler will throw an error. The decimal notation can be
prefixed either by '+' or '-' symbol that specifies the positive and negative numbers.

Examples of float literal in decimal form are:

1. 1.2, +9.0, -4.5

Let's see a simple example of float literal in decimal form.

1. #include <stdio.h>
2. int main()
3. {
4. const float a=4.5; // constant float literal
5. const float b=5.6; // constant float literal
6. float sum;
7. sum=a+b;
8. printf("%f", sum);
9. return 0;
10. }

Output

10.100000

Exponential form

The exponential form is useful when we want to represent the number, which is having a big
magnitude. It contains two parts, i.e., mantissa and exponent. For example, the number is
2340000000000, and it can be expressed as 2.34e12 in an exponential form.

Syntax of float literal in exponential form

1. [+/-] <Mantissa> <e/E> [+/-] <Exponent>

Examples of real literal in exponential notation are:

1. +1e23, -9e2, +2e-25


Character literal

A character literal contains a single character enclosed within single quotes. If multiple
characters are assigned to the variable, then we need to create a character array. If we try to
store more than one character in a variable, then the warning of a multi-character character
constant will be generated. Let's observe this scenario through an example.

1. #include <stdio.h>
2. int main()
3. {
4. const char c='ak';
5. printf("%c",c);
6. return 0;
7. }

String literal

A string literal represents multiple characters enclosed within double-quotes. It contains an


additional character, i.e., '\0' (null character), which gets automatically inserted. This null
character specifies the termination of the string. We can use the '+' symbol to concatenate two
strings.

For example,

String1= "javatpoint";

Tokens in C
Tokens in C is the most important element to be used in creating a program in C. We can
define the token as the smallest individual element in C. For `example, we cannot create a
sentence without using words; similarly, we cannot create a program in C without using
tokens in C. Therefore, we can say that tokens in C is the building block or the basic
component for creating a program in C language.

Classification of tokens in C

Tokens in C language can be divided into the following categories:


 Keywords in C
 Identifiers in C
 Strings in C
 Operators in C
 Constant in C
 Special Characters in C

Let's understand each token one by one.

Keywords in C

Keywords in C can be defined as the pre-defined or the reserved words having its own
importance, and each keyword has its own functionality. Since keywords are the pre-defined
words used by the compiler, so they cannot be used as the variable names. If the keywords
are used as the variable names, it means that we are assigning a different meaning to the
keyword, which is not allowed. C language supports 32 keywords given below:

auto double int struct

break else long switch

case enum register typedef

char extern return union

const float short unsigned

continue for signed void

default goto sizeof volatile


do if static while

Identifiers in C

Identifiers in C are used for naming variables, functions, arrays, structures, etc. Identifiers in
C are the user-defined words. It can be composed of uppercase letters, lowercase letters,
underscore, or digits, but the starting letter should be either an underscore or an alphabet.
Identifiers cannot be used as keywords. Rules for constructing identifiers in C are given
below:

 The first character of an identifier should be either an alphabet or an underscore, and then it
can be followed by any of the character, digit, or underscore.
 It should not begin with any numerical digit.
 In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say that
identifiers are case sensitive.
 Commas or blank spaces cannot be specified within an identifier.
 Keywords cannot be represented as an identifier.
 The length of the identifiers should not be more than 31 characters.
 Identifiers should be written in such a way that it is meaningful, short, and easy to read.

Strings in C

Strings in C are always represented as an array of characters having null character '\0' at the
end of the string. This null character denotes the end of the string. Strings in C are enclosed
within double quotes, while characters are enclosed within single characters. The size of a
string is a number of characters that the string contains.

Now, we describe the strings in different ways:

char a[10] = "javatpoint"; // The compiler allocates the 10 bytes to the 'a' array.

char a[] = "javatpoint"; // The compiler allocates the memory at the run time.

char a[10] = {'j','a','v','a','t','p','o','i','n','t','\0'}; // String is represented in the form of characters.

Operators in C

Operators in C is a special symbol used to perform the functions. The data items on which the
operators are applied are known as operands. Operators are applied between the operands.
Depending on the number of operands, operators are classified as follows:

Unary Operator

A unary operator is an operator applied to the single operand. For example: increment
operator (++), decrement operator (--), sizeof, (type)*.

Binary Operator
The binary operator is an operator applied between two operands. The following is the list of
the binary operators:

 Arithmetic Operators
 Relational Operators
 Shift Operators
 Logical Operators
 Bitwise Operators
 Conditional Operators
 Assignment Operator
 Misc Operator

Constants in C

A constant is a value assigned to the variable which will remain the same throughout the
program, i.e., the constant value cannot be changed.

There are two ways of declaring constant:

 Using const keyword


 Using #define pre-processor

Types of constants in C

Constant Example

Integer constant 10, 11, 34, etc.

Floating-point constant 45.6, 67.8, 11.2, etc.

Octal constant 011, 088, 022, etc.

Hexadecimal constant 0x1a, 0x4b, 0x6b, etc.

Character constant 'a', 'b', 'c', etc.

String constant "java", "c++", ".net", etc.

Special characters in C

Some special characters are used in C, and they have a special meaning which cannot be used
for another purpose.

 Square brackets [ ]: The opening and closing brackets represent the single and
multidimensional subscripts.
 Simple brackets ( ): It is used in function declaration and function calling. For example,
printf() is a pre-defined function.
 Curly braces { }: It is used in the opening and closing of the code. It is used in the opening
and closing of the loops.
 Comma (,): It is used for separating for more than one statement and for example,
separating function parameters in a function call, separating the variable when printing the
value of more than one variable using a single printf statement.
 Hash/pre-processor (#): It is used for pre-processor directive. It basically denotes that we
are using the header file.
 Asterisk (*): This symbol is used to represent pointers and also used as an operator for
multiplication.
 Tilde (~): It is used as a destructor to free memory.
 Period (.): It is used to access a member of a structure or a union.

C Boolean
In C, Boolean is a data type that contains two types of values, i.e., 0 and 1. Basically, the bool
type value represents two types of behavior, either true or false. Here, '0' represents false
value, while '1' represents true value.

In C Boolean, '0' is stored as 0, and another integer is stored as 1. We do not require to use
any header file to use the Boolean data type in C++, but in C, we have to use the header file,
i.e., stdbool.h. If we do not use the header file, then the program will not compile.

Syntax

1. bool variable_name;

Static in C
Static is a keyword used in C programming language. It can be used with both variables and
functions, i.e., we can declare a static variable and static function as well. An ordinary
variable is limited to the scope in which it is defined, while the scope of the static variable is
throughout the program.

Static keyword can be used in the following situations:

 Static global variable


When a global variable is declared with a static keyword, then it is known as a static global
variable. It is declared at the top of the program, and its visibility is throughout the program.
 Static function
When a function is declared with a static keyword known as a static function. Its lifetime is
throughout the program.
 Static local variable
When a local variable is declared with a static keyword, then it is known as a static local
variable. The memory of a static local variable is valid throughout the program, but the
scope of visibility of a variable is the same as the automatic local variables. However, when
the function modifies the static local variable during the first function call, then this modified
value will be available for the next function call also.
 Static member variables
When the member variables are declared with a static keyword in a class, then it is known as
static member variables. They can be accessed by all the instances of a class, not with a
specific instance.
 Static method
The member function of a class declared with a static keyword is known as a static method.
It is accessible by all the instances of a class, not with a specific instance.

Let's understand through an example.

1. #include <stdio.h>
2. int main()
3. {
4. printf("%d",func());
5. printf("\n%d",func());
6. return 0;
7. }
8. int func()
9. {
10. int count=0; // variable initialization
11. count++; // incrementing counter variable
12.
13. return count; }

In the above code, the func() function is called. In func(), count variable gets updated. As
soon as the function completes its execution, the memory of the count variable will be
removed. If we do not want to remove the count from memory, then we need to use the count
variable as static. If we declare the variable as static, then the variable will not be removed
from the memory even when the function completes its execution.
Static variable

A static variable is a variable that persists its value across the various function calls.

Syntax

The syntax of a static variable is given below:

1. static data_type variable_name;

Let's look at a simple example of static variable.

1. #include <stdio.h>
2. int main()
3. {
4. printf("%d",func());
5. printf("\n%d",func());
6.
7. return 0;
8. }
9. int func()
10. {
11. static int count=0;
12. count++;
13. return count;
14. }

In the above code, we have declared the count variable as static. When the func() is called,
the value of count gets updated to 1, and during the next function call, the value of the count
variable becomes 2. Therefore, we can say that the value of the static variable persists within
the function call.

Output

1
2

Static Function

As we know that non-static functions are global by default means that the function can be
accessed outside the file also, but if we declare the function as static, then it limits the
function scope. The static function can be accessed within a file only.

The static function would look like as:

1. static void func()


2. {
3. printf("Hello javaTpoint");
4. }
Differences b/w static and global variable

Global variables are the variables that are declared outside the function. These global
variables exist at the beginning of the program, and its scope remains till the end of the
program. It can be accessed outside the program also.

Static variables are limited to the source file in which they are defined, i.e., they are not
accessible by the other source files.

Both the static and global variables have static initialization. Here, static initialization means
if we do not assign any value to the variable then by default, 0 value will be assigned to the
variable.

Differences b/w static local and static global variable

Static global variable

If the variable declared with a static keyword outside the function, then it is known as a static
global variable. It is accessible throughout the program.

Static local variable

The variable with a static keyword is declared inside a function is known as a static local
variable. The scope of the static local variable will be the same as the automatic local
variables, but its memory will be available throughout the program execution. When the
function modifies the value of the static local variable during one function call, then it will
remain the same even during the next function call.

Properties of a static variable

The following are the properties of a static variable:

 The memory of a static variable is allocated within a static variable.


 Its memory is available throughout the program, but the scope will remain the same as the
automatic local variables. Its
 value will persist across the various function calls.
 If we do not assign any value to the variable, then the default value will be 0.
 A global static variable cannot be accessed outside the program, while a global variable can
be accessed by other source files.

Programming Errors in C
Errors are the problems or the faults that occur in the program, which makes the behavior of
the program abnormal, and experienced developers can also make these faults. Programming
errors are also known as the bugs or faults, and the process of removing these bugs is known
as debugging.
These errors are detected either during the time of compilation or execution. Thus, the errors
must be removed from the program for the successful execution of the program.

There are mainly five types of errors exist in C programming:

 Syntax error
 Run-time error
 Linker error
 Logical error
 Semantic error

Syntax error

Syntax errors are also known as the compilation errors as they occurred at the compilation
time, or we can say that the syntax errors are thrown by the compilers. These errors are
mainly occurred due to the mistakes while typing or do not follow the syntax of the specified
programming language. These mistakes are generally made by beginners only because they
are new to the language. These errors can be easily debugged or corrected.

For example:

1. If we want to declare the variable of type integer,


2. int a; // this is the correct form
3. Int a; // this is an incorrect form.

Commonly occurred syntax errors are:

 If we miss the parenthesis (}) while writing the code.


 Displaying the value of a variable without its declaration.
 If we miss the semicolon (;) at the end of the statement.

Let's understand through an example.

1. #include <stdio.h>
2. int main()
3. {
4. a = 10;
5. printf("The value of a is : %d", a);
6. return 0;
7. }

Output
In the above output, we observe that the code throws the error that 'a' is undeclared. This error
is nothing but the syntax error only.

There can be another possibility in which the syntax error can exist, i.e., if we make mistakes
in the basic construct. Let's understand this scenario through an example.

1. #include <stdio.h>
2. int main()
3. {
4. int a=2;
5. if(.) // syntax error
6.
7. printf("a is greater than 1");
8. return 0;
9. }

In the above code, we put the (.) instead of condition in 'if', so this generates the syntax error
as shown in the below screenshot.

Output

Run-time error

Sometimes the errors exist during the execution-time even after the successful compilation
known as run-time errors. When the program is running, and it is not able to perform the
operation is the main cause of the run-time error. The division by zero is the common
example of the run-time error. These errors are very difficult to find, as the compiler does not
point to these errors.
Let's understand through an example.

1. #include <stdio.h>
2. int main()
3. {
4. int a=2;
5. int b=2/0;
6. printf("The value of b is : %d", b);
7. return 0;
8. }

Output

In the above output, we observe that the code shows the run-time error, i.e., division by zero.

Linker error

Linker errors are mainly generated when the executable file of the program is not created.
This can be happened either due to the wrong function prototyping or usage of the wrong
header file. For example, the main.c file contains the sub() function whose declaration and
definition is done in some other file such as func.c. During the compilation, the compiler
finds the sub() function in func.c file, so it generates two object files, i.e., main.o and func.o.
At the execution time, if the definition of sub() function is not found in the func.o file, then
the linker error will be thrown. The most common linker error that occurs is that we use
Main() instead of main().

Let's understand through a simple example.

1. #include <stdio.h>
2. int Main()
3. {
4. int a=78;
5. printf("The value of a is : %d", a);
6. return 0;
7. }

Output
Logical error

The logical error is an error that leads to an undesired output. These errors produce the
incorrect output, but they are error-free, known as logical errors. These types of mistakes are
mainly done by beginners. The occurrence of these errors mainly depends upon the logical
thinking of the developer. If the programmers sound logically good, then there will be fewer
chances of these errors.

Let's understand through an example.

1. #include <stdio.h>
2. int main()
3. {
4. int sum=0; // variable initialization
5. int k=1;
6. for(int i=1;i<=10;i++); // logical error, as we put the semicolon after loop
7. {
8. sum=sum+k;
9. k++;
10. }
11. printf("The value of sum is %d", sum);
12. return 0;
13. }

Output

In the above code, we are trying to print the sum of 10 digits, but we got the wrong output as
we put the semicolon (;) after the for loop, so the inner statements of the for loop will not
execute. This produces the wrong output.

Semantic error

Semantic errors are the errors that occurred when the statements are not understandable by
the compiler.

The following can be the cases for the semantic error:


 Use of a un-initialized variable.
int i;
i=i+2;
 Type compatibility
int b = "javatpoint";
 Errors in expressions
int a, b, c;
a+b = c;
 Array index out of bound
int a[10];
a[10] = 34;

Let's understand through an example.

1. #include <stdio.h>
2. int main()
3. {
4. int a,b,c;
5. a=2;
6. b=3;
7. c=1;
8. a+b=c; // semantic error
9. return 0;
10. }

In the above code, we use the statement a+b =c, which is incorrect as we cannot use the two
operands on the left-side.

Output

Compile time vs Runtime


Compile-time and Runtime are the two programming terms used in the software
development. Compile-time is the time at which the source code is converted into an
executable code while the run time is the time at which the executable code is started
running. Both the compile-time and runtime refer to different types of error.
Compile-time errors

Compile-time errors are the errors that occurred when we write the wrong syntax. If we write
the wrong syntax or semantics of any programming language, then the compile-time errors
will be thrown by the compiler. The compiler will not allow to run the program until all the
errors are removed from the program. When all the errors are removed from the program,
then the compiler will generate the executable file.

The compile-time errors can be:

 Syntax errors
 Semantic errors

Syntax errors

When the programmer does not follow the syntax of any programming language, then the
compiler will throw the syntax error.

For example,

int a, b:

The above declaration generates the compile-time error as in C, every statement ends with the
semicolon, but we put a colon (:) at the end of the statement.

Semantic errors

The semantic errors exist when the statements are not meaningful to the compiler.

For example,

a+b=c;

The above statement throws a compile-time errors. In the above statement, we are assigning
the value of 'c' to the summation of 'a' and 'b' which is not possible in C programming
language as it can contain only one variable on the left of the assignment operator while right
of the assignment operator can contain more than one variable.

The above statement can be re-written as:

c=a+b;

Runtime errors

The runtime errors are the errors that occur during the execution and after compilation. The
examples of runtime errors are division by zero, etc. These errors are not easy to detect as the
compiler does not point to these errors.

Let's look at the differences between compile-time and runtime:


Compile-time Runtime

The compile-time errors are the errors which The runtime errors are the errors which are not
are produced at the compile-time, and they generated by the compiler and produce an
are detected by the compiler. unpredictable result at the execution time.

In this case, the compiler prevents the code


In this case, the compiler does not detect the error,
from execution if it detects an error in the
so it cannot prevent the code from the execution.
program.

It contains the syntax and semantic errors


It contains the errors such as division by zero,
such as missing semicolon at the end of the
determining the square root of a negative number.
statement.

Example of Compile-time error

1. #include <stdio.h>
2. int main()
3. {
4. int a=20;
5. printf("The value of a is : %d",a):
6. return 0;
7. }

In the above code, we have tried to print the value of 'a', but it throws an error. We put the
colon at the end of the statement instead of a semicolon, so this code generates a compile-
time error.

Conditional Operator in C
The conditional operator is also known as a ternary operator. The conditional statements are
the decision-making statements which depends upon the output of the expression. It is
represented by two symbols, i.e., '?' and ':'.

As conditional operator works on three operands, so it is also known as the ternary operator.

The behavior of the conditional operator is similar to the 'if-else' statement as 'if-else'
statement is also a decision-making statement.

Syntax of a conditional operator

1. Expression1? expression2: expression3;

The pictorial representation of the above syntax is shown below:


Meaning of the above syntax.

 In the above syntax, the expression1 is a Boolean condition that can be either true or false
value.
 If the expression1 results into a true value, then the expression2 will execute.
 The expression2 is said to be true only when it returns a non-zero value.
 If the expression1 returns false value then the expression3 will execute.
 The expression3 is said to be false only when it returns zero value.

Let's understand the ternary or conditional operator through an example.

1. #include <stdio.h>
2. int main()
3. {
4. int age; // variable declaration
5. printf("Enter your age");
6. scanf("%d",&age); // taking user input for age variable
7. (age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting")); // conditional o
perator
8. return 0;
9. }

In the above code, we are taking input as the 'age' of the user. After taking input, we have
applied the condition by using a conditional operator. In this condition, we are checking the
age of the user. If the age of the user is greater than or equal to 18, then the statement1 will
execute, i.e., (printf("eligible for voting")) otherwise, statement2 will execute, i.e.,
(printf("not eligible for voting")).

Let's observe the output of the above program.

If we provide the age of user below 18, then the output would be:
If we provide the age of user above 18, then the output would be:

As we can observe from the above two outputs that if the condition is true, then the
statement1 is executed; otherwise, statement2 will be executed.

Till now, we have observed that how conditional operator checks the condition and based on
condition, it executes the statements. Now, we will see how a conditional operator is used to
assign the value to a variable.

Let's understand this scenario through an example.

1. #include <stdio.h>
2. int main()
3. {
4. int a=5,b; // variable declaration
5. b=((a==5)?(3):(2)); // conditional operator
6. printf("The value of 'b' variable is : %d",b);
7. return 0;
8. }

In the above code, we have declared two variables, i.e., 'a' and 'b', and assign 5 value to the 'a'
variable. After the declaration, we are assigning value to the 'b' variable by using the
conditional operator. If the value of 'a' is equal to 5 then 'b' is assigned with a 3 value
otherwise 2.

Output
The above output shows that the value of 'b' variable is 3 because the value of 'a' variable is
equal to 5.

As we know that the behavior of conditional operator and 'if-else' is similar but they have
some differences. Let's look at their differences.

 A conditional operator is a single programming statement, while the 'if-else' statement is a


programming block in which statements come under the parenthesis.
 A conditional operator can also be used for assigning a value to the variable, whereas the 'if-
else' statement cannot be used for the assignment purpose.
 It is not useful for executing the statements when the statements are multiple, whereas the
'if-else' statement proves more suitable when executing multiple statements.
 The nested ternary operator is more complex and cannot be easily debugged, while the
nested 'if-else' statement is easy to read and maintain.

Bitwise Operator in C
The bitwise operators are the operators used to perform the operations on the data at the bit-
level. When we perform the bitwise operations, then it is also known as bit-level
programming. It consists of two digits, either 0 or 1. It is mainly used in numerical
computations to make the calculations faster.

We have different types of bitwise operators in the C programming language. The following
is the list of the bitwise operators:

Operator Meaning of operator

& Bitwise AND operator

| Bitwise OR operator

^ Bitwise exclusive OR operator

~ One's complement operator (unary operator)

<< Left shift operator

>> Right shift operator


Let's look at the truth table of the bitwise operators.

X Y X&Y X|Y X^Y

0 00 0 0

0 10 1 1

1 00 1 1

1 11 1 1

Bitwise AND operator

Bitwise AND operator is denoted by the single ampersand sign (&). Two integer operands
are written on both sides of the (&) operator. If the corresponding bits of both the operands
are 1, then the output of the bitwise AND operation is 1; otherwise, the output would be 0.

For example,

1. We have two variables a and b.


2. a =6;
3. b=4;
4. The binary representation of the above two variables are given below:
5. a = 0110
6. b = 0100
7. When we apply the bitwise AND operation in the above two variables, i.e., a&b, the output
would be:
8. Result = 0100

As we can observe from the above result that bits of both the variables are compared one by
one. If the bit of both the variables is 1 then the output would be 1, otherwise 0.

Let's understand the bitwise AND operator through the program.

1. #include <stdio.h>
2. int main()
3. {
4. int a=6, b=14; // variable declarations
5. printf("The output of the Bitwise AND operator a&b is %d",a&b);
6. return 0;
7. }

In the above code, we have created two variables, i.e., 'a' and 'b'. The values of 'a' and 'b' are 6
and 14 respectively. The binary value of 'a' and 'b' are 0110 and 1110, respectively. When we
apply the AND operator between these two variables,

a AND b = 0110 && 1110 = 0110

Output
Bitwise OR operator

The bitwise OR operator is represented by a single vertical sign (|). Two integer operands are
written on both sides of the (|) symbol. If the bit value of any of the operand is 1, then the
output would be 1, otherwise 0.

For example,

1. We consider two variables,


2. a = 23;
3. b = 10;
4. The binary representation of the above two variables would be:
5. a = 0001 0111
6. b = 0000 1010
7. When we apply the bitwise OR operator in the above two variables, i.e., a|b , then the outpu
t would be:
8. Result = 0001 1111

As we can observe from the above result that the bits of both the operands are compared one
by one; if the value of either bit is 1, then the output would be 1 otherwise 0.

Let's understand the bitwise OR operator through a program.

1. #include <stdio.h>
2. int main()
3. {
4. int a=23,b=10; // variable declarations
5. printf("The output of the Bitwise OR operator a|b is %d",a|b);
6. return 0;
7. }

Output
Bitwise exclusive OR operator

Bitwise exclusive OR operator is denoted by (^) symbol. Two operands are written on both
sides of the exclusive OR operator. If the corresponding bit of any of the operand is 1 then
the output would be 1, otherwise 0.

For example,

1. We consider two variables a and b,


2. a = 12;
3. b = 10;
4. The binary representation of the above two variables would be:
5. a = 0000 1100
6. b = 0000 1010
7. When we apply the bitwise exclusive OR operator in the above two variables (a^b), then the
result would be:
8. Result = 0000 1110

As we can observe from the above result that the bits of both the operands are compared one
by one; if the corresponding bit value of any of the operand is 1, then the output would be 1
otherwise 0.

Let's understand the bitwise exclusive OR operator through a program.

1. #include <stdio.h>
2. int main()
3. {
4. int a=12,b=10; // variable declarations
5. printf("The output of the Bitwise exclusive OR operator a^b is %d",a^b);
6. return 0;
7. }

Output
Bitwise complement operator

The bitwise complement operator is also known as one's complement operator. It is


represented by the symbol tilde (~). It takes only one operand or variable and performs
complement operation on an operand. When we apply the complement operation on any bits,
then 0 becomes 1 and 1 becomes 0.

For example,

1. If we have a variable named 'a',


2. a = 8;
3. The binary representation of the above variable is given below:
4. a = 1000
5. When we apply the bitwise complement operator to the operand, then the output would be
:
6. Result = 0111

As we can observe from the above result that if the bit is 1, then it gets changed to 0 else 1.

Let's understand the complement operator through a program.

1. #include <stdio.h>
2. int main()
3. {
4. int a=8; // variable declarations
5. printf("The output of the Bitwise complement operator ~a is %d",~a);
6. return 0;
7. }

Output
Bitwise shift operators

Two types of bitwise shift operators exist in C programming. The bitwise shift operators will
shift the bits either on the left-side or right-side. Therefore, we can say that the bitwise shift
operator is divided into two categories:

 Left-shift operator
 Right-shift operator

Left-shift operator

It is an operator that shifts the number of bits to the left-side.

Syntax of the left-shift operator is given below:

1. Operand << n

Where,

Operand is an integer expression on which we apply the left-shift operation.

n is the number of bits to be shifted.

In the case of Left-shift operator, 'n' bits will be shifted on the left-side. The 'n' bits on the left
side will be popped out, and 'n' bits on the right-side are filled with 0.

For example,

1. Suppose we have a statement:


2. int a = 5;
3. The binary representation of 'a' is given below:
4. a = 0101
5. If we want to left-shift the above representation by 2, then the statement would be:
6. a << 2;
7. 0101<<2 = 00010100

Let's understand through a program.

1. #include <stdio.h>
2. int main()
3. {
4. int a=5; // variable initialization
5. printf("The value of a<<2 is : %d ", a<<2);
6. return 0;
7. }

Output

Right-shift operator

It is an operator that shifts the number of bits to the right side.

Syntax of the right-shift operator is given below:

1. Operand >> n;

Where,

Operand is an integer expression on which we apply the right-shift operation.

N is the number of bits to be shifted.

In the case of the right-shift operator, 'n' bits will be shifted on the right-side. The 'n' bits on
the right-side will be popped out, and 'n' bits on the left-side are filled with 0.

For example,

1. Suppose we have a statement,


2. int a = 7;
3. The binary representation of the above variable would be:
4. a = 0111
5. If we want to right-shift the above representation by 2, then the statement would be:
6. a>>2;
7. 0000 0111 >> 2 = 0000 0001

Let's understand through a program.

1. #include <stdio.h>
2. int main()
3. {
4. int a=7; // variable initialization
5. printf("The value of a>>2 is : %d ", a>>2);
6. return 0;
7. }

Output

C if else Statement
The if-else statement in C is used to perform the operations based on some specific condition.
The operations specified in if block are executed if and only if the given condition is true.

There are the following variants of if statement in C language.

 If statement
 If-else statement
 If else-if ladder
 Nested if

If Statement
The if statement is used to check some given condition and perform some operations
depending upon the correctness of that condition. It is mostly used in the scenario where we
need to perform the different operations for the different conditions. The syntax of the if
statement is given below.

1. if(expression){
2. //code to be executed
3. }

Flowchart of if statement in C
Let's see a simple example of C language if statement.

1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("Enter a number:");
5. scanf("%d",&number);
6. if(number%2==0){
7. printf("%d is even number",number);
8. }
9. return 0;
10. }

Output

Enter a number:4
4 is even number
enter a number:5
Program to find the largest number of the three.

1. #include <stdio.h>
2. int main()
3. {
4. int a, b, c;
5. printf("Enter three numbers?");
6. scanf("%d %d %d",&a,&b,&c);
7. if(a>b && a>c)
8. {
9. printf("%d is largest",a);
10. }
11. if(b>a && b > c)
12. {
13. printf("%d is largest",b);
14. }
15. if(c>a && c>b)
16. {
17. printf("%d is largest",c);
18. }
19. if(a == b && a == c)
20. {
21. printf("All are equal");
22. }
23. }

Output

Enter three numbers?


12 23 34
34 is largest

If-else Statement
The if-else statement is used to perform two operations for a single condition. The if-else
statement is an extension to the if statement using which, we can perform two different
operations, i.e., one is for the correctness of that condition, and the other is for the
incorrectness of the condition. Here, we must notice that if and else block cannot be executed
simiulteneously. Using if-else statement is always preferable since it always invokes an
otherwise case with every if condition. The syntax of the if-else statement is given below.

1. if(expression){
2. //code to be executed if condition is true
3. }else{
4. //code to be executed if condition is false
5. }

Flowchart of the if-else statement in C


Let's see the simple example to check whether a number is even or odd using if-else
statement in C language.

1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. if(number%2==0){
7. printf("%d is even number",number);
8. }
9. else{
10. printf("%d is odd number",number);
11. }
12. return 0;
13. }

Output

enter a number:4
4 is even number
enter a number:5
5 is odd number

If else-if ladder Statement


The if-else-if ladder statement is an extension to the if-else statement. It is used in the
scenario where there are multiple cases to be performed for different conditions. In if-else-if
ladder statement, if a condition is true then the statements defined in the if block will be
executed, otherwise if some other condition is true then the statements defined in the else-if
block will be executed, at the last if none of the condition is true then the statements defined
in the else block will be executed. There are multiple else-if blocks possible. It is similar to
the switch case statement where the default is executed instead of else block if none of the
cases is matched.

1. if(condition1){
2. //code to be executed if condition1 is true
3. }else if(condition2){
4. //code to be executed if condition2 is true
5. }
6. else if(condition3){
7. //code to be executed if condition3 is true
8. }
9. ...
10. else{
11. //code to be executed if all the conditions are false
12. }

Flowchart of else-if ladder statement in C


The example of an if-else-if statement in C language is given below.

1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. if(number==10){
7. printf("number is equals to 10");
8. }
9. else if(number==50){
10. printf("number is equal to 50");
11. }
12. else if(number==100){
13. printf("number is equal to 100");
14. }
15. else{
16. printf("number is not equal to 10, 50 or 100");
17. }
18. return 0;
19. }
Output

enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

Program to calculate the grade of the student according to the specified marks.

1. #include <stdio.h>
2. int main()
3. {
4. int marks;
5. printf("Enter your marks?");
6. scanf("%d",&marks);
7. if(marks > 85 && marks <= 100)
8. {
9. printf("Congrats ! you scored grade A ...");
10. }
11. else if (marks > 60 && marks <= 85)
12. {
13. printf("You scored grade B + ...");
14. }
15. else if (marks > 40 && marks <= 60)
16. {
17. printf("You scored grade B ...");
18. }
19. else if (marks > 30 && marks <= 40)
20. {
21. printf("You scored grade C ...");
22. }
23. else
24. {
25. printf("Sorry you are fail ...");
26. }
27. }

Output

Enter your marks?10


Sorry you are fail ...
Enter your marks?40
You scored grade C ...
Enter your marks?90
Congrats ! you scored grade A ...

C Switch Statement
The switch statement in C is an alternate to if-else-if ladder statement which allows us to
execute multiple operations for the different possibles values of a single variable called
switch variable. Here, We can define various statements in the multiple cases for the different
values of a single variable.
The syntax of switch statement in c language is given below:

1. switch(expression){
2. case value1:
3. //code to be executed;
4. break; //optional
5. case value2:
6. //code to be executed;
7. break; //optional
8. ......
9.
10. default:
11. code to be executed if all cases are not matched;
12. }

Rules for switch statement in C language

1) The switch expression must be of an integer or character type.

2) The case value must be an integer or character constant.

3) The case value can be used only inside the switch statement.

4) The break statement in switch case is not must. It is optional. If there is no break statement
found in the case, all the cases will be executed present after the matched case. It is known as
fall through the state of C switch statement.

Let's try to understand it by the examples. We are assuming that there are following variables.

1. int x,y,z;
2. char a,b;
3. float f;

Valid Switch Invalid Switch Valid Case Invalid Case

switch(x) switch(f) case 3; case 2.5;

switch(x>y) switch(x+2.5) case 'a'; case x;

switch(a+b-2) case 1+2; case x+2;

switch(func(x,y)) case 'x'>'y'; case 1,2,3;


Flowchart of switch statement in C

Functioning of switch case statement


First, the integer expression specified in the switch statement is evaluated. This value is then
matched one by one with the constant values given in the different cases. If a match is found,
then all the statements specified in that case are executed along with the all the cases present
after that case including the default statement. No two cases can have similar values. If the
matched case contains a break statement, then all the cases present after that will be skipped,
and the control comes out of the switch. Otherwise, all the cases following the matched case
will be executed.

Let's see a simple example of c language switch statement.

1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. switch(number){
7. case 10:
8. printf("number is equals to 10");
9. break;
10. case 50:
11. printf("number is equal to 50");
12. break;
13. case 100:
14. printf("number is equal to 100");
15. break;
16. default:
17. printf("number is not equal to 10, 50 or 100");
18. }
19. return 0;
20. }

Output

enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

Switch case example 2

1. #include <stdio.h>
2. int main()
3. {
4. int x = 10, y = 5;
5. switch(x>y && x+y>0)
6. {
7. case 1:
8. printf("hi");
9. break;
10. case 0:
11. printf("bye");
12. break;
13. default:
14. printf(" Hello bye ");
15. }
16.
17. }

Output

hi
C Switch statement is fall-through

In C language, the switch statement is fall through; it means if you don't use a break
statement in the switch case, all the cases after the matching case will be executed.

Let's try to understand the fall through state of switch statement by the example given below.

1. #include<stdio.h>
2. int main(){
3. int number=0;
4.
5. printf("enter a number:");
6. scanf("%d",&number);
7.
8. switch(number){
9. case 10:
10. printf("number is equal to 10\n");
11. case 50:
12. printf("number is equal to 50\n");
13. case 100:
14. printf("number is equal to 100\n");
15. default:
16. printf("number is not equal to 10, 50 or 100");
17. }
18. return 0;
19. }

Output

enter a number:10
number is equal to 10
number is equal to 50
number is equal to 100
number is not equal to 10, 50 or 100

Output

enter a number:50
number is equal to 50
number is equal to 100
number is not equal to 10, 50 or 100

Nested switch case statement

We can use as many switch statement as we want inside a switch statement. Such type of
statements is called nested switch case statements. Consider the following example.

1. #include <stdio.h>
2. int main () {
3.
4. int i = 10;
5. int j = 20;
6.
7. switch(i) {
8.
9. case 10:
10. printf("the value of i evaluated in outer switch: %d\n",i);
11. case 20:
12. switch(j) {
13. case 20:
14. printf("The value of j evaluated in nested switch: %d\n",j);
15. }
16. }
17.
18. printf("Exact value of i is : %d\n", i );
19. printf("Exact value of j is : %d\n", j );
20.
21. return 0;
22. }

if-else vs switch
What is an if-else statement?

An if-else statement in C programming is a conditional statement that executes a different set


of statements based on the condition that is true or false. The 'if' block will be executed only
when the specified condition is true, and if the specified condition is false, then the else block
will be executed.

Syntax of if-else statement is given below:

1. if(expression)
2. {
3. // statements;
4. }
5. else
6. {
7. // statements;
8. }

What is a switch statement?

A switch statement is a conditional statement used in C programming to check the value of a


variable and compare it with all the cases. If the value is matched with any case, then its
corresponding statements will be executed. Each case has some name or number known as
the identifier. The value entered by the user will be compared with all the cases until the case
is found. If the value entered by the user is not matched with any case, then the default
statement will be executed.

Syntax of the switch statement is given below:


1. switch(expression)
2. {
3. case constant 1:
4. // statements;
5. break;
6. case constant 2:
7. // statements;
8. break;
9. case constant n:
10. // statements;
11. break;
12. default:
13. // statements;
14. }

Similarity b/w if-else and switch

Both the if-else and switch are the decision-making statements. Here, decision-making
statements mean that the output of the expression will decide which statements are to be
executed.

Differences b/w if-else and switch statement

The following are the differences between if-else and switch statement are:

 Definition

if-else

Based on the result of the expression in the 'if-else' statement, the block of statements will be
executed. If the condition is true, then the 'if' block will be executed otherwise 'else' block
will execute.

Switch statement
The switch statement contains multiple cases or choices. The user will decide the case, which
is to execute.

 Expression

If-else

It can contain a single expression or multiple expressions for multiple choices. In this, an
expression is evaluated based on the range of values or conditions. It checks both equality
and logical expressions.

Switch

It contains only a single expression, and this expression is either a single integer object or a
string object. It checks only equality expression.

 Evaluation

If-else

An if-else statement can evaluate almost all the types of data such as integer, floating-point,
character, pointer, or Boolean.

Switch

A switch statement can evaluate either an integer or a character.

 Sequence of Execution

If-else

In the case of 'if-else' statement, either the 'if' block or the 'else' block will be executed based
on the condition.

Switch

In the case of the 'switch' statement, one case after another will be executed until the break
keyword is not found, or the default statement is executed.

 Default Execution

If-else

If the condition is not true within the 'if' statement, then by default, the else block statements
will be executed.

Switch

If the expression specified within the switch statement is not matched with any of the cases,
then the default statement, if defined, will be executed.
 Values

If-else

Values are based on the condition specified inside the 'if' statement. The value will decide
either the 'if' or 'else' block is to be executed.

Switch

In this case, value is decided by the user. Based on the choice of the user, the case will be
executed.

 Use

If-else

It evaluates a condition to be true or false.

Switch

A switch statement compares the value of the variable with multiple cases. If the value is
matched with any of the cases, then the block of statements associated with this case will be
executed.

 Editing

If-else

Editing in 'if-else' statement is not easy as if we remove the 'else' statement, then it will create
the havoc.

Switch

Editing in switch statement is easier as compared to the 'if-else' statement. If we remove any
of the cases from the switch, then it will not interrupt the execution of other cases. Therefore,
we can say that the switch statement is easy to modify and maintain.

 Speed

If-else

If the choices are multiple, then the speed of the execution of 'if-else' statements is slow.

Switch

The case constants in the switch statement create a jump table at the compile time. This jump
table chooses the path of the execution based on the value of the expression. If we have a
multiple choice, then the execution of the switch statement will be much faster than the
equivalent logic of 'if-else' statement.
Let's summarize the above differences in a tabular form.

If-else switch

Depending on the condition in the


The user will decide which statement is to be
Definition 'if' statement, 'if' and 'else' blocks
executed.
are executed.

It contains either logical or equality It contains a single expression which can be


Expression
expression. either a character or integer variable.

It evaluates all types of data, such


Evaluation as integer, floating-point, character It evaluates either an integer, or character.
or Boolean.

First, the condition is checked. If It executes one case after another till the break
Sequence of
the condition is true then 'if' block keyword is not found, or the default statement is
execution
is executed otherwise 'else' block executed.

Default If the condition is not true, then by If the value does not match with any case, then
execution default, else block will be executed. by default, default statement is executed.

Cases in a switch statement are easy to maintain


Editing is not easy in the 'if-else' and modify. Therefore, we can say that the
Editing
statement. removal or editing of any case will not interrupt
the execution of other cases.

If there are multiple choices


If we have multiple choices then the switch
implemented through 'if-else', then
Speed statement is the best option as the speed of the
the speed of the execution will be
execution will be much higher than 'if-else'.
slow.

C Loops
The looping can be defined as repeating the same process multiple times until a specific
condition satisfies. There are three types of loops used in the C language. In this part of the
tutorial, we are going to learn all the aspects of C loops.

Why use loops in C language?


The looping simplifies the complex problems into the easy ones. It enables us to alter the
flow of the program so that instead of writing the same code again and again, we can repeat
the same code for a finite number of times. For example, if we need to print the first 10
natural numbers then, instead of using the printf statement 10 times, we can print inside a
loop which runs up to 10 iterations.
Advantage of loops in C

1) It provides code reusability.

2) Using loops, we do not need to write the same code again and again.

3) Using loops, we can traverse over the elements of data structures (array or linked lists).

Types of C Loops
There are three types of loops in C language that is given below:

1. do while
2. while
3. for

do-while loop in C

The do-while loop continues until a given condition satisfies. It is also called post tested loop.
It is used when it is necessary to execute the loop at least once (mostly menu driven
programs).

The syntax of do-while loop in c language is given below:

1. do{
2. //code to be executed
3. }while(condition);

Flowchart and Example of do-while loop

while loop in C

The while loop in c is to be used in the scenario where we don't know the number of
iterations in advance. The block of statements is executed in the while loop until the
condition specified in the while loop is satisfied. It is also called a pre-tested loop.

The syntax of while loop in c language is given below:

1. while(condition){
2. //code to be executed
3. }

Flowchart and Example of while loop

for loop in C

The for loop is used in the case where we need to execute some part of the code until the
given condition is satisfied. The for loop is also called as a per-tested loop. It is better to use
for loop if the number of iteration is known in advance.
The syntax of for loop in c language is given below:

1. for(initialization;condition;incr/decr){
2. //code to be executed
3. }

do while loop in C
The do while loop is a post tested loop. Using the do-while loop, we can repeat the execution
of several parts of the statements. The do-while loop is mainly used in the case where we
need to execute the loop at least once. The do-while loop is mostly used in menu-driven
programs where the termination condition depends upon the end user.

do while loop syntax

The syntax of the C language do-while loop is given below:

1. do{
2. //code to be executed
3. }while(condition);

Example 1

1. #include<stdio.h>
2. #include<stdlib.h>
3. void main ()
4. {
5. char c;
6. int choice,dummy;
7. do{
8. printf("\n1. Print Hello\n2. Print Javatpoint\n3. Exit\n");
9. scanf("%d",&choice);
10. switch(choice)
11. {
12. case 1 :
13. printf("Hello");
14. break;
15. case 2:
16. printf("Javatpoint");
17. break;
18. case 3:
19. exit(0);
20. break;
21. default:
22. printf("please enter valid choice");
23. }
24. printf("do you want to enter more?");
25. scanf("%d",&dummy);
26. scanf("%c",&c);
27. }while(c=='y');
28. }

Output
1. Print Hello
2. Print Javatpoint
3. Exit
1
Hello
do you want to enter more?
y

1. Print Hello
2. Print Javatpoint
3. Exit
2
Javatpoint
do you want to enter more?
n

Flowchart of do while loop

do while example

There is given the simple program of c language do while loop where we are printing the
table of 1.

1. #include<stdio.h>
2. int main(){
3. int i=1;
4. do{
5. printf("%d \n",i);
6. i++;
7. }while(i<=10);
8. return 0;
9. }

Output
1
2
3
4
5
6
7
8
9
10

Program to print table for the given number using do while loop

1. #include<stdio.h>
2. int main(){
3. int i=1,number=0;
4. printf("Enter a number: ");
5. scanf("%d",&number);
6. do{
7. printf("%d \n",(number*i));
8. i++;
9. }while(i<=10);
10. return 0;
11. }

Output
Enter a number: 5
5
10
15
20
25
30
35
40
45
50
Enter a number: 10
10
20
30
40
50
60
70
80
90
100
Infinitive do while loop

The do-while loop will run infinite times if we pass any non-zero value as the conditional
expression.

1. do{
2. //statement
3. }while(1);

Next Topic C while loop

while loop in C
While loop is also known as a pre-tested loop. In general, a while loop allows a part of the
code to be executed multiple times depending upon a given boolean condition. It can be
viewed as a repeating if statement. The while loop is mostly used in the case where the
number of iterations is not known in advance.

Syntax of while loop in C language

The syntax of while loop in c language is given below:

1. while(condition){
2. //code to be executed
3. }

Flowchart of while loop in C


Example of the while loop in C language
Let's see the simple program of while loop that prints table of 1.

1. #include<stdio.h>
2. int main(){
3. int i=1;
4. while(i<=10){
5. printf("%d \n",i);
6. i++;
7. }
8. return 0;
9. }

Output
1
2
3
4
5
6
7
8
9
10

Program to print table for the given number using while


loop in C
1. #include<stdio.h>
2. int main(){
3. int i=1,number=0,b=9;
4. printf("Enter a number: ");
5. scanf("%d",&number);
6. while(i<=10){
7. printf("%d \n",(number*i));
8. i++;
9. }
10. return 0;
11. }

Output
Enter a number: 50
50
100
150
200
250
300
350
400
450
500
Enter a number: 100
100
200
300
400
500
600
700
800
900
1000

Properties of while loop


 A conditional expression is used to check the condition. The statements defined inside the
while loop will repeatedly execute until the given condition fails.
 The condition will be true if it returns 0. The condition will be false if it returns any non-zero
number.
 In while loop, the condition expression is compulsory.
 Running a while loop without a body is possible.
 We can have more than one conditional expression in while loop.
 If the loop body contains only one statement, then the braces are optional.

Example 1

1. #include<stdio.h>
2. void main ()
3. {
4. int j = 1;
5. while(j+=2,j<=10)
6. {
7. printf("%d ",j);
8. }
9. printf("%d",j);
10. }

Output
3 5 7 9 11

Example 2

1. #include<stdio.h>
2. void main ()
3. {
4. while()
5. {
6. printf("hello Javatpoint");
7. }
8. }
Output
compile time error: while loop can't be empty

Example 3

1. #include<stdio.h>
2. void main ()
3. {
4. int x = 10, y = 2;
5. while(x+y-1)
6. {
7. printf("%d %d",x--,y--);
8. }
9. }

Output
infinite loop

Infinitive while loop in C


If the expression passed in while loop results in any non-zero value then the loop will run the
infinite number of times.

1. while(1){
2. //statement
3. }

for loop in C
The for loop in C language is used to iterate the statements or a part of the program several
times. It is frequently used to traverse the data structures like the array and linked list.

Syntax of for loop in C

The syntax of for loop in c language is given below:

1. for(Expression 1; Expression 2; Expression 3){


2. //code to be executed
3. }
Flowchart of for loop in C

C for loop Examples

Let's see the simple program of for loop that prints table of 1.

1. #include<stdio.h>
2. int main(){
3. int i=0;
4. for(i=1;i<=10;i++){
5. printf("%d \n",i);
6. }
7. return 0;
8. }

Output

1
2
3
4
5
6
7
8
9
10

C Program: Print table for the given number using C for loop

1. #include<stdio.h>
2. int main(){
3. int i=1,number=0;
4. printf("Enter a number: ");
5. scanf("%d",&number);
6. for(i=1;i<=10;i++){
7. printf("%d \n",(number*i));
8. }
9. return 0;
10. }

Output

Enter a number: 2
2
4
6
8
10
12
14
16
18
20
Enter a number: 1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000

Properties of Expression 1

 The expression represents the initialization of the loop variable.


 We can initialize more than one variable in Expression 1.
 Expression 1 is optional.
 In C, we can not declare the variables in Expression 1. However, It can be an exception in
some compilers.

Example 1

1. #include <stdio.h>
2. int main()
3. {
4. int a,b,c;
5. for(a=0,b=12,c=23;a<2;a++)
6. {
7. printf("%d ",a+b+c);
8. }
9. }

Output

35 36

Example 2

1. #include <stdio.h>
2. int main()
3. {
4. int i=1;
5. for(;i<5;i++)
6. {
7. printf("%d ",i);
8. }
9. }

Output

1 2 3 4

Properties of Expression 2

 Expression 2 is a conditional expression. It checks for a specific condition to be satisfied. If it


is not, the loop is terminated.
 Expression 2 can have more than one condition. However, the loop will iterate until the last
condition becomes false. Other conditions will be treated as statements.
 Expression 2 is optional.
 Expression 2 can perform the task of expression 1 and expression 3. That is, we can initialize
the variable as well as update the loop variable in expression 2 itself.
 We can pass zero or non-zero value in expression 2. However, in C, any non-zero value is
true, and zero is false by default.

Example 1

1. #include <stdio.h>
2. int main()
3. {
4. int i;
5. for(i=0;i<=4;i++)
6. {
7. printf("%d ",i);
8. }
9. }

output

0 1 2 3 4

Example 2

1. #include <stdio.h>
2. int main()
3. {
4. int i,j,k;
5. for(i=0,j=0,k=0;i<4,k<8,j<10;i++)
6. {
7. printf("%d %d %d\n",i,j,k);
8. j+=2;
9. k+=3;
10. }
11. }

Output

0 0 0
1 2 3
2 4 6
3 6 9
4 8 12

Example 3

1. #include <stdio.h>
2. int main()
3. {
4. int i;
5. for(i=0;;i++)
6. {
7. printf("%d",i);
8. }
9. }

Output

infinite loop

Properties of Expression 3

 Expression 3 is used to update the loop variable.


 We can update more than one variable at the same time.
 Expression 3 is optional.

Example 1
1. #include<stdio.h>
2. void main ()
3. {
4. int i=0,j=2;
5. for(i = 0;i<5;i++,j=j+2)
6. {
7. printf("%d %d\n",i,j);
8. }
9. }

Output

0 2
1 4
2 6
3 8
4 10

Loop body

The braces {} are used to define the scope of the loop. However, if the loop contains only one
statement, then we don't need to use braces. A loop without a body is possible. The braces
work as a block separator, i.e., the value variable declared inside for loop is valid only for
that block and not outside. Consider the following example.

1. #include<stdio.h>
2. void main ()
3. {
4. int i;
5. for(i=0;i<10;i++)
6. {
7. int i = 20;
8. printf("%d ",i);
9. }
10. }

Output

20 20 20 20 20 20 20 20 20 20

Infinitive for loop in C

To make a for loop infinite, we need not give any expression in the syntax. Instead of that, we
need to provide two semicolons to validate the syntax of the for loop. This will work as an
infinite for loop.

1. #include<stdio.h>
2. void main ()
3. {
4. for(;;)
5. {
6. printf("welcome to javatpoint");
7. }
8. }

If you run this program, you will see above statement infinite times.

Nested Loops in C
C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping
of statements inside another loop. Let's observe an example of nesting loops in C.

Any number of loops can be defined inside another loop, i.e., there is no restriction for
defining any number of loops. The nesting level can be defined at n times. You can define
any type of loop inside another loop; for example, you can define 'while' loop inside a 'for'
loop.

Syntax of Nested loop

1. Outer_loop
2. {
3. Inner_loop
4. {
5. // inner loop statements.
6. }
7. // outer loop statements.
8. }

Outer_loop and Inner_loop are the valid loops that can be a 'for' loop, 'while' loop or 'do-
while' loop.

Nested for loop

The nested for loop means any type of loop which is defined inside the 'for' loop.

1. for (initialization; condition; update)


2. {
3. for(initialization; condition; update)
4. {
5. // inner loop statements.
6. }
7. // outer loop statements.
8. }

Example of nested for loop

1. #include <stdio.h>
2. int main()
3. {
4. int n;// variable declaration
5. printf("Enter the value of n :");
6. // Displaying the n tables.
7. for(int i=1;i<=n;i++) // outer loop
8. {
9. for(int j=1;j<=10;j++) // inner loop
10. {
11. printf("%d\t",(i*j)); // printing the value.
12. }
13. printf("\n");
14. }

Explanation of the above code

 First, the 'i' variable is initialized to 1 and then program control passes to the i<=n.
 The program control checks whether the condition 'i<=n' is true or not.
 If the condition is true, then the program control passes to the inner loop.
 The inner loop will get executed until the condition is true.
 After the execution of the inner loop, the control moves back to the update of the
outer loop, i.e., i++.
 After incrementing the value of the loop counter, the condition is checked again, i.e.,
i<=n.
 If the condition is true, then the inner loop will be executed again.
 This process will continue until the condition of the outer loop is true.

Output:

Nested while loop

The nested while loop means any type of loop which is defined inside the 'while' loop.

1. while(condition)
2. {
3. while(condition)
4. {
5. // inner loop statements.
6. }
7. // outer loop statements.
8. }
Example of nested while loop

1. #include <stdio.h>
2. int main()
3. {
4. int rows; // variable declaration
5. int columns; // variable declaration
6. int k=1; // variable initialization
7. printf("Enter the number of rows :"); // input the number of rows.
8. scanf("%d",&rows);
9. printf("\nEnter the number of columns :"); // input the number of columns.
10. scanf("%d",&columns);
11. int a[rows][columns]; //2d array declaration
12. int i=1;
13. while(i<=rows) // outer loop
14. {
15. int j=1;
16. while(j<=columns) // inner loop
17. {
18. printf("%d\t",k); // printing the value of k.
19. k++; // increment counter
20. j++;
21. }
22. i++;
23. printf("\n");
24. }
25. }

Explanation of the above code.

 We have created the 2d array, i.e., int a[rows][columns].


 The program initializes the 'i' variable by 1.
 Now, control moves to the while loop, and this loop checks whether the condition is
true, then the program control moves to the inner loop.
 After the execution of the inner loop, the control moves to the update of the outer
loop, i.e., i++.
 After incrementing the value of 'i', the condition (i<=rows) is checked.
 If the condition is true, the control then again moves to the inner loop.
 This process continues until the condition of the outer loop is true.

Output:
Nested do..while loop

The nested do..while loop means any type of loop which is defined inside the 'do..while' loop.

1. do
2. {
3. do
4. {
5. // inner loop statements.
6. }while(condition);
7. // outer loop statements.
8. }while(condition);

Example of nested do..while loop.

1. #include <stdio.h>
2. int main()
3. {
4. /*printing the pattern
5. ********
6. ********
7. ********
8. ******** */
9. int i=1;
10. do // outer loop
11. {
12. int j=1;
13. do // inner loop
14. {
15. printf("*");
16. j++;
17. }while(j<=8);
18. printf("\n");
19. i++;
20. }while(i<=4);
21. }

Output:

Explanation of the above code.

 First, we initialize the outer loop counter variable, i.e., 'i' by 1.


 As we know that the do..while loop executes once without checking the condition, so
the inner loop is executed without checking the condition in the outer loop.
 After the execution of the inner loop, the control moves to the update of the i++.
 When the loop counter value is incremented, the condition is checked. If the condition
in the outer loop is true, then the inner loop is executed.
 This process will continue until the condition in the outer loop is true.

Infinite Loop in C
What is infinite loop?
An infinite loop is a looping construct that does not terminate the loop and executes the loop
forever. It is also called an indefinite loop or an endless loop. It either produces a continuous
output or no output.

When to use an infinite loop


An infinite loop is useful for those applications that accept the user input and generate the
output continuously until the user exits from the application manually. In the following
situations, this type of loop can be used:

 All the operating systems run in an infinite loop as it does not exist after performing some
task. It comes out of an infinite loop only when the user manually shuts down the system.
 All the servers run in an infinite loop as the server responds to all the client requests. It
comes out of an indefinite loop only when the administrator shuts down the server
manually.
 All the games also run in an infinite loop. The game will accept the user requests until the
user exits from the game.
We can create an infinite loop through various loop structures. The following are the loop
structures through which we will define the infinite loop:

 for loop
 while loop
 do-while loop
 go to statement
 C macros

For loop

Let's see the infinite 'for' loop. The following is the definition for the infinite for loop:

1. for(; ;)
2. {
3. // body of the for loop.
4. }

As we know that all the parts of the 'for' loop are optional, and in the above for loop, we
have not mentioned any condition; so, this loop will execute infinite times.

Let's understand through an example.

1. #include <stdio.h>
2. int main()
3. {
4. for(;;)
5. {
6. printf("Hello javatpoint");
7. }
8. return 0;
9. }

In the above code, we run the 'for' loop infinite times, so "Hello javatpoint" will be
displayed infinitely.

Output
while loop

Now, we will see how to create an infinite loop using a while loop. The following is the
definition for the infinite while loop:

1. while(1)
2. {
3. // body of the loop..
4. }

In the above while loop, we put '1' inside the loop condition. As we know that any non-zero
integer represents the true condition while '0' represents the false condition.

Let's look at a simple example.

1. #include <stdio.h>
2. int main()
3. {
4. int i=0;
5. while(1)
6. {
7. i++;
8. printf("i is :%d",i);
9. }
10. return 0;
11. }

In the above code, we have defined a while loop, which runs infinite times as it does not
contain any condition. The value of 'i' will be updated an infinite number of times.

Output
do..while loop

The do..while loop can also be used to create the infinite loop. The following is the syntax to
create the infinite do..while loop.

1. do
2. {
3. // body of the loop..
4. }while(1);

The above do..while loop represents the infinite condition as we provide the '1' value inside
the loop condition. As we already know that non-zero integer represents the true condition, so
this loop will run infinite times.

goto statement

We can also use the goto statement to define the infinite loop.

1. infinite_loop;
2. // body statements.
3. goto infinite_loop;

In the above code, the goto statement transfers the control to the infinite loop.

Macros

We can also create the infinite loop with the help of a macro constant. Let's understand
through an example.

1. #include <stdio.h>
2. #define infinite for(;;)
3. int main()
4. {
5.
6. infinite
7. {
8. printf("hello");
9. }
10.
11. return 0;
12. }

In the above code, we have defined a macro named as 'infinite', and its value is 'for(;;)'.
Whenever the word 'infinite' comes in a program then it will be replaced with a 'for(;;)'.

Output

Till now, we have seen various ways to define an infinite loop. However, we need some
approach to come out of the infinite loop. In order to come out of the infinite loop, we can
use the break statement.

Let's understand through an example.

1. #include <stdio.h>
2. int main()
3. {
4. char ch;
5. while(1)
6. {
7. ch=getchar();
8. if(ch=='n')
9. {
10. break;
11. }
12. printf("hello");
13. }
14. return 0;
15. }

In the above code, we have defined the while loop, which will execute an infinite number of
times until we press the key 'n'. We have added the 'if' statement inside the while loop. The 'if'
statement contains the break keyword, and the break keyword brings control out of the loop.

Unintentional infinite loops

Sometimes the situation arises where unintentional infinite loops occur due to the bug in the
code. If we are the beginners, then it becomes very difficult to trace them. Below are some
measures to trace an unintentional infinite loop:

 We should examine the semicolons carefully. Sometimes we put the semicolon at the wrong
place, which leads to the infinite loop.

1. #include <stdio.h>
2. int main()
3. {
4. int i=1;
5. while(i<=10);
6. {
7. printf("%d", i);
8. i++;
9. }
10. return 0;
11. }

In the above code, we put the semicolon after the condition of the while loop which leads to
the infinite loop. Due to this semicolon, the internal body of the while loop will not execute.

 We should check the logical conditions carefully. Sometimes by mistake, we place the
assignment operator (=) instead of a relational operator (= =).

1. #include <stdio.h>
2. int main()
3. {
4. char ch='n';
5. while(ch='y')
6. {
7. printf("hello");
8. }
9. return 0;
10. }

In the above code, we use the assignment operator (ch='y') which leads to the execution of
loop infinite number of times.

 We use the wrong loop condition which causes the loop to be executed indefinitely.
1. #include <stdio.h>
2. int main()
3. {
4. for(int i=1;i>=1;i++)
5. {
6. printf("hello");
7. }
8. return 0;
9. }

The above code will execute the 'for loop' infinite number of times. As we put the condition
(i>=1), which will always be true for every condition, it means that "hello" will be printed
infinitely.

 We should be careful when we are using the break keyword in the nested loop because it
will terminate the execution of the nearest loop, not the entire loop.

1. #include <stdio.h>
2. int main()
3. {
4. while(1)
5. {
6. for(int i=1;i<=10;i++)
7. {
8. if(i%2==0)
9. {
10. break;
11. }
12. }
13. }
14. return 0;
15. }

In the above code, the while loop will be executed an infinite number of times as we use the
break keyword in an inner loop. This break keyword will bring the control out of the inner
loop, not from the outer loop.

 We should be very careful when we are using the floating-point value inside the loop as we
cannot underestimate the floating-point errors.

1. #include <stdio.h>
2. int main()
3. {
4. float x = 3.0;
5. while (x != 4.0) {
6. printf("x = %f\n", x);
7. x += 0.1;
8. }
9. return 0;
10. }
In the above code, the loop will run infinite times as the computer represents a floating-point
value as a real value. The computer will represent the value of 4.0 as 3.999999 or 4.000001,
so the condition (x !=4.0) will never be false. The solution to this problem is to write the
condition as (k<=4.0).

C break statement
The break is a keyword in C which is used to bring the program control out of the loop. The
break statement is used inside loops or switch statement. The break statement breaks the loop
one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to
outer loops. The break statement in C can be used in the following two scenarios:

1. With switch case


2. With loop

Syntax:

1. //loop or switch case


2. break;

Flowchart of break in c

Example

1. #include<stdio.h>
2. #include<stdlib.h>
3. void main ()
4. {
5. int i;
6. for(i = 0; i<10; i++)
7. {
8. printf("%d ",i);
9. if(i == 5)
10. break;
11. }
12. printf("came outside of loop i = %d",i);
13.
14. }

Output

0 1 2 3 4 5 came outside of loop i = 5

Example of C break statement with switch case

Click here to see the example of C break with the switch statement.

C break statement with the nested loop


In such case, it breaks only the inner loop, but not outer loop.

1. #include<stdio.h>
2. int main(){
3. int i=1,j=1;//initializing a local variable
4. for(i=1;i<=3;i++){
5. for(j=1;j<=3;j++){
6. printf("%d &d\n",i,j);
7. if(i==2 && j==2){
8. break;//will break loop of j only
9. }
10. }//end of for loop
11. return 0;
12. }

Output

1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3

As you can see the output on the console, 2 3 is not printed because there is a break statement
after printing i==2 and j==2. But 3 1, 3 2 and 3 3 are printed because the break statement is
used to break the inner loop only.

break statement with while loop


Consider the following example to use break statement inside while loop.
1. #include<stdio.h>
2. void main ()
3. {
4. int i = 0;
5. while(1)
6. {
7. printf("%d ",i);
8. i++;
9. if(i == 10)
10. break;
11. }
12. printf("came out of while loop");
13. }

Output

0 1 2 3 4 5 6 7 8 9 came out of while loop

break statement with do-while loop


Consider the following example to use the break statement with a do-while loop.

1. #include<stdio.h>
2. void main ()
3. {
4. int n=2,i,choice;
5. do
6. {
7. i=1;
8. while(i<=10)
9. {
10. printf("%d X %d = %d\n",n,i,n*i);
11. i++;
12. }
13. printf("do you want to continue with the table of %d , enter any non-zero value to contin
ue.",n+1);
14. scanf("%d",&choice);
15. if(choice == 0)
16. {
17. break;
18. }
19. n++;
20. }while(1);
21. }

Output

2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
2 X 4 = 8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
do you want to continue with the table of 3 , enter any non-zero value to
continue.1
3 X 1 = 3
3 X 2 = 6
3 X 3 = 9
3 X 4 = 12
3 X 5 = 15
3 X 6 = 18
3 X 7 = 21
3 X 8 = 24
3 X 9 = 27
3 X 10 = 30
do you want to continue with the table of 4 , enter any non-zero value to
continue.0

C continue statement
The continue statement in C language is used to bring the program control to the beginning
of the loop. The continue statement skips some lines of code inside the loop and continues
with the next iteration. It is mainly used for a condition so that we can skip some code for a
particular condition.

Syntax:

1. //loop statements
2. continue;
3. //some lines of the code which is to be skipped

Continue statement example 1


1. #include<stdio.h>
2. void main ()
3. {
4. int i = 0;
5. while(i!=10)
6. {
7. printf("%d", i);
8. continue;
9. i++;
10. }
11. }

Output

infinite loop
Continue statement example 2
1. #include<stdio.h>
2. int main(){
3. int i=1;//initializing a local variable
4. //starting a loop from 1 to 10
5. for(i=1;i<=10;i++){
6. if(i==5){//if value of i is equal to 5, it will continue the loop
7. continue;
8. }
9. printf("%d \n",i);
10. }//end of for loop
11. return 0;
12. }

Output

1
2
3
4
6
7
8
9
10

As you can see, 5 is not printed on the console because loop is continued at i==5.

C continue statement with inner loop


In such case, C continue statement continues only inner loop, but not outer loop.

1. #include<stdio.h>
2. int main(){
3. int i=1,j=1;//initializing a local variable
4. for(i=1;i<=3;i++){
5. for(j=1;j<=3;j++){
6. if(i==2 && j==2){
7. continue;//will continue loop of j only
8. }
9. printf("%d %d\n",i,j);
10. }
11. }//end of for loop
12. return 0;
13. }

Output

1 1
1 2
1 3
2 1
2 3
3 1
3 2
3 3

As you can see, 2 2 is not printed on the console because inner loop is continued at i==2 and
j==2.

C goto statement
The goto statement is known as jump statement in C. As the name suggests, goto is used to
transfer the program control to a predefined label. The goto statment can be used to repeat
some part of the code for a particular condition. It can also be used to break the multiple
loops which can't be done by using a single break statement. However, using goto is avoided
these days since it makes the program less readable and complecated.

Syntax:

1. label:
2. //some part of the code;
3. goto label;

goto example
Let's see a simple example to use goto statement in C language.

1. #include <stdio.h>
2. int main()
3. {
4. int num,i=1;
5. printf("Enter the number whose table you want to print?");
6. scanf("%d",&num);
7. table:
8. printf("%d x %d = %d\n",num,i,num*i);
9. i++;
10. if(i<=10)
11. goto table;
12. }

Output:

Enter the number whose table you want to print?10


10 x 1 = 10
10 x 2 = 20
10 x 3 = 30
10 x 4 = 40
10 x 5 = 50
10 x 6 = 60
10 x 7 = 70
10 x 8 = 80
10 x 9 = 90
10 x 10 = 100

When should we use goto?


The only condition in which using goto is preferable is when we need to break the multiple
loops using a single statement at the same time. Consider the following example.

1. #include <stdio.h>
2. int main()
3. {
4. int i, j, k;
5. for(i=0;i<10;i++)
6. {
7. for(j=0;j<5;j++)
8. {
9. for(k=0;k<3;k++)
10. {
11. printf("%d %d %d\n",i,j,k);
12. if(j == 3)
13. {
14. goto out;
15. }
16. }
17. }
18. }
19. out:
20. printf("came out of the loop");
21. }

0 0 0
0 0 1
0 0 2
0 1 0
0 1 1
0 1 2
0 2 0
0 2 1
0 2 2
0 3 0
came out of the loop

Type Casting in C
Typecasting allows us to convert one data type into other. In C language, we use cast operator
for typecasting which is denoted by (type).
Syntax:

1. (type)value;

Note: It is always recommended to convert the lower value to higher for avoiding data loss.

Without Type Casting:

1. int f= 9/4;
2. printf("f : %d\n", f );//Output: 2

With Type Casting:

1. float f=(float) 9/4;


2. printf("f : %f\n", f );//Output: 2.250000

Type Casting example


Let's see a simple example to cast int value into the float.

1. #include<stdio.h>
2. int main(){
3. float f= (float)9/4;
4. printf("f : %f\n", f );
5. return 0;
6. }

Output:

f : 2.250000

You might also like