Wa0005
Wa0005
UNIT I
SYLLABUS:
Basics of C, I/O, Branching and Loops:
Structure of a C Program – Data types – Keywords - Variables – Type Qualifiers - Constants –
Operators–expressions and precedence- Console I/O– Unformatted and Formatted Console I/O
-Conditional Branching and Loops-Writing and evaluation of conditionals and consequent
branching
NOTES:
1. STRUCTURE OF A C PROGRAM:
The basic structure of a C program is divided into 6 parts which makes it easy to read, modify,
document, and understand in a particular format. C program must follow the below-mentioned
outline in order to successfully compile and execute. Debugging is easier in a well-structured C
program.
1. Documentation
2. Preprocessor Section
3. Definition
4. Global Declaration
5. Main() Function
6. Sub Programs
1. Documentation
This section consists of the description of the program, the name of the program, and the
creation date and time of the program. It is specified at the start of the program in the form of
comments. Documentation can be represented as:
Or
/*
*/
Anything written as comments will be treated as documentation of the program and this will not
interfere with the given code. Basically, it gives an overview to the reader of the program.
2. Preprocessor Section
All the header files of the program will be declared in the preprocessor section of the program.
Header files help us to access other’s improved code into our code. A copy of these multiple
files is inserted into our program before the process of compilation.
Example:
#include<stdio.h>
#include<math.h>
3. Definition
The #define preprocessor is used to create a constant throughout the program. Whenever this
name is encountered by the compiler, it is replaced by the actual piece of defined code.
Example:
4. Global Declaration
The global declaration section contains global variables, function declaration, and static
variables. Variables and functions which are declared in this scope can be used anywhere in the
program.
Example:
5. Main() Function
Every C program must have a main function. The main() function of the program is written in this
section. Operations like declaration and execution are performed inside the curly braces of the
main program. The return type of the main() function can be int as well as void too. void() main
tells the compiler that the program will not return any value. The int main() tells the compiler that
the program will return an integer value.
Example:
void main()
or
int main()
6. Sub Programs
User-defined functions are called in this section of the program. The control of the program is
shifted to the called function whenever they are called from the main or outside the main()
function. These are specified as per the requirements of the programmer.
Example:
return x+y;
// Link
#include <stdio.h>
// Definition
#define X 20
// Global Declaration
int sum(int y);
// Main() Function
int main(void)
{
int y = 55;
printf("Sum: %d", sum(y));
return 0;
}
// Subprogram
int sum(int y)
{
return y + X;
}
Output
Sum: 75
2. DATA TYPES:
Each variable in C has an associated data type. It specifies the type of data that the variable
can store like integer, character, floating, double, etc. Each data type requires different amounts
of memory and has some specific operations which can be performed over it. The data type is a
collection of data with values having fixed values, meaning as well as its characteristics.
Types Description
Primitive data types are the most basic data types that are used for
PrimitiveData representing simple values such as integers, float, characters, etc.
Types
User Defined The user-defined data types are defined by the user himself.
Data Types
Derived Types The data types that are derived from the primitive or built-in datatypes are
referred to as Derived Data Types.
DATA RANGE:
Different data types also have different ranges up to which they can store numbers. These
ranges may vary from compiler to compiler. Below is a list of ranges along with the memory
requirement and format specifiers on the 32-bit GCC compiler.
Note: The long, short, signed and unsigned are datatype modifier that can be
used with some primitive data types to change the size or length of the datatype.
Syntax of Integer
int var_name;
1. unsigned int: Unsigned int data type in C is used to store the data values from zero to
positive numbers but it can’t store negative values like signed int.
2. short int: It is lesser in size than the int by 2 bytes so can only store values from -32,768
to 32,767.
3. long int: Larger version of the int datatype so can store values greater than int.
4. unsigned short int: Similar in relationship with short int as unsigned int with int.
Note: The size of an integer data type is compiler-dependent. We can use sizeof
operator to check the actual size of any data type.
Example of int
// C program to print Integer data types.
#include <stdio.h>
int main()
{
// Integer value with positive data.
int a = 9;
return 0;
}
Output
Syntax of char
char var_name;
Example of char
// C program to print Integer data types.
#include <stdio.h>
int main()
{
char a = 'a';
char c;
a++;
printf("Value of a after increment is:
%c\n", a);
return 0;
}
Output
Value of a: a
Value of c: c
Syntax of float
float var_name;
Example of Float
// C Program to demonstrate use
// of Floating types
#include <stdio.h>
int main()
float a = 9.0f;
float b = 2.5f;
// 2x10^-4
float c = 2E-4f;
printf("%f\n", a);
printf("%f\n", b);
printf("%f", c);
return 0;
Output
9.000000
2.500000
0.000200
Syntax of Double
The variable can be declared as double precision floating point using the double keyword:
double var_name;
Example of Double
// C Program to
demonstrate
int main()
{
double a =
123123123.00;
double b = 12.293123;
double c =
2312312312.123123;
printf("%lf\n", a);
printf("%lf\n", b);
printf("%lf", c);
return 0;
}
Output
123123123.000000
12.293123
2312312312.123123
Syntax:
// function return type void
int print(void);
Example of Void
// C program to
demonstrate
// use of void
pointers
#include <stdio.h>
int main()
{
int val = 30;
void* ptr = &val;
printf("%d",
*(int*)ptr);
return 0;
}
Output
30
Example
// C Program to print size of
int main()
{
int size_of_int = sizeof(int);
int size_of_char = sizeof(char);
int size_of_float = sizeof(float);
int size_of_double = sizeof(double);
return 0;
}
Output
3. KEYWORDS
auto
auto is the default storage class variable that is declared inside a function or a block. auto
variables can only be accessed within the function/block they are declared. By default, auto
variables have garbage values assigned to them. Automatic variables are also called local
variables as they are local to a function.
Here num is the variable of the storage class auto and its type is int. Below is the C program to
demonstrate the auto keyword:
// C program to
demonstrate
// auto keyword
#include <stdio.h>
int printvalue()
{
auto int a = 10;
printf("%d", a);
}
// Driver code
int main()
{
printvalue();
return 0;
}
Output
10
break and continue
The break statement is used to terminate the innermost loop. It generally terminates a loop or a
switch statement. The switch statement skips to the next iteration of the loop. Below is the C
program to demonstrate break and continue in C:
// C program to show
use
// of break and
continue
#include <stdio.h>
// Driver code
int main()
{
for (int i = 1; i <=
10; i++)
{
if (i == 2)
{
continue;
}
if (i == 6)
{
break;
}
printf("%d ", i);
}
return 0;
}
Output
1345
switch, case, and default
The switch statement in C is used as an alternate to the if-else ladder statement. For a single
variable i.e, switch variable it allows us to execute multiple operations for different possible
values of a single variable.
switch(Expression)
break;
case:'2': // operation 2
break;
// C program to
demonstrate
// Driver code
int main() {
int i = 4;
switch (i) {
case 1:
printf("Case
1\n");break;
case 2:
printf("Case
2\n");break;
case 3:
printf("Case
3\n");break;
case 4:
printf("Case
4\n");break;
default:
printf("Default\n");break
;
}
}
Output
Case 4
Note: it is best to add a break statement after every case so that switch statement doesn’t
continue checking the remaining cases.
Output
Case 4
Default
char
char keyword in C is used to declare a character variable in the C programming language.
char x = 'D';
// char keyword
#include <stdio.h>
// Driver code
int main() {
char c = 'a';
printf("%c", c);
return 0;
}
Output
const
The const keyword defines a variable who’s value cannot be changed.
// C program to
demonstrate
// const keyword
#include <stdio.h>
// Driver code
int main() {
const int a = 11;
a = a + 2;
printf("%d", a);
return 0;
}
This code will produce an error because the integer a was defined as a constant and it’s value
was later on changed.
Output:
a = a + 2;
do
The do statement is used to declare a do-while loop. A do-while loop is a loop that executes
once, and then checks it’s condition to see if it should continue through the loop. After the first
iteration, it will continue to execute the code while the condition is true.
// C program to
demonstrate
// do-while keyword
#include <stdio.h>
// Driver code
int main()
{
int i = 1;
do {
printf("%d ", i);
i++;
} while(i <= 5);
return 0;
}
Output
12345
Example:
double num;
// C program to
demonstrate
// Driver code
int main() {
float f = 0.3;
double d = 10.67;
printf("Float value:
%f\n", f);
printf("Double value:
%f\n", d);
return 0;
}
Output
if-else
The if-else statement is used to make decisions, where if a condition is true, then it will execute
a block of code; if it isn’t true (else), then it will execute a different block of code.
if(marks == 97) {
// if marks are 97 then will execute this block of code
else {
// C program to
demonstrate
// if-else keyword
#include <stdio.h>
// Driver code
int main()
{
int a = 10;
if(a < 11)
{
printf("A is less
than 11");
}
else
{
printf("A is equal to
or "
"greater than
11");
}
return 0;
}
Output
A is less than 11
enum
The enum keyword is used to declare an enum (short for enumeration). An enum is a
user-defined datatype, which holds a list of user-defined integer constants. By default, the value
of each constant is it’s index (starting at zero), though this can be changed. You can declare an
object of an enum and can set it’s value to one of the constants you declared before. Here is an
example of how an enum might be used:
// An example program to
// demonstrate working of
// enum in C
#include<stdio.h>
// enum declaration:
enum week{Mon, Tue, Wed, Thur, Fri,
Sat, Sun};
// Driver code
int main()
{
//object of the enum (week), called
day
enum week day;
day = Wed;
printf("%d", day);
return 0;
}
Output
extern
The extern keyword is used to declare a variable or a function that has an external linkage
outside of the file declaration.
#include
<stdio.h>
extern int a;
int main(){
printf("%d",
a);
return 0;
}
for
The “for” keyword is used to declare a for-loop. A for-loop is a loop that is specified to run a
certain amount of times.
// C program to
demonstrate
// for keyword
#include <stdio.h>
// Driver code
int main()
{
for (int i = 0; i <
5; i++)
{
printf("%d ", i);
}
return 0;
}
Output
01234
goto
The goto statement is used to transfer the control of the program to the given label. It is used to
jump from anywhere to anywhere within a function.
Example:
goto label;
// code
label:
// C program
demonstrate
// goto keyword
#include <stdio.h>
// Function to print
numbers
// from 1 to 10
void printNumbers() {
int n = 1;
label:
printf("%d ", n);
n++;
if (n <= 10) goto
label;
}
// Driver code
int main(){
printNumbers();
return 0;
}
Output
1 2 3 4 5 6 7 8 9 10
int
int keyword is used in a type declaration to give a variable an integer type. In C, the integer
variable must have a range of at least -32768 to +32767.
Example:
int x = 10;
// C program to
demonstrate
// int keyword
#include <stdio.h>
void sum() {
int a = 10, b =
20;
int sum;
sum = a + b;
printf("%d",
sum);
}
// Driver code
int main() {
sum();
return 0;
}
Output
30
Below is the C program to demonstrate the short, long, signed, and unsigned keywords:
// C program to demonstrate
// Driver code
int main() {
// short integer
short int a = 12345;
// signed integer
signed int b = -34;
// unsigned integer
unsigned int c = 12;
// L or l is used for
// long int in C.
long int d = 99998L;
Example:
return x;
// C program to
demonstrate
// return keyword
#include <stdio.h>
int sum(int x, int y)
{
int sum;
sum = x + y;
return sum;
}
// Driver code
int main() {
int num1 = 10;
int num2 = 20;
printf("Sum: %d",
sum(num1,
num2));
return 0;
}
Output
Sum: 30
sizeof
sizeof is a keyword that gets the size of an expression, (variables, arrays, pointers, etc.) in
bytes.
Example:
sizeof(char);
sizeof(int);
sizeof(float); in bytes.
// C program to
demonsstrate
// sizeof keyword
#include <stdio.h>
// Driver code
int main() {
int x = 10;
printf("%d",
sizeof(x));
return 0;
}
Output
register
Register variables tell the compiler to store variables in the CPU register instead of memory.
Frequently used variables are kept in the CPU registers for faster access.
Example:
static
The static keyword is used to create static variables. A static variable is not limited by a scope
and can be used throughout the program. It’s value is preserved even after it’s scope.
For Example:
struct
The struct keyword in C programming language is used to declare a structure. A structure is a
list of variables, (they can be of different data types), which are grouped together under one
data type.
For Example:
struct Geek {
char name[50];
int num;
double var;
};
// struct keyword
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
};
// Driver code
int main( ) {
// Declare Book1 of type Book
struct Books book1;
// book 1 specification
strcpy(book1.title, "C++
Programming");
strcpy(book1.author, "Bjarne
Stroustrup");
typedef
The typedef keyword in C programming language is used to define a data type with a new name
in the program. typedef keyword is used to make our code more readable.
For Example:
union
The union is a user-defined data type. All data members which are declared under the union
keyword share the same memory location.
Example:
union GeekforGeeks {
int x;
char s;
} obj;
#include <stdio.h>
union student {
int age;
char marks;
} s;
// Driver code
int main() {
s.age = 15;
s.marks = 56;
printf("age = %d",
s.age);
printf("\nmarks = %d",
s.marks);
}
Output
age = 56
marks = 56
void
The void keyword means nothing i.e, NULL value. When the function return type is used as the
void, the keyword void specifies that it has no return value.
Example:
void fun() {
// program
volatile
The volatile keyword is used to create volatile objects. Objects which are declared volatile are
omitted from optimization as their values can be changed by code outside the scope of the
current code at any point in time.
For Example:
marks are declared constant so they can’t be changed by the program. But hardware can
change it as they are volatile objects.
4. VARIABLES:
What is a variable in C?
A variable in C is a memory location with some name that helps store some form
of data and retrieves it when required. We can store different types of data in the
variable and reuse the same variable for storing some other data any number of
times.
They can be viewed as the names given to the memory location so that we can refer to it
without having to memorize the memory address. The size of the variable depends upon the
data type it stores.
C Variable Syntax
The syntax to declare a variable in C specifies the name and the type of the variable.
or
Here,
Example
Note: C is a strongly typed language so all the variables types must be specified
before using them.
1. Variable Declaration
2. Variable Definition
3. Variable Initialization
1. C Variable Declaration
Variable declaration in C tells the compiler about the existence of the variable with the given
name and data type.When the variable is declared compiler automatically allocates the memory
for it.
2. C Variable Definition
In the definition of a C variable, the compiler allocates some memory and some value to it. A
defined variable will contain some random garbage value till it is not initialized.
Example
int var;
char var2;
Note: Most of the modern C compilers declare and define the variable in single step.
3. C Variable Initialization
Initialization of a variable is the process where the user assigns some meaningful value to the
variable.
Example
or
int main()
{
// declaration with definition
int defined_var;
// initialization
defined_var = 12;
return 0;
}
Output
Defined_var: 0
Value of ini_var: 25
C Variable Types
The C variables can be classified into the following types:
1. Local Variables
2. Global Variables
3. Static Variables
4. Automatic Variables
5. Extern Variables
6. Register Variables
1. Local Variables in C
A Local variable in C is a variable that is declared inside a function or a block of code. Its
scope is limited to the block or function in which it is declared.
// function.
#include <stdio.h>
void function()
{
int x = 10; // local variable
printf("%d", x);
}
Output
10
In the above code, x can be used only in the scope of function(). Using it in the main function
will give an error.
2. Global Variables in C
A Global variable in C is a variable that is declared outside the function or a block of code. Its
scope is the whole program i.e. we can access the global variable anywhere in the C program
after it is declared.
#include <stdio.h>
int main()
{
function1();
function2();
return 0;
}
Output
Function 1: 20
Function 2: 20
In the above code, both functions can use the global variable as global variables are accessible
by all the functions.
Note: When we have same name for local and global variable, local variable will be
given preference over the global variable by the compiler.
For accessing global variable in this case, we can use the method mention here.
3. Static Variables in C
A static variable in C is a variable that is defined using the static keyword. It can be defined
only once in a C program and its scope depends upon the region where it is declared (can be
global or local).
As its lifetime is till the end of the program, it can retain its value for multiple function calls as
shown in the example.
#include <stdio.h>
void function()
{
int x = 20; // local variable
static int y = 30; // static
variable
x = x + 10;
y = y + 10;
printf("\tLocal: %d\n\tStatic:
%d\n", x, y);
}
int main()
{
printf("First Call\n");
function();
printf("Second Call\n");
function();
printf("Third Call\n");
function();
return 0;
}
Output
First Call
Local: 30
Static: 40
Second Call
Local: 30
Static: 50
Third Call
Local: 30
Static: 60
In the above example, we can see that the local variable will always print the same value
whenever the function will be called whereas the static variable will print the incremented value
in each function call.
Note: Storage Classes in C is the concept that helps us to determine the scope,
lifetime, memory location, and default value (initial value) of a variable.
4. Automatic Variable in C
All the local variables are automatic variables by default. They are also known as auto
variables.
Their scope is local and their lifetime is till the end of the block. If we need, we can use the
auto keyword to define the auto variables.
or
#include <stdio.h>
void function()
{
int x = 10; // local variable (also
automatic)
auto int y = 20; // automatic variable
printf("Auto Variable: %d", y);
}
int main()
{
function();
return 0;
}
Output
Auto Variable: 20
In the above example, both x and y are automatic variables. The only difference is that variable
y is explicitly declared with the auto keyword.
5. External Variables in C
External variables in C can be shared between multiple C files. We can declare an external
variable using the extern keyword.
----------myfile.h------------
----------program1.c----------
#include "myfile.h"
#include <stdio.h>
void printValue(){
6. Register Variables in C
Register variables in C are those variables that are stored in the CPU register instead of the
conventional storage place like RAM. Their scope is local and exists till the end of the block or
a function.
// variable
#include <stdio.h>
int main()
{
// register variable
register int var = 22;
Output
NOTE: We cannot get the address of the register variable using addressof (&)
operator because they are stored in the CPU register. The compiler will throw an
error if we try to get the address of register variable.
Constant Variable in C
Till now we have only seen the variables whose values can be modified any number of times.
But C language also provides us a way to make the value of a variable immutable. We can do
that by defining the variable as constant.
Note: We have to always initialize the const variable at the definition as we cannot
modify its value after defining.
// C Program to Demonstrate
constant variable
#include <stdio.h>
int main()
{
// variable
int not_constant;
// constant variable;
const int constant = 20;
// changing values
not_constant = 40;
constant = 22;
return 0;
}
Output
5. TYPE QUALIFIERS
Type qualifiers add special attributes to existing data types in C programming
language.
There are three type qualifiers in C language and volatile and restrict type
qualifiers are explained below −
Volatile
A volatile type qualifier is used to tell the compiler that a variable is shared.
That is, a variable may be referenced and changed by other programs (or)
entities if it is declared as volatile.
Restrict
This is used only with pointers. It indicates that the pointer is only an initial way
to access the deference data. It provides more help to the compiler for
optimization.
Example Program
int *ptr
int a= 0;
ptr = &a;
____
____
____
*ptr+=4; // Cannot be replaced with *ptr+=9
____
____
____
*ptr+=5;
Here, the compiler cannot replace the two statements *ptr+=4 and *ptr+=5 by
one statement *ptr+=9. Because, it is not clear if the variable ‘a’ can be
accessed directly (or) through other pointers.
For example,
Here, the compiler can replace the two statements by one statement, *ptr+=9.
Because, it is sure that variable cannot be accessed through any other
resources.
Example
Following is the C program for the use of restrict keyword −
Live Demo
#include<stdio.h>
void keyword(int* a, int* b, int* restrict c){
*a += *c;
// Since c is restrict, compiler will
// not reload value at address c in
// its assembly code.
*b += *c;
}
int main(void){
int p = 10, q = 20,r=30;
keyword(&p, &q,&r);
printf("%d %d %d", p, q,r);
return 0;
}
Output
When the above program is executed, it produces the following result −
40 50 30
6. CONSTANTS
What is a constant in C?
As the name suggests, a constant in C is a variable that cannot be modified once
it is declared in the program. We can not make any change in the value of the
constant variables after they are defined.
int main()
{
return 0;
}
Output
Printing value of Integer Constant: 25
Printing value of Character Constant: A
Printing value of Float Constant: 15.660000
One thing to note here is that we have to initialize the constant variables at
declaration. Otherwise, the variable will store some garbage value and we
won’t be able to change it. The following image describes examples of incorrect
and correct variable definitions.
Types of Constants in C
The type of the constant is the same as the data type of the variables. Following
is the list of the types of constants
● Integer Constant
● Character Constant
● Structure Constant
We just have to add the const keyword at the start of the variable declaration.
Properties of Constant in C
The important properties of constant variables in C defined using the const
keyword are as follows:
We can only initialize the constant variable in C at the time of its declaration.
Otherwise, it will store the garbage value.
2. Immutability
The constant variables in c are immutable after its definition, i.e., they can be
initialized only once in the whole program. After that, we cannot modify the
value stored inside that variable.
int main()
{
// declaring a constant variable
const int var;
// initializing constant variable var after declaration
var = 20;
Output
In function 'main':
10:9: error: assignment of read-only variable 'var'
10 | var = 20;
| ^
Constant Literals
Constants are variables that cannot be Literals are the fixed values that
modified once declared. define themselves.
Constants are defined by using the They themselves are the values
const keyword in C. They store literal that are assigned to the variables
values in themselves. or constants.
0 seconds of 15 secondsVolume 0%
This ad will end in 13
Example
int main()
{
Output
The value of pi: 3.14
7. OPERATORS:
What is a constant in C?
As the name suggests, a constant in C is a variable that cannot be modified once
it is declared in the program. We can not make any change in the value of the
constant variables after they are defined.
Example of Constants in C
// C program to illustrate constant variable definition
#include <stdio.h>
int main()
{
return 0;
}
Output
Printing value of Integer Constant: 25
Printing value of Character Constant: A
Printing value of Float Constant: 15.660000
One thing to note here is that we have to initialize the constant variables at
declaration. Otherwise, the variable will store some garbage value and we
won’t be able to change it. The following image describes examples of incorrect
and correct variable definitions.
Types of Constants in C
The type of the constant is the same as the data type of the variables. Following
is the list of the types of constants
● Integer Constant
● Character Constant
● Array Constant
● Structure Constant
We just have to add the const keyword at the start of the variable declaration.
Properties of Constant in C
The important properties of constant variables in C defined using the const
keyword are as follows:
We can only initialize the constant variable in C at the time of its declaration.
Otherwise, it will store the garbage value.
2. Immutability
The constant variables in c are immutable after its definition, i.e., they can be
initialized only once in the whole program. After that, we cannot modify the
value stored inside that variable.
int main()
{
// declaring a constant variable
const int var;
// initializing constant variable var after declaration
var = 20;
Output
In function 'main':
10:9: error: assignment of read-only variable 'var'
10 | var = 20;
| ^
Difference between Constants and Literals
The constant and literals are often confused as the same. But in C language,
they are different entities and have different semantics. The following table list
the differences between the constants and literals in C:
Constant Literals
Constants are variables that cannot be Literals are the fixed values that
modified once declared. define themselves.
Constants are defined by using the They themselves are the values
const keyword in C. They store literal that are assigned to the variables
values in themselves. or constants.
0 seconds of 15 secondsVolume 0%
This ad will end in 13
Example
int main()
{
Output
The value of pi: 3.14
8. OPERATORS
Here, ‘+’ is the operator known as the addition operator, and ‘a’ and ‘b’ are
operands. The addition operator tells the compiler to add both of the operands
‘a’ and ‘b’. The functionality of the C programming language is incomplete
without the use of operators.
Types of Operators in C
C has many built-in operators and can be classified into 6 types:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Other Operators
The above operators have been discussed in detail:
1. Arithmetic Operations in C
These operators are used to perform arithmetic/mathematical operations on
operands. Examples: (+, -, *, /, %,++,–). Arithmetic operators are of two types:
a) Unary Operators:
Operators that operate or work with a single operand are unary operators. For
example: Increment(++) and Decrement(–) Operators
int val = 5;
cout<<++val; // 6
b) Binary Operators:
Operators that operate or work with two operands are binary operators. For
example: Addition(+), Subtraction(-), multiplication(*), Division(/) operators
int a = 7;
int b = 2;
cout<<a+b; // 9
2. Relational Operators in C
These are used for the comparison of the values of two operands. For example,
checking if one operand is equal to the other operand or not, whether an
operand is greater than the other operand or not, etc. Some of the relational
operators are (==, >= , <= )(See this article for more reference).
int a = 3;
int b = 5;
cout<<(a < b);
// operator to check if a is smaller than b
3. Logical Operator in C
Logical Operators are used to combining two or more conditions/constraints or
to complement the evaluation of the original condition in consideration. The
result of the operation of a logical operator is a Boolean value either true or
false.
For example, the logical AND represented as the ‘&&’ operator in C returns
true when both the conditions under consideration are satisfied. Otherwise, it
returns false. Therefore, a && b returns true when both a and b are true (i.e.
non-zero)(See this article for more reference).
cout<<((4 != 5) && (4 < 5)); // true
4. Bitwise Operators in C
The Bitwise operators are used to perform bit-level operations on the operands.
The operators are first converted to bit-level and then the calculation is
performed on the operands. Mathematical operations such as addition,
subtraction, multiplication, etc. can be performed at the bit level for faster
processing. For example, the bitwise AND operator represented as ‘&’ in C
takes two numbers as operands and does AND on every bit of two numbers.
The result of AND is 1 only if both bits are 1(True).
int a = 5, b = 9; // a = 5(00000101), b = 9(00001001)
cout << (a ^ b); // 00001100
cout <<(~a); // 11111010
5. Assignment Operators in C
Assignment operators are used to assign value to a variable. The left side
operand of the assignment operator is a variable and the right side operand of
the assignment operator is a value. The value on the right side must be of the
same data type as the variable on the left side otherwise the compiler will raise
an error.
a) “=”
This is the simplest assignment operator. This operator is used to assign the
value on the right to the variable on the left.
Example:
a = 10;
b = 20;
ch = 'y';
b) “+=”
This operator is the combination of the ‘+’ and ‘=’ operators. This operator first
adds the current value of the variable on left to the value on the right and then
assigns the result to the variable on the left.
Example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.
c) “-=”
This operator is a combination of ‘-‘ and ‘=’ operators. This operator first
subtracts the value on the right from the current value of the variable on left and
then assigns the result to the variable on the left.
Example:
(a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.
d) “*=”
This operator is a combination of the ‘*’ and ‘=’ operators. This operator first
multiplies the current value of the variable on left to the value on the right and
then assigns the result to the variable on the left.
Example:
(a *= b) can be written as (a = a * b)
If initially, the value stored in a is 5. Then (a *= 6) = 30.
e) “/=”
This operator is a combination of the ‘/’ and ‘=’ operators. This operator first
divides the current value of the variable on left by the value on the right and
then assigns the result to the variable on the left.
Example:
(a /= b) can be written as (a = a / b)
If initially, the value stored in a is 6. Then (a /= 2) = 3.
6. Other Operators
Apart from the above operators, there are some other operators available in C
used to perform some specific tasks. Some of them are discussed here:
i. sizeof operator
denoted by size_t.
● Basically, the sizeof the operator is used to compute the size of the
variable.
that evaluates its first operand and discards the result, it then
evaluates the second operand and returns this value (and type).
Expression3
operators.
to know more about dot operators refer to this article and to know more about
arrow(->) operators refer to this article.
v. Cast Operator
into another.
// Operators
#include <stdio.h>
int main()
int a = 10, b = 5;
// Arithmetic operators
// by 1
printf(
// Logical operators
(!(a == b)));
return 0;
Output
Following are the Arithmetic operators in C
The value of a + b is 15
The value of a - b is 5
The value of a * b is 50
The value of a / b is 2
The value of a % b is 0
The value of a++ is 10
The value of a-- is 11
The value of ++a is 11
The value of --a is 10
Precedence of Operators in C
The below table describes the precedence order and associativity of operators in
C. The precedence of the operator decreases from top to bottom.
Postfix increment/decrement
a++/a– left-to-right
(a is a variable)
Prefix increment/decrement (a
++a/–a right-to-left
is a variable)
2
Logical negation/bitwise
!~ right-to-left
complement
Multiplication/division/modulu
3 *,/,% left-to-right
s
Relational greater
> , >= left-to-right
than/greater than or equal to
12 || Logical OR left-to-right
= Assignment right-to-left
Addition/subtraction
+= , -= right-to-left
assignment
14
Multiplication/division
*= , /= right-to-left
assignment
Modulus/bitwise AND
%= , &= right-to-left
assignment
Bitwise exclusive/inclusive OR
^= , |= right-to-left
assignment
Conclusion
In this article, the points we learned about the operator are as follows:
C.
conditional, or logical.
● There are seven types of Unary operators, Arithmetic operator,
● ‘=’ and ‘==’ are not same as ‘=’ assigns the value whereas ‘==’ checks if
1. Arithmetic Operations in C
These operators are used to perform arithmetic/mathematical operations on
operands. Examples: (+, -, *, /, %,++,–). Arithmetic operators are of two types:
a) Unary Operators:
Operators that operate or work with a single operand are unary operators. For
example: Increment(++) and Decrement(–) Operators
int val = 5;
cout<<++val; // 6
b) Binary Operators:
Operators that operate or work with two operands are binary operators. For
example: Addition(+), Subtraction(-), multiplication(*), Division(/) operators
int a = 7;
int b = 2;
cout<<a+b; // 9
2. Relational Operators in C
These are used for the comparison of the values of two operands. For example,
checking if one operand is equal to the other operand or not, whether an
operand is greater than the other operand or not, etc. Some of the relational
operators are (==, >= , <= )(See this article for more reference).
int a = 3;
int b = 5;
cout<<(a < b);
// operator to check if a is smaller than b
3. Logical Operator in C
Logical Operators are used to combining two or more conditions/constraints or
to complement the evaluation of the original condition in consideration. The
result of the operation of a logical operator is a Boolean value either true or
false.
For example, the logical AND represented as the ‘&&’ operator in C returns
true when both the conditions under consideration are satisfied. Otherwise, it
returns false. Therefore, a && b returns true when both a and b are true (i.e.
non-zero)(See this article for more reference).
cout<<((4 != 5) && (4 < 5)); // true
4. Bitwise Operators in C
The Bitwise operators are used to perform bit-level operations on the operands.
The operators are first converted to bit-level and then the calculation is
performed on the operands. Mathematical operations such as addition,
subtraction, multiplication, etc. can be performed at the bit level for faster
processing. For example, the bitwise AND operator represented as ‘&’ in C
takes two numbers as operands and does AND on every bit of two numbers.
The result of AND is 1 only if both bits are 1(True).
int a = 5, b = 9; // a = 5(00000101), b = 9(00001001)
cout << (a ^ b); // 00001100
cout <<(~a); // 11111010
5. Assignment Operators in C
Assignment operators are used to assign value to a variable. The left side
operand of the assignment operator is a variable and the right side operand of
the assignment operator is a value. The value on the right side must be of the
same data type as the variable on the left side otherwise the compiler will raise
an error.
a) “=”
This is the simplest assignment operator. This operator is used to assign the
value on the right to the variable on the left.
Example:
a = 10;
b = 20;
ch = 'y';
b) “+=”
This operator is the combination of the ‘+’ and ‘=’ operators. This operator first
adds the current value of the variable on left to the value on the right and then
assigns the result to the variable on the left.
Example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.
c) “-=”
This operator is a combination of ‘-‘ and ‘=’ operators. This operator first
subtracts the value on the right from the current value of the variable on left and
then assigns the result to the variable on the left.
Example:
(a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.
d) “*=”
This operator is a combination of the ‘*’ and ‘=’ operators. This operator first
multiplies the current value of the variable on left to the value on the right and
then assigns the result to the variable on the left.
Example:
(a *= b) can be written as (a = a * b)
If initially, the value stored in a is 5. Then (a *= 6) = 30.
e) “/=”
This operator is a combination of the ‘/’ and ‘=’ operators. This operator first
divides the current value of the variable on left by the value on the right and
then assigns the result to the variable on the left.
Example:
(a /= b) can be written as (a = a / b)
If initially, the value stored in a is 6. Then (a /= 2) = 3.
6. Other Operators
Apart from the above operators, there are some other operators available in C
used to perform some specific tasks. Some of them are discussed here:
i. sizeof operator
denoted by size_t.
● Basically, the sizeof the operator is used to compute the size of the
variable.
that evaluates its first operand and discards the result, it then
evaluates the second operand and returns this value (and type).
Expression3
operators.
to know more about dot operators refer to this article and to know more about
arrow(->) operators refer to this article.
v. Cast Operator
into another.
● Pointer operator & returns the address of a variable. For example &a;
int main()
{
int a = 10, b = 5;
// Arithmetic operators
printf("Following are the Arithmetic operators in C\n");
printf("The value of a + b is %d\n", a + b);
printf("The value of a - b is %d\n", a - b);
// Comparison operators
// Output of all these comparison operators will be (1)
// if it is true and (0) if it is false
printf(
"\nFollowing are the comparison operators in C\n");
printf("The value of a == b is %d\n", (a == b));
printf("The value of a != b is %d\n", (a != b));
printf("The value of a >= b is %d\n", (a >= b));
printf("The value of a <= b is %d\n", (a <= b));
printf("The value of a > b is %d\n", (a > b));
printf("The value of a < b is %d\n", (a < b));
// Logical operators
printf("\nFollowing are the logical operators in C\n");
printf("The value of this logical and operator ((a==b) "
((a == b) && (a < b)));
printf("The value of this logical or operator ((a==b) "
"|| (a<b)) is:%d\n",
((a == b) || (a < b)));
printf("The value of this logical not operator "
"(!(a==b)) is:%d\n",
(!(a == b)));
return 0;
}
Output
Following are the Arithmetic operators in C
The value of a + b is 15
The value of a - b is 5
The value of a * b is 50
The value of a / b is 2
The value of a % b is 0
The value of a++ is 10
The value of a-- is 11
The value of ++a is 11
The value of --a is 10
Precedence of Operators in C
The below table describes the precedence order and associativity of operators in
C. The precedence of the operator decreases from top to bottom.
Precedence Operator Description Associativity
Postfix increment/decrement
a++/a– left-to-right
(a is a variable)
Prefix increment/decrement (a
++a/–a right-to-left
is a variable)
Logical negation/bitwise
!~ right-to-left
complement
2
Cast (convert value to
(type) right-to-left
temporary value of type)
* Dereference right-to-left
Multiplication/division/modulu
3 *,/,% left-to-right
s
Relational greater
> , >= left-to-right
than/greater than or equal to
Relational is equal to/is not
7 == , != left-to-right
equal to
12 || Logical OR left-to-right
Addition/subtraction
+= , -= right-to-left
assignment
Multiplication/division
*= , /= right-to-left
assignment
14
Modulus/bitwise AND
%= , &= right-to-left
assignment
Bitwise exclusive/inclusive OR
^= , |= right-to-left
assignment
Conclusion
In this article, the points we learned about the operator are as follows:
C.
conditional, or logical.
● ‘=’ and ‘==’ are not same as ‘=’ assigns the value whereas ‘==’ checks if
Types of Expressions:
Examples:
5, 10 + 5 / 6.0, 'x’
integer results after implementing all the automatic and explicit type
conversions.
Examples:
x, x * y, x + int( 5.0)
point results after implementing all the automatic and explicit type
conversions.
Examples:
x + y, 10.75
first and then the results compared. Relational expressions are also
Examples:
x <= y, x + y > 2
Examples:
x > y && x == 10, x == 10 || y == 5
Examples:
&x, ptr, ptr++
at bit level. They are basically used for testing or shifting bits.
Examples:
x << 3
Shift operators are often used for multiplication and division by powers
of two.
Note: An expression may also use combinations of the above expressions. Such
expressions are known as compound expressions.
10.FORMATTED AND UNFORMATTED INPUT AND OUTPUT FUNCTIONS IN C
Formatted I/O functions are used to take various inputs from the user and display
multiple outputs to the user. These types of I/O functions can help to display the
output to the user in different formats using the format specifiers. These I/O
supports all data types like int, float, char, and many more.
These functions are called formatted I/O functions because we can use format
specifiers in these functions and hence, we can format these functions according
to our needs.
int/signed
1 %d used for I/O signed integer value
int
unsigned
7 %i used for the I/O integer value
int
1. printf()
2. scanf()
3. sprintf()
4. sscanf()
printf():
printf() function is used in a C program to display any value like float, integer,
character, string, etc on the console screen. It is a pre-defined function that is
already declared in the stdio.h(header file).
Syntax 1:
Example:
// C program to implement
// printf() function
#include <stdio.h>
// Driver code
int main()
{
// Declaring an int type variable
int a;
return 0;
}
Output
20
Syntax 2:
To display any string or a message
printf(“Enter the text which you want to display”);
Example:
C
// C program to implement
// printf() function
#include <stdio.h>
// Driver code
int main()
{
// Displays the string written
// inside the double quotes
printf("This is a string");
return 0;
}
Output
This is a string
scanf():
scanf() function is used in the C program for reading or taking any value from the
keyboard by the user, these values can be of any data type like integer, float,
character, string, and many more. This function is declared in stdio.h(header file),
that’s why it is also a pre-defined function. In scanf() function we use
&(address-of operator) which is used to store the variable value on the memory
location of that variable.
Syntax:
Example:
C
// C program to implement
// scanf() function
#include <stdio.h>
// Driver code
int main()
{
int num1;
// Printing a message on
// the output screen
printf("Enter a integer number: ");
return 0;
}
Output
Output:
sprintf():
sprintf stands for “string print”. This function is similar to printf() function but this
function prints the string into a character array instead of printing it on the
console screen.
Syntax:
sprintf(array_name, “format specifier”, variable_name);
Example:
// C program to implement
// the sprintf() function
#include <stdio.h>
// Driver code
int main()
{
char str[50];
int a = 2, b = 8;
Output
sscanf():
sscanf stands for “string scanf”. This function is similar to scanf() function but
this function reads data from the string or character array instead of the console
screen.
Syntax:
Example:
// C program to implement
// sscanf() function
#include <stdio.h>
// Driver code
int main()
{
char str[50];
int a = 2, b = 8, c, d;
Output
c = 2 and d = 8
Unformatted I/O functions are used only for character data type or character
array/string and cannot be used for any other datatype. These functions are used
to read single input from the user at the console and it allows to display the value
at the console.
These functions are called unformatted I/O functions because we cannot use
format specifiers in these functions and hence, cannot format these functions
according to our needs.
1. getch()
2. getche()
3. getchar()
4. putchar()
5. gets()
6. puts()
7. putch()
getch():
getch() function reads a single character from the keyboard by the user but
doesn’t display that character on the console screen and immediately returned
without pressing enter key. This function is declared in conio.h(header file).
getch() is also used for hold the screen.
Syntax:
getch();
or
variable-name = getch();
Example:
// C program to implement
// getch() function
#include <conio.h>
#include <stdio.h>
// Driver code
int main()
{
printf("Enter any character: ");
return 0;
Output:
getche():
getche() function reads a single character from the keyboard by the user and
displays it on the console screen and immediately returns without pressing the
enter key. This function is declared in conio.h(header file).
Syntax:
getche();
or
variable_name = getche();
Example:
// C program to implement
// the getche() function
#include <conio.h>
#include <stdio.h>
// Driver code
int main()
{
printf("Enter any character: ");
Output:
getchar():
The getchar() function is used to read only a first single character from the
keyboard whether multiple characters is typed by the user and this function reads
one character at one time until and unless the enter key is pressed. This function
is declared in stdio.h(header file)
Syntax:
Variable-name = getchar();
Example:
// C program to implement
#include <conio.h>
#include <stdio.h>
// Driver code
int main()
char ch;
printf("%c", ch);
return 0;
Output:
putchar():
The putchar() function is used to display a single character at a time by passing
that character directly to it or by passing a variable that has already stored a
character. This function is declared in stdio.h(header file)
Syntax:
putchar(variable_name);
Example:
// C program to implement
// the putchar() function
#include <conio.h>
#include <stdio.h>
// Driver code
int main()
{
char ch;
printf("Enter any character: ");
// Reads a character
ch = getchar();
Output:
Z
gets():
gets() function reads a group of characters or strings from the keyboard by the
user and these characters get stored in a character array. This function allows us
to write space-separated texts or strings. This function is declared in
stdio.h(header file).
Syntax:
gets(str);
Example:
C
// C program to implement
#include <conio.h>
#include <stdio.h>
// Driver code
int main()
{
// Declaring a char type array
// of length 50 characters
char name[50];
// a string
gets(name);
// or a string
name);
return 0;
Output:
Please enter some texts: geeks for geeks
puts():
Syntax:
puts(identifier_name );
Example:
// C program to implement
#include <stdio.h>
// Driver code
int main()
char name[50];
printf("Enter your text: ");
gets(name);
// Displays string
puts(name);
return 0;
Output:
putch():
putch() function is used to display a single character which is given by the user
and that character prints at the current cursor location. This function is declared
in conio.h(header file)
Syntax:
putch(variable_name);
Example:
// C program to implement
#include <conio.h>
#include <stdio.h>
// Driver code
int main()
{
char ch;
ch = getch();
putch(ch);
return 0;
Output:
These are used for storing data These functions are not more
3
more user friendly user-friendly.
● if statement
● else statement
● else-if statement
● switch statement
if Statement
Syntax of if Statement in C
if (condition) {
//code to be executed if condition specified evaluates is true
}
Example of if Statement in C
#include <stdio.h>
int main() {
int x = 10;
if (x > 5) {
return 0;
Output
x is greater than 5
Explanation:
In the above example, the "if" statement checks whether the value of "x" is
greater than 5. Since the condition is true (x is indeed greater than 5), the code
within the curly braces is executed, and the message "x is greater than 5" is
printed to the console.
else Statement
if (condition) {
// statemnets
} else{
// code executed if condition is false
}
C
#include <stdio.h>
int main() {
int x = 10;
if (x < 5) {
return 0;
Output
Explanation:
In this example, the if statement in C checks whether the value of the variable
x is less than 5 or not. Since the value of x (which is 10), this condition is false,
and the code within the "if" block is not executed. Instead, the code within the
"else" block is executed, which prints the message "x is greater than or equal
to 5" to the console.
else if Statement
The else if statement in Cis used when we want to check multiple conditions.
It follows an "if" statement and is executed if the previous "if" statement’s
condition is false.
The "else if" statement can be repeated multiple times to check for multiple
conditions. If all conditions are false, the code within the final "else" block will
be executed.
C
#include <stdio.h>
int main() {
int x = 10;
if (x > 15) {
else if (x > 5) {
printf("x is greater than 5 but less than or equal to 15");
else {
return 0;
Output
Explanation:
In the above code, we have used a complete block of if, else if and else
statements. The if statement first checks whether the value of x is greater
than 15 or not. Since x(which is 10) is less than 15, so the control moves to
the else if block. Now the program checks whether x is greater than 5 or not.
This time the condition is true, so the code block inside this else-if block will
be executed and we get the required output on the screen i.e., "x is greater
than 5 but less than or equal to 15".
switch Statement
The switch statement in C is used when we have multiple conditions to check.
It is often used as an alternative to multiple "if" and "else if" statements.
switch (expression) {
case value1:
// code to be executed if expression equals value1
break;
case value2:
// code to be executed if expression equals value2
break;
...
default:
// code to be executed if none of the cases match
break;
}
The "expression" in the above syntax is the value being evaluated. Each "case"
statement represents a possible value of the expression. If the expression
matches one of the "case" statements, the code block within the matching
"case" statement is executed. If none of the "case" statements match, the
code within the "default" block is executed.
C
#include <stdio.h>
int main() {
int x = 2;
switch (x) {
case 1:
printf("x is 1");
break;
case 2:
printf("x is 2");
break;
case 3:
printf("x is 3");
break;
default:
return 0;
Output
x is 2
Explanation:
In the above example, the "switch" statement checks the value of "x". Since "x"
is equal to 2, the code within the second "case" statement is executed, and the
message "x is 2" is printed to the console.
11. LOOPS
Loops in programming are used to repeat a block of code until the specified
condition is met. A loop statement allows programmers to execute a statement
or group of statements multiple times without repetition of code.
C
// C program to illustrate need of loops
#include <stdio.h>
int main()
return 0;
Output
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
There are mainly two types of loops in C Programming:
checked before entering the main body of the loop. For Loop and
evaluated at the end of the loop body. The loop body will execute at
Loop
Description
Type
first Initializes, then condition check, then executes the body
for loop
and at last, the update is done.
while first Initializes, then condition checks, and then executes the
loop body, and updating can be inside the body.
do-while do-while first executes the body and then the condition check is
loop done.
for Loop
for loop in C programming is a repetition control structure that allows
programmers to write a loop that will be executed a specific number of times.
for loop enables programmers to perform n number of steps together in a single
line.
Syntax:
for (initialize expression; test expression; update expression)
{
//
// body of for loop
//
}
Example:
for(int i = 0; i < n; ++i)
{
printf("Body of for loop which will execute till n");
}
In for loop, a loop variable is used to control the loop. Firstly we initialize the
loop variable with some value, then check its test condition. If the statement is
true then control will move to the body and the body of for loop will be
executed. Steps will be repeated till the exit condition becomes true. If the test
condition will be false then it will stop.
the condition evaluates to true then the loop body will be executed
and then an update of the loop variable is done. If the test expression
becomes false then the control will exit from the loop. for example,
i<=9;
C
// C program to illustrate for loop
#include <stdio.h>
// Driver code
int main()
int i = 0;
{
printf( "Hello World\n");
return 0;
Output
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
While Loop
While loop does not depend upon the number of iterations. In for loop the
number of iterations was previously known to us but in the While loop, the
execution is terminated on the basis of the test condition. If the test condition
will become false then it will break from the while loop else body will be
executed.
Syntax:
initialization_expression;
while (test_expression)
{
// body of the while loop
update_expression;
}
// C program to illustrate
// while loop
#include <stdio.h>
// Driver code
int main()
// Initialization expression
int i = 2;
// Test expression
// loop body
// update expression
i++;
}
return 0;
Output
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
do-while Loop
The do-while loop is similar to a while loop but the only difference lies in the
do-while loop test condition which is tested at the end of the body. In the
do-while loop, the loop body will execute at least once irrespective of the test
condition.
Syntax:
initialization_expression;
do
{
// body of do-while loop
update_expression;
} while (test_expression);
C
// C program to illustrate
// do-while loop
#include <stdio.h>
// Driver code
int main()
// Initialization expression
int i = 2;
do
// loop body
// Update expression
i++;
// Test expression
Output
Hello World
Name Description
Infinite Loop
An infinite loop is executed when the test expression never becomes false and
the body of the loop is executed repeatedly. A program is stuck in an Infinite
loop when the condition is always true. Mostly this is an error that can be
resolved by using Loop Control statements.
#include <stdio.h>
// Driver code
int main ()
int i;
// is blank
for ( ; ; )
}
return 0;
Output
This loop will run forever.
This loop will run forever.
This loop will run forever.
...
// C program to demonstrate
// loop
#include <stdio.h>
// Driver code
int main()
while (1)
return 0;
Output
This loop will run forever.
This loop will run forever.
This loop will run forever.
...
C
// C program to demonstrate
// loop
#include <stdio.h>
// Driver code
int main()
do
{
printf("This loop will run forever.\n");
} while (1);
return 0;
Output
This loop will run forever.
This loop will run forever.
This loop will run forever.
...