C Programming Notes
C Programming Notes
What is Language?
Language is a mode of communication that is used to share ideas, opinions with each
other. For example, if we want to teach someone, we need a language that is
understandable by both communicators.
i. Machine Language
The advantage of assembly language is that it requires less memory and less execution
time to execute a program.
The main advantage of a high-level language is that it is easy to read, write, and
maintain.
High-level programming language includes Python, Java, JavaScript, PHP, C#, C++,
Objective C, Cobol, Perl, Pascal, LISP, FORTRAN, and Swift programming language.
The advantage of POP language is that it helps programmers to easily track the
program flow and code can be reused in different parts of the program.
The main advantage of object-oriented programming is that OOP is faster and easier to
execute, maintain, modify, as well as debug.
Natural language is a part of human languages such as English, Russian, German, and
Japanese. It is used by machines to understand, manipulate, and interpret human's
language. It is used by developers to perform tasks such as translation, automatic
summarization, Named Entity Recognition (NER), relationship extraction, and
topic segmentation.
The main advantage of natural language is that it helps users to ask questions in any
subject and directly respond within seconds.
What is C language?
C Language is a general-purpose, programming language. Which was created by Dennis
Ritchie in 1972 at AT & T’S Bell Telephone Laboratories. Dennis Ritchie wanted to
create an operating system named Unix Operating System. to develop it, the C language
was developed.
The special thing is that we can do low-level programming with the help of C language,
due to this feature, C programming language is used to make system software such as
Operating system, Device Driver, Compiler, etc.
C Language covered the Basic features ( Variable, Data Types, Array, String, Function,
Structure, Pointer, Loop, etc.) of all other programming languages, due to which C
language is called Mother Language of all other programming languages.
Features of C Language
C is a simple and easy programming language.
There are commands/instructions like English in C language which are very easy for a
programmer to read, understand, and code.
C is a Procedure Oriented Programming Language.
C is a very powerful and case sensitive programming language.
C Language is a Compiler based dynamic programming language.
C language is a middle level language due to which both low level and high level
programming can be done.
The C language is the most commonly used programming language in developing
operating systems and embedded systems.
C language is a very portable and powerful programming language.
C language is a Syntax Based Language.
C is a general purpose programming language that covers basic features of all other
languages.
Applications of C Language
If you are learning any programming language and you do not know what you can make by
learning that language, then you will not be able to do anything by learning that language.
In such a situation, you should know what you are going to do by learning that language, so
let’s know what you can make with the help of C language.
You can make a good operating system using C Language like- Windows, Linux, Mac.
because the major part of this operating system is written in C language.
With the help of C Language you can create a Compiler which converts programming
language code into machine language.
With this, you can create a Text Editor.
Utility Software can be created.
Can create software with database management like – Oracle, Mysql, etc.
Device drivers can be created.
What is the History of C Language?
In earlier times, every programming language was created to fulfill some purpose, such
as Forton (Formula Translator) was created to make Scientific and Mathematical
Applications. Similarly, COBOL (Common Business Oriented Language) was created to
make business applications.
In similar way, C Language was also originally created to make the Unix operating
system. C Language was developed by Dennis Ritchie in 1972 at Bell Laboratories of
AT&T (American Telephone & Telegraph).
Dennis Ritchie is said to be the inventor of the C language, but the history of C language
is quite interesting.
in 1960 Dennis Ritchie and some other employees working on a project called Multics, at
Bell Laboratories of AT&T (American Telephone & Telegraph).
The aim of this project was to create an operating system for a large computer on which
thousands of people could work simultaneously.
But AT&T Bell Laboratories closed this project after a few years because this project
could not make money for them. After the closure of the project, all the employees of this
project got involved in the work of another project.
Ken Thompson, who was also working on Project Multics, created a file system. He used
the knowledge gained from the Multics project to further improve this file system.
When Ken Thompson completed the work of that system, he named the system Unix, the
entire code of this system was written in Assembly Language.
Ken Thompson created Unix with the help of B Language, B Language was created by
Ken Thompson in 1969 by improving a little more the language BCPL which was created
by Martin Richards, so Ken Thompson named his language in honor of Martin Richards.
BCPL was created in 1966 by Martin Richards to combine the basic features of all other
programming languages of the time. Which further improvised by Ken Thompson for his
use and created the B language.
The biggest drawback of B Language was that there was no concept of “Data Types”
(everything was expressed in machine language) and B Language did not provide the
functionality of “Structure”.
Dennis Ritchie created C Language in 1972, removing all these drawbacks of B
Language. Dennis Ritchie has added some more features in C language along with
removing the drawback of B Language.
C Language was a powerful mixture of high-level functionality and operating system
building features. Therefore, many components of Unix were re-written in the C
language.
Kernighan and Ritchie wrote a book called, “The C Programming Language, 1st edition”
(Kernighan said that he has no contribution in the design of C language. It has been made
entirely by Dennis Ritchie, but he ” Is the author of famous programs like Hello World
”and other Unix programs).
ANSI (American National Standards Institute) published A standard of C language in
1989 that was called ANSI C or “C89” due to this published standard.
This standard was approved by the ISO (International Organization for Standardization)
in 1990, after that, it was called “C90”. In 1999, ISO published another standard of C
language for the internationalization of C. after that C was called “C99”.
In 2011, another standard was published for C, after that, it was named “C11” and in
2018, another standard of C was published that is called “C18”. C18 is the latest standard
in the C programming language.
Features of C Language
These are some special features of C Language, due to which C language has made its place
in the hearts of programmers for the last 50 years.
1. Portability
2. Powerful Programming Language
3. Simple Programming Language
4. Structured Oriented Language
5. Compiler Based
6. Syntax Based Language
7. Efficient use of pointers
8. Middle level language
9. Case sensitive
10. Modularity
1. Portability
C programs are very portable means that C programs can be run easily on different machines
or PCs with little change or no change. Compiler and Preprocessor make it possible to run on
different PCs.
Read about compiler and preprocessor from here – Compiler and Preprocessor.
5. Compiler Based
C language is a compiler based programming language. Programs of C language cannot be
executed or run without compiling.
9. Case Sensitive
C language is a Case Sensitive Programming Language. We understand the meaning of Case
Sensitive by an example, if we write such printf in C language and write PRINTF in another
place, then in C language, both are different things. This is a special feature of C Language.
If the words written in Lower Case and Upper Case in a programming language have
different meanings, then such programming language is called Case Sensitive Programming
Language like – C, C ++, JAVA, .NET Programming Language is Case Sensitive
Programming Language and such Programming language in which there is no difference
between the words written in Lower Case and Upper Case is called Case Insensitive
Programming Language. HTML, SQL Language is a case insensitive language.
10. Modularity
In C language, we can divide our code into blocks so that it is easier to read and write the
code. It is a technique to design software in which a whole program is divided into several
functions or blocks.
Application of C Language
C language is used to create Computer Application Software like Databases,
spreadsheets, etc.
Embedded software is used in writing.
C language is used to create system software such as Operating System
To create applications related to Graphics such as Computer and Mobile games |
Unix kernel has been fully developed in C language.
C Language is used to create Network Devices and Device drivers.
C language is used to make a compiler. The compiler converts the high level code into
low level code or machine code.
Basic Structure of C Program
Whenever we create a program in C language, we can divide that program into six different
sections. This section is as follows:
1. Documentation (Documentation Section)
2. Preprocessor Statements (Link Section)
3. Definition Section
4. Global Declarations Section
5. Main functions section
6. User-Defined Functions or Sub Program Section
In C language, all these six sections together make up the Basic Structure of C Program. Now
let’s learn in detail about all these sections -:
3. Definition Section
The definition of Symbolic Constant is defined in this section, so this section is called
Definition Section. Macros are used in this section.
Example -:
#define PI 3.14
4. Global Declarations Section
Within the Global Declarations Section section, we declare such variables which we can use
anywhere in our program, and that variable is called Global Variables, we can use these
variables in any function.
In the Global Declaration section, we also declare functions that we want to use anywhere in
our program, and such functions are called Global Function.
Example -:
int area (int x); //global function
int n; // global Variable
Types of Tokens In C
There are six types of tokens –
Keywords
Identifiers
Constants
Strings
Special Symbols
Operators
Let’s learn one by one about all these types of C Tokens in detail.
1. Keywords
When we write a program in C language, then there are some words in the program and every
word has some meaning, and the word which is already defined is called Keyword or
Reserved Word or Predefined Word.
Because the keywords are predefined or reserved, so they cannot be used as the name of a
variable. They have their own different significance and specialty.
If we use a keyword as the name of a Variable, then it means, we are changing the meaning
of the keyword which is not allowed in the C language.
Each keyword has its own meaning, and its meaning cannot be changed. The compiler is
already aware of the meaning of all keywords, so the compiler does not need to tell the
meaning of these keywords separately.
C language supports total 32 keywords, which are given below. We write the keywords in the
lowercase letter.
auto double int struct
break else long switch
case enum register typedef
char extern return union
const short float unsigned
continue for signed void
default goto sizeof volatile
do if static while
2. Identifiers
You will see many things in your daily life such as car, mobile, home, your friends like
Ramesh, Suresh, etc. You may know all of them by a different name. Just think once, if they
are not named, how will you talk about them?
So it is very important to have their name so that we can uniquely identify everyone and that
name we call Identifiers.
Identifiers are used to name Variable, Function, Array, Structure, etc. In C language,
Identifiers are user-defined. User-defined means the user determines what will be the name of
Variable, Function, Array, Structure, etc.
The names contain only uppercase letters, lowercase letters, underscore, and numbers. But
the two identifiers cannot have the same name. Also, we cannot use keywords as identifiers.
3. String
String is an Array of character that ends with a Null character (\ 0). The Null character (\ 0)
indicates that the string is over. String is always written with double quotes (” “). The size of
the string depends on the number of characters present in it.
We can define a string in different ways -:
char string [20] = {‘C’, ‘s’, T’, ‘u’, ‘t’, ‘o’, r ‘, i’, ‘a’, ‘l’, p ‘, o’, ‘i’, ‘n’, ‘t’, ‘\ 0’};
char string [20] = “CsTutorialpoint”;
char string [] = “CsTutorialpoint”;
In the above examples, the compiler will allocate 20 bytes of memory in the string, in which
String is represented as a character. In the second example also, the compiler will allocate 20
bytes of memory to the string in RAM, and in the third example, the compiler will allocate
memory to the string in RAM at run time.
4. Operator
You must have read about a lot of operators in maths. For example, like 2 + 4 in it, 2 and 4
are called operands or data, and + we are called operators. So the operator performs the basic
operation and the operator needs some data or operands for the operation. Without operands,
the operator cannot do any of his work.
In C language, there are some similar operators, with the help of which we perform some
operations. Depending on the number of operands the operator can be divided into two parts:
–
1. Unary Operators
2. Binary Operators
5. Constant
Constants are those whose value does not change. Once the value is declared, it cannot be
changed. Constant’s value is fixed, this is also called Literals.
We can declare Constant in two ways -:
Using const keyword
Using #define pre-processor
Types of Constant
Constant Example
Integer constant 4, 111, 110, 34, etc.
Floating-point constant 65.6, 67.8, 11.2, 2.0 etc.
Octal constant 011, 088, 022, etc.
Hexadecimal constant 0x1a, 0x4b, 0x6b, etc.
Character constant ‘a’, ‘b’, ‘c’, etc.
String constant “C”, “C++”, “Python”, “Java”, “.net”, etc.
6. Special Character
Some special symbols are used in C language which has their own special meaning and
cannot be used for any other purpose.
The following Special Symbols are used in the C language which has their own special
meaning and cannot be used for any other purpose.
Brackets [] -: Opening and Closing brackets are used in references to the Array element, It
also indicate single and multidimensional subscripts.
Parentheses () -: parenthesis () is used in function calls and function declaration in C
language.
Curly Braces {} -: Curly Braces {} is used to start and end the code. Curly Braces {} tells the
compiler that the code starts where it is and ends with it.
Comma (,) -: Comma (,) is used to separate multiple statements such as when separating
parameters in a function call, when printing the value of more than one variable by printf().
To isolate those variables, etc.
Semicolon (;) -: The semicolon (;) is used when a statement in the program has ended. the
semicolon tells the compiler that the statement in the program has ended.
Assignment operator (=) -: It is used to assign value to a variable in C language.
Pre-processor (#) -: This is used for preprocessor directives. This symbol tells the pre-
processor, that the header file is to be used in this line of the program.
Whenever we want to store any information or data in our computer or laptop, then we store
it in the memory of our computer. The operating system provides a complex address, in
which data is stored in memory, which is difficult for normal users like us to remember.
In such a situation, the operating system also provides some features to the normal user so
that he can decide the name of the place in which he wants to keep that data and if he creates
a folder, then he Can keep the data or information inside that folder. so that, if he needs that
data or information further, then he can easily find and retrieve it.
Similarly, when we create a program in the C language, and if we want to store any data in
that program, then we store that data or information in memory And the place where we have
stored that data or information, we give a name of that place. and that place name is called a
variable, we give memory location a name so that data can be easily found later.
In simple words, a Variable is the name of the place in memory where we store any data
or information, so that, if the information is needed then it can easily find and use it.
Variable Declaration -:
When we create a variable to store data in C language, first of all we have to declare that
variable and this is called declaration.
Through variable declaration, we tell the compiler that:
What is the name of the variable
Which type of data is going to be stored in the variable.
How much space in memory will be needed to store data to the variable so that the
compiler can allocate memory to that variable correctly.
By declaring the variable, we tell the compiler that we are going to use this name and
type in the variable in our program.
Example -:
int num;
num = 78;
In this example int is a data type that tells the compiler that the integer type value is going to
be stored in this variable and num is the name of the variable in which we are storing 78 .
We can declare the variable using the extern keyword, although it is optional.
Example -:
extern int a, b, c;
Variable Definition -:
When we declare a variable in our program and tell the compiler that this data type and name
of variable is going to be used in our program, it is called variable definition. Variable
declaration and variable definition are related to each other.
Example -:
int a;
float b, c;
Initializing a variable -:
When we store a value in the declared variable, it is called initialization.
Example -:
int num;
num = 100;
In this example, we store 100 values in a variable named num, by num = 100.
We can also initialize a variable in a single line by a single statement.
Example -:
int num = 96;
Types of Variables in C
In C language, Variables are of the following types:
1. Local variable
2. Global variable
1. Local variable
A variable that we declare inside a function or block is called a local variable.
The scope of the local variable is only up to that block or function, we cannot use such
variable in any other function.
Declaration of such variables has to be done at the beginning and the local variable needs to
be initialized before use.
The scope of a local variable is only up to the block in which that declare is, we cannot use
such variable in any other block or function.
Example -:
#include <stdio.h>
void fun()
{
int x = 150; // local variable
}
int main()
{
fun();
}
In this example, the scope of x variable is only up to the fun () function, we cannot use it in
any other function except the fun () function.
2. Global variable
Global variables are variables that are declared outside the function or block. We can use the
global variable in any other block or function. The value of this variable can be used and
changed in any function.
It is necessary to declare this variable before using it.
Example -:
#include <stdio.h>
int x = 10; //global variable
void fun1()
{
printf("%d \n" , x);
}
void fun2()
{
printf("%d \n" , x);
}
int main()
{
fun1();
fun2();
return 0;
}
Output -:
10
10
In the above example, we have declared the x variable outside the function or block and used
this x variable with both fun1 () and fun2 () functions because it is a global variable that we
can use with any function.
Output -:
x = 14, ch = a, f1 = 25.700001
Syntax -:
int x = 5;
long int y;
Example
#include <stdio.h>
int main ()
{
int x = 5;
long int y;
printf ("Enter a Number \n");
scanf ("%d", &y);
printf ("value of x = %d, y = %d", x, y);
return 0;
}
Output -:
Enter a Number
10
value of x = 5, y = 10
Character Type
We store character type data in a variable made with char data type.
The “char” keyword is used to create a variable of character type.
A variable created by the keyword “char” stores a single character.
Variables made with Character Type have a size of 1 byte.
The %c Format Specifier is used to print the value of a variable made of char data
type.
Syntax
char ch = 'A';
char ch2 = 'a';
Example
#include <stdio.h>
int main ()
{
char ch = 'A';
char ch2;
printf ("Enter a Character \n");
scanf ("%c", &ch2);
printf ("value of ch = %c, ch2 = %c", ch, ch2);
return 0;
}
Output -:
Enter a Character
B
value of ch = A, ch2 = B
Float
It is used to store decimal points values.
The “float” keyword is used to create a variable of floating point type.
The variable made from Float Type has a size of 4 bytes.
The %f Format Specifier is used to print the value of a variable made of Float data
type.
return 0;
}
Output -:
Enter a decimal number
10.06
Sum of x and y is 15.560000
Double
It is also used to store data with decimal points like float data type.
The “double” keyword is used to create a variable of double data type.
A variable made of double type has a size of 8 byte.
The %lf Format Specifier is used to print the value of a variable made of double data
type.
return 0;
}
Output
float x = 680000000.000000 and double y = 679999999.454000
Friends, all the data types that you have known about above are called basic data types or pre-
defined data types. Let’s now learn about Derived Data Types.
2. Derived Data Types
Derived Data Types are data types that contain grouping of variables.
Derived Data Types is as follows:
Array
Function
Pointer
We will learn about these Derived Data Types in our further post details.
Here, the “+” operator is known as Addition Operator and the ‘a’ and ‘b’ are operands. The
Addition Operator tells the compiler to be added both operands ‘a’ and ‘b’.
If you are learning a programming language and do not have the concept of operators, then
that programming language is incomplete because operators are the foundation of any
programming language and C language is incomplete without operators.
Operators are used to manipulate data and variables in a program. In C language, we will read
about different type operators.
1. Arithmetic Operators
Arithmetic Operators are used to perform arithmetic operations such as Addition,
Subtraction, Multiplication, Division, etc.
The following operators are covered under Arithmetic Operators -: (+, -, *, /,%, post-
increment, pre-increment, post-decrement, pre-decrement).
There are two types of Arithmetic Operators.
1. Unary Operators
2. Binary Operators
2. Relational Operators
Relational operators are used to compare between two operands, such as to determine which
of the two operands is larger and which is smaller, to determine whether one of the operands
is equal to another of the operands.
Relational Operators provide the result as True or False. Some examples of Relational
Operators are: (==,> =, <=)
3. Logical Operators
Logical Operators are used to combine two and more conditions. The result always gets
Boolean value by Logical Operators which means the result is given as True or False and we
consider True as 1 and False as 0.
For Example -: In C language Logical Operators (&&) returns true in the result when both
conditions are satisfied and if both conditions are not satisfied then it returns False in the
result.
Examples of Logical Operators are: (&&, ||,!) |
4. Bitwise Operators
Bitwise Operators are used to perform operations in the bit level between operands. Bitwise
Operators first convert the operands to Bit and then perform the operation.
To perform fast processing of Mathematical operations like addition, subtraction,
multiplication, etc is done at Bit-level by Bitwise Operators.
Examples of Bitwise Operators are: – (&, |, ^, ~, >>, <<)
5. Assignment Operators
Assignment Operators are used to assign a value to a variable. The operator on the left side of
the Assignment Operators is the variable and the operator on the right side is the value that
has to be stored in the left side operands (variable).
In Assignment Operators, the left side will be a variable, and the right side should also be the
value of the same type because we can assign the same type of value in a variable.
If the operands on both sides are of different types then that value cannot be assigned in the
variable and if we do this then there is a risk of data loss.
sizeof operator
The sizeof operator is heavily used in the C/C++ programming language. It is a unary
operator run in a compile-time that can be used to calculate the size of operands.
The result of sizeof operator is an unsigned integral type which is usually denoted by size_t.
Basically, the sizeof operator is used to calculate the size of a variable.
Comma operator
Comma Operator is a binary operator that evaluates the first operand and provides the result,
then evaluates the second operator and then returns its result. The Comma Operator has the
lowest precedence in any C operator. The comma acts as both an operator and a separator.
Conditional Operator
Is Conditional Operator something like this Expression1? Expression2: Expression3. First of
all, Expression1 is seen and then if Expression1 is true then Expression2 is executed, and if
Expression1 is false. Then Expression3 is executed.
Unary Operators In C
Operators who need only one operand to perform the operation are called Unary Operators.
Examples of this operators are -: ‘+ +’, ‘- -‘, here we call the “+ +” operator as the Increment
Operator and the “- -” operator we call the Decrement Operator.
# 1) Increment Operator In C
Increment Operators are operators that, when used with a variable, then it increases the value
of that variable by one.
For Example -: Suppose we have created a variable x by int data type and store 5 values in it.
Now if we use Increment Operator in variable x then the value of x variable will increase
from 5 to 6.
Output -:
Before using increment operator the value of x is: 5
After using increment operator the value of x is: 6
We can use the Increment Operator in two ways, one before the Variable name and
the other after the Variable name.
When we use increment operator before a variable name then it is called pre
increment operator and when it is used after a variable name then it is called post
increment operator.
While using the increment operator both ways, the value of the variable increases by
one,
But when we use pre increment and post increment operator at a time where more
than one operator is being used, then the result of both types of increment operator
can be different there.
First we will create a program using the pre increment operator, then the second one using the
post increment operator, and finally, we will compare the result/output of these two.
printf ("\n Post Increment Operator Result -: Value is: x = %d, y = %d", x, y);
return 0;
}
Output -:
Post Increment Operator Result -: Value is: x = 6, y = 5
# 2) Decrement Operator In C
Decrement operator is an operator that, when used with a variable, then it reduce the value of
that variable by one. We can also use Decrement Operator as an increment operator in two
ways, one before the variable name and the other after the variable name.
When we use Decrement Operator before variable name then it is called Pre Decrement
Operator and when we use it after variable name then it is called Post Decrement Operator.
return 0;
}
Output -:
Post Decrement Operator Result -: Value is: x = 4, y = 5
Binary Operators In C
The operators who require two operands to perform the operation are called Binary
Operators.
Examples of this Operators are: (+, -, *, /,%). here “+” Is called an Addition Operator, “-” is
called Subtraction Operator. “*” Is called a Multiplication Operator. “/” Is called Division
Operator. “%” Is called Modulus Operator or Modulo Operator.
c = a+b;
printf ("Addition of a + b is: %d", c);
c = a-b;
printf ("\n Subtraction of a-b is: %d", c);
c = a*b;
printf ("\n Multiplication of a*b is: %d", c);
c = a/b;
printf ("\n Division of a/b is: %d", c);
c = a%b;
printf ("\n Remainder of is: %d", c);
return 0;
}
Output -:
Enter two number
10
5
Addition of a + b is: 15
Subtraction of a-b is: 5
Multiplication of a*b is: 50
Division of a/b is: 2
Remainder of is: 0
Relational Operators in C
Relational operators are used to make comparisons between any two operands such as -: One
operand is equal to another operand or not, to know which of the two operands is bigger and
which is smaller Etc.
Relational Operators returns the result as True and False.
if (a==b)
{
printf("\n Both Are Equal");
}
else
{
printf("\n Both Are Not Equal");
}
return 0;
}
Output -:
Enter Two Number
10
20
Both Are Not Equal
if (a!=b)
{
printf ("\n Both Are Equal");
}
else
{
printf ("\n Both Are Not Equal");
}
return 0;
}
Output -:
Enter Two Number
15
15
Both Are Not Equal
In this example, both the operands are equal, but Not equal to operator (! =) Returned false
which led to both Are Not Equal in the result.
if (A!=B)
{
printf ("\n A is Greater Than B");
}
else
{
printf ("\n A is Smaller Than B");
}
return 0;
}
Output -:
Enter Two Number
20
15
A is greater than B
if (A!=B)
{
printf ("\n A is Less Than B");
}
else
{
printf ("\n A is Greater Than B");
}
return 0;
}
Output -:
Enter Two Number
10
20
A is Less Than B
if (A>=B)
{
printf ("\n A is Greater Than Or Equal to B");
}
else
{
printf ("\n A is Not Greater Than Or Equal to B");
}
return 0;
}
Output -:
Enter A Number
5
A is Greater Than Or Equal to B
6. Less than or equal to operator (<=)
This operator checks from the given operands whether the first operand is small or equal to
the second operand. If the first operand is small or equal, then it returns true in the result and
if the first operand is not smaller or equal to the second operand, then it returns False.
Example -:
#include <stdio.h>
int main ()
{
int A = 3, B = 5;
if (A<=B)
{
printf ("\n A is Less Than Or Equal to B");
}
else
{
printf ("\n A is Not Less Than Or Equal to B");
}
return 0;
}
Output -:
A is Less Than Or Equal to B
Logical Operators In C
Logical Operators are used to combine two and more conditions. The result always gets
Boolean value by Logical Operators, which means the result is given as True or False and we
consider True as 1 and False as 0.
For Example -: In C language Logical Operators (&&) returns true in the result when both
conditions are satisfied and if both conditions are not satisfied then it returns False in the
result.
Examples of Logical Operators are : (&&, ||,!) In this, “&&” is called AND Operator, ” || ” is
called OR Operator. ” ! ” is called NOT Operator.
Let’s now learn about all these operators one by one.
Output -:
Initial value of a is: 10
Final value of a is: 10
Result of logical expression is: 0
You saw in this example, a == 20 is wrong in the expression but the operand a++ was correct,
its result should be 11, but the compiler did not check it because the first operand was wrong
and that is why the compiler after the first operand was wrong Did not run a++ at all.
int main ()
{
int a = 10, result;
Example -:
#include <stdio.h>
int main ()
{
int a = 110, result;
printf ("Initial value of a = %d \n", a);
Assignment Operators In C
Assignment operators is a binary operator which is used to assign values in a variable, with
its right and left sides being a one-one operand. The operand on the left side is variable in
which the value is assigned and the right side operands can contain any of the constant,
variable, and expression.
Example -:
x = 18 // right operand is a constant
We can assign the same value to multiple variables simultaneously by the assignment
operator.
x = y = z = 100
Here x, y, and z are initialized to 100.
In C language, the assignment operator can be divided into two categories.
1. Simple assignment operator
2. Compound assignment operators
Conditional Operator in C
Conditional Operator is a ternary operator as it works on three operands. The Conditional
Operator behaves like an if-else statement.
With the help of Conditional Operator, we can also do all the work done by if-else.
With the conditional operator, we can write code using very few lines.
Conditional statements are represented by two symbols, namely, ‘? Is represented by ‘and’: ‘.
(?:)
Look at this syntax, if the condition of Expression1 is True, then Expression2 runs or else
Expression3 runs.
Example – Conditional Operator In C
We are going to create such a program with the help of conditional operator.
In which we will say the user to enter his age. Then they will check the age entered by them
and tell them whether the user is eligible for voting or not.
If the user is eligible for voting, then we will print “eligible for voting” in the output,
otherwise, we will print “not eligible for voting”.
#include <stdio.h>
int main ()
{
int age; // variable declaration
Syntax
if (condition)
{
Statements;
}
if statements are of 3 types:
If..else
Nested if esle
Else if ladder
if else Statement
In this decision control statement, we have two blocks of statements. One block is inside if
and the other block is inside else.
If, If condition is true, then the statement inside the if block is executed, otherwise the
statement inside the else block is executed.
Syntax
if (Condition)
{
True block of statements
}
Else
{
False block of statements
}
else if ladder
else if ladder control statement is also like if-else statement but there is a slight difference in
it that inside else block one or more if-else statement conditions are present.
Syntax
if (condition1)
{
// These statements would execute if the condition1 is true
}
else if (condition2)
{
// These statements would execute if the condition2 is true
}
else if (condition3)
{
// These statements would execute if the condition3 is true
}
.
.
else
{
// These statements would execute if all the conditions return false.
}
Nested if else
When inside the if statement or else statement one or more if else statement, then it is called
Nested
Syntax
if (condition) {
// Nested if else inside the body of "if"
if (condition2) {
// Statements inside the body of nested "if"
}
else {
// Statements inside the body of nested "else"
}
}
else {
// Statements inside the body of "else"
}
Loop Statements
When we want to repeatedly run a particular statement until a particular condition is met,
then in that case we use Loop Statements.
There are three types of loop statements in C language:
While loop
Do while loop
For loop
While loop
In the while loop, the first condition is checked and if the condition is true only then the
statement inside the while loop is run until the statement inside the while loop runs as long as
the condition of the while loop is true. as soon as the condition is False, the control is moved
out of the while loop, and another statement is executed.
Syntax
while (Condition)
{
Statements;
}
Do while loop
The do-while loop is also similar to the while loop, but there is a difference in that the while
loop first checks the condition, and the statements inside the while loop are run only when the
condition is true whereas, in the do-while loop the condition is true Or False, the statement
inside it runs once.
Syntax
Do
{
// statements inside the loop
}
While (condition);
For loop
In For Loop, we write both the initialization and control condition of the variable together
inside the parentheses “()”. If the condition of For Loop is true, then the statement inside it is
run, or else the statement is not run.
Syntax
for (initialization statement; condition)
{
// statements inside the loop
}
Switch statement
When we have a lot of conditions and we have to run a statement matching that condition,
then we use the switch case statement. with the help of Switch Case Statement We can do all
the work done by if-else
Syntax
Switch (expression)
{
Case label1:
Statement (S);
Break;
Case label2:
Statement (S);
Break;
Case label3;
Statement (s);
Break;
….
Case labelN:
Statement (s);
Break;
Default:
Statement (s);
}
Goto Statement
The goto statement is also known as the jump control statement, it is used to transfer the
control of the program from one block to another. The goto keyword is used when declaring
the goto statement.
Syntax
goto labelname;
Labelname;
In the syntax above, goto is a keyword used to transfer control to labelname. labelname is a
variable name. goto will transfer the control of the program to labelname and the statements
after labelname will be executed.
if statement in C
When we want to execute a statement inside a block only when the given condition is
true, then we use the if statement.
if Statement is a very simple Decision Making Control Statement which decides on
the basis of the given condition whether the statement inside the if block will run or
not.
If the condition is true then the statement inside the if block is run and if the condition
is false then the statement inside the if block is not run.
In C language, when we write one or more statements by covering them with a curly
bracket {}, then it is called a block.
The condition in parenthesis () of if is checked as true or false. If the condition is true
then it is considered to be a non-zero value and if the condition is false then it is
considered zero.
Syntax -:
if (condition)
{
// Statements to execute if
// condition is true
}
Example
If (5>2) // Here () is called parenthesis in which 5> 2 is an expression or condition.
{
printf ("five is greater than two");
}
Output -:
five is greater than two
If else Statement In C
The if-else statement is an extended form of the If statement. In this, we execute the
statement of the block containing else, if the if condition is false.
The if-else statement is used when we have to perform two operations on the same condition.
Meaning that when we want to run the statement of another block when a condition is true
and the statement of another block should run when the condition is false.
Example -:
Here we will create a program in which we will enter the user’s age and based on the input
entered by the user, we will check whether the user is eligible for voting?
If the user’s age is more than 18, then we will run a statement inside the if block and if the
user is less than 18, then we will run a statement inside the else block.
// c program to check user are eligible or not for voting
#include <stdio.h>
int main ()
{
int age;
printf ("Enter Your Age \n");
scanf ("%d", &age);
if (age>=18)
{
/* The codes in this block will only execute when
The above condition (age> = 18) is true.
*/
In this example, we take input from the user and check whether he is more than 18 years old.
Based on the input given by the user, its output will be something like this.
Output -:
Enter Your Age
21
You are eligible for vote
A nested if-else statement is also similar to an if-else statement, but the slight difference is
that in a nested if-else statement, we use many more if-else statements within the if-else
statement.
When we use an if-else statement or if statement inside an if block or inside an else block
then, it is called a Nested if-else statement.
The nested if-else statement is used when we have a lot of conditions, which we have to
execute a statement only after checking.
Let us understand these things by making a program.
Example -:
Below we are going to create a program in which we will take three numbers of inputs from
the user and based on the input given by that user, we will check which of those numbers is
bigger. We will finally print the value of whatever number will be bigger.
#include <stdio.h>
int main ()
{
int x, y, z;
printf ("Enter three number \n");
scanf ("%d %d %d", &x, &y, &z);
if (y>z)
printf ("Greater value is: %d", y);
else
printf ("Greater value is: %d", z);
}
return 0;
}
Run Code Live
You can run the live demo of this program by clicking on the Run Code Live button above.
In this program, we input three values from the user via scanf (). Then we first checked if x>y
in the parenthesis of if the value of x is greater than y?
There can be two points here, either the value of x will be greater than y or smaller.
If the value of x is larger, then we will enter the inside of the if block and run the statement
inside it, and if the value of x is smaller, then we will enter the inside else block and run the
statement inside it.
Both these things depend on the input given by the user, so let’s see what the output of this
program is.
Output -:
Enter three number
12
6
10
Greater value is: 12
Now let’s know about the else if ladder statement And how it is used.
else if ladder statement in C
When we use an if statement or if-else statement inside an else block then, it is called else if
ladder statement.
else if ladder statement is used when we have many conditions in else statement which we
have to execute a statement only after checking.
Syntax -:
if (condition1)
{
// code to be executed if condition1 is true
}
else if (condition2) {
// code to be executed if condition2 is true
}
else if (condition3) {
// code to be executed if condition3 is true
}
.
.
.
else {
// code to be executed if all the conditions are false
}
Let us understand the else if ladder statement by creating a program
Example -:
Below we are going to create a program in which we will input two values from the user,
then compare the input given by the user to each other.
Are the two values equal?
Which of the two is smaller and which is bigger.
#include <stdio.h>
int main ()
{
int num1, num2;
printf ("Input the value of var1:");
scanf ("%d", &num1);
if (num1 == num2)
{
printf ("num1 is equal to num2 \n");
}
else if (num1>num2)
{
printf ("num1 is greater than num2 \n");
}
else
{
printf ("num2 is greater than num1 \n");
}
return 0;
}
Output -:
Input the value of num1: 10
Input the value of num2: 20
num2 is greater than num1
What is Loop In C
When we want to run a particular part of a program or a block multiple times, then we
use Loop Statements.
Meaning that when we want to run any particular statement of our program repeatedly
till a particular condition is true, then we use Loop Statements.
Let’s understand these things with this one example.
Example -: If we want to print “Welcome To CsTutorialpoint” 10 times, then one way we can
print “Welcome To CsTutorialpoint” by writing 10 printf () in the program. Another way can
be that we use Loop Statements.
If we use the previous method then the program will be something like this:
#include <stdio.h>
Void main ()
{
printf ("Welcome To CsTutorialpoint \n");
printf ("Welcome To CsTutorialpoint \n");
printf ("Welcome To CsTutorialpoint \n");
printf ("Welcome To CsTutorialpoint \n");
printf ("Welcome To CsTutorialpoint \n");
printf ("Welcome To CsTutorialpoint \n");
printf ("Welcome To CsTutorialpoint \n");
printf ("Welcome To CsTutorialpoint \n");
printf ("Welcome To CsTutorialpoint \n");
printf ("Welcome To CsTutorialpoint \n");
Output -:
Welcome To CsTutorialpoint
Welcome To CsTutorialpoint
Welcome To CsTutorialpoint
Welcome To CsTutorialpoint
Welcome To CsTutorialpoint
Welcome To CsTutorialpoint
Welcome To CsTutorialpoint
Welcome To CsTutorialpoint
Welcome To CsTutorialpoint
Welcome To CsTutorialpoint
If we want to print “Welcome To CsTutorialpoint” 10 times using Loop Statements, then for
this we have to write a Loop Statement in which we will give condition and secondly we
have to write a printf () Statement by which we will print “Welcome To CsTutorialpoint”.
#include <stdio.h>
int main ()
{
int i = 1; // initialization expression
Types of Loop in C
In C language, we can use loop in three ways.
1. While loop
2. Do while loop
3. For loop
1. While Loop
While Loop is used when we do not already know how often to run the loop.
In While Loop, we write the condition in parenthesis “()” after the while keyword. If
the condition is true then the control enters the body of the while Loop and runs the
statements inside the while loop.
As the control comes to the end of While Loop, the control again goes to While Loop
and the condition is checked again and if the condition is true this time, then the
statement inside While Loop runs again.
This action continues till the condition of the while Loop does not become False. We
also use the increment (++) and increment (-) operators to change the condition of
while loop.
While Loop is also called the entry control loop because the condition is checked
before the control reaches the block of the while loop, and if the condition is true then
the control enters the body of the while Loop and runs the statement inside it.
While Loop’s syntax is something like this:
Syntax
while (condition)
{
// code to be executed
statements;
statements;
.
.
}
2. Do while loop
Do while loop is used when we want to execute the statement inside the Do while loop block
once.
We finally check the condition in the Do while loop and if the condition is true then the
control again goes to the Do while loop and the statement inside it start executing and if the
condition is False then the control is removed from the do while loop and another statement is
executed.
Syntax -:
Do
{
// code to be executed
statements;
statements;
statements;
.
.
} while (condition);
3. For Loop
For Loop is used when we have to run a particular statement repeatedly until a particular
condition is correct.
In the case of for Loop, we already know how many times the loop will run, so for Loop, is
also called a pre-tested loop or open-ended loop.
In for loop, we write both the initialization and control condition of the variable together
inside the parentheses “()”. If the condition of For Loop is true, then the statement inside it is
run, or else the statement is not run.
Syntax -:
for (initial value; condition; incrementation or decrementation)
{
statements;
}
For Loop in C
For Loop is an entry-controlled loop In which the condition inside For Loop is
checked before executing the statement And if the condition is true only then the
statement inside For Loop is executed or run.
In C language, For Loop is used to execute a particular statement or block repeatedly
until a particular condition is true.
In For Loop, we write both the initialization and control condition of the variable
together inside the parentheses “()”. If the condition of For Loop is true, then the
statement inside it is run or else the statement is not run.
Condition Test: – The condition is written in this section every time we have to run a loop.
The condition can be any Boolean expression. For example: i <= 10;
Once the loop is run, the condition is checked again and if the condition returns true this time,
then the loop runs again and if the condition is false then the control comes out of the loop.
Update Expression -: Here the increment or decrement operator is used to update the
Expression. for example: i ++;
Let’s understand the for loop better by this one example.
// i = 1; Initialization
// i<= 10 Condition Test
// i++ Update Expression
return 0;
}
Run Code
Let’s see how this program will execute?
How Program Work?
1. The first variable will be the declare.
2. The control goes to the for loop and store 1 value in the i variable
3. After that the condition i <= 10 will be checked.
4. The stipulated condition is correct, so the statement inside the for loop will execute
once. Which will print once Hello World on the screen.
5. When the statement of the body of the for loop is executed once, then the control will
go to the Update Expression where the value of i will be incremented due to i ++
being written.
6. After incrementing the value of i, the control will again go to section i <= 10 in the
condition of the for loop and check the condition again.
7. If this time the condition is true, then the statements inside the for loop will be
executed again and the control will again go to Update Express.
8. Where the value of i will be incremented again due to i ++ being written.
9. After that the control will again go to section i <= 10 for the condition of the for loop
and check the condition again.
10. Here the action will continue until the condition with i <= 10 becomes false.
11. When the condition with i <= 10 is checked 11 times, then the condition will be
wrong because by then the value of i will be 11 so the control loop will be out.
12. Before coming out of the control loop, “Hello World” must have been printed 10
times.
The output of this program will be
Output -:
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
update_expression;
}
Test Expression -:
In this expression, we check the condition. If the condition is true then we enter inside the
body of the while loop and execute the statement inside it, and if the condition is false then
we do not enter inside the while loop.
Example -:
include <stdio.h>
#include <conio.h>
int main ()
{
int num = 1; // initializing the variable
while (num<=10) // test_expression
{
printf ("%d \n", num);
num++; // update_expression;
}
return 0;
}
In the example above (num <= 10) there is a test_expression.
Update Expression -:
When we enter inside the body of the while loop, we try to change the condition of the while
loop using the update expression. In Update Expression we use increment or increment
operator with variable.
Example -:
while (num<=10) // test_expression
{
printf ("%d \n", num);
num++; // update_expression;
}
See the example program we created above, in it, we have written num ++, this is an update
expression incrementing the value of num variable.
To understand the while loop more, let us now create a program.
E
xample Program of While Loop
We are going to create a program in which we will print the values from 1 to 10.
#include <stdio.h>
int main ()
{
int i = 1;
while (i<=10)
{
printf ("%d \n", i);
i++;
}
return 0;
}
Run Code
In this program we have int i = 1; I did a variable declare named i and stored 1 in it.
Then we put a condition in the parenthesis of the while loop by i<= 10. Since this condition is
correct, the control enters the body of the while loop and runs the statement inside it.
i++ in the body of the while loop; Is a statement with the help of which we are increasing the
value of the i variable.
Thereby comes a time in which the value of i variable becomes larger than 10 and i<= 10
condition becomes false. The control then exits from the while loop.
The output of this program will be something like
Output -:
1
2
3
4
5
6
7
8
9
10
Now let us know about Do While Loop
Note – After writing While (condition) in Do While loop, it is necessary to apply semicolon
in the end, whereas it was not in the while loop.
The Do While loop is also called the post-tested loop or exit controlled loop because in the
Do While loop, the condition is checked at the end of the block
Let’s understand the Do While loop by making a program and understand it better.
do {
// loop body
printf ("Hello World \n");
return 0;
}
Look at this example program above, in that we first created the i variable and stored 2 values
in it.
Then we created a body of do-while loop inside which we used the printf () function to print
“Hello World”.
After that we have i++; By increasing the value of i, due to which the value of i will increase
to 2.
At the end of the body of the do-while loop, we have written the condition i<= 1, which will
check if the condition is false because the value of the i variable has increased due to which
i<= 1 is not true.
Because of which the condition will be false, the control will come out of the do-while loop.
If you want to try this program by running , then you can try it by clicking on the demo
button below.
Live Demo
The output of this program will be something like this.
Output -:
Hello World
switch (number)
{
case 10:
printf ("number is equals to 10");
break;
case 50:
printf ("number is equal to 50");
break;
case 100:
printf ("number is equal to 100");
break;
default:
printf ("number is not equal to 10, 50 or 100");
}
Run Code Live
Output -:
Enter a number
10
number is equals to 10
Example Program -:
#include <stdio.h>
int main ()
{
int i;
Continue Statement C
Continue Statement is a loop control statement that we use in C language when we
want to run the program from next iteration by skipping a particular line or code when
a particular condition becomes true.
Suppose you are playing a game and in order to cross a level in that game you need
some particular point within a particular time.
If you have achieved that point before time, then the game starts at the next level.
In the same way, when we have some special condition in our program, we want to
start the program with the next iteration, then we have to use the continue statement.
The continue statement is slightly opposite to the break statement. It does not take the
control of the program out of the entire loop, but takes the control of the program to
the beginning of that loop and runs the loop with the next iteration.
The continue statement is mostly used inside a loop statement with an if condition.