Unit 1
Unit 1
1. 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.
1
Primary Data Types in C
1. Integer (int): Refers to positive and negative whole numbers (without decimal),
such as 10, 12, 65, 3400, etc.
Range: -2,147,483,648 to 2,147,483,647
Size: 4 bytes
Format Specifier: %d
Syntax of Integer: use ‘int’ keyword to declare the integer variable
int var_name;
Example of int
#include <stdio.h>
void main()
{
int i = 5;
printf("The integer value is: %d \n", i);
}
Output: The integer value is: 5
2. Character (char): Refers to all the ASCII character sets within single quotes such
as ‘a’, ‘A’, etc.
#include <stdio.h>
void main()
{
char c = 'b';
printf("The character value is: %c \n", c);
}
Output: The character value is: b
3. Floating-point (float): Refers to all the real number values or decimal points, such
as 3.14, 10.09, 5.34, etc.
#include <stdio.h>
void main()
{
float f = 7.2357;
printf("The float value is: %f \n", f);
}
2
Output: The float value is: 7.235700
4. Double (double): Used when the range exceeds the numeric values that do not come
under either floating-point or integer data type.
#include <stdio.h>
void main()
{
double d = 71.2357455;
printf("The double value is: %lf \n", d);
}
Output: The double value is: 71.24
Modifiers are C keywords that modify the meaning of fundamental data types. It
indicates how much memory will be allocated to a variable. Modifiers are prefixed with
fundamental data types to adjust the memory allocated for a variable. C Programming
Language has four data type modifiers:
long
short
signed
Unsigned
These modifiers make the memory required for primary data types more precise.
Format
Data Type Minimal Range Size in bit
Specifier
unsigned char %c 0 to 255 8
char %c -127 to 127 8
signed char %c -127 to 127 8
int %d, %i -32,767 to 32,767 16 or 32
unsigned int %u 0 to 65,535 16 or 32
3
unsigned short int %hu 0 to 65,535 16
signed short int %hd Same as short int 16
-2,147,483,647 to
long int %ld, %li 32
2,147,483,647
long long int %lld, %lli -(2^63) to (2^63)-1 64
signed long int %ld, %li Same as long int 32
unsigned long int %lu 0 to 4,294,967,295 32
unsigned
%llu (2^63)-1 64
longlong int
1E-37 to 1E+37 along with six
float %f 32
digits of the precisions
1E-37 to 1E+37 along with six
double %lf 64
digits of the precisions
1E-37 to 1E+37 along with six
long double %Lf 80
digits of the precisions
2. VARIABLES
A variable is the name of the memory location. It is used to store information. Its value
can be altered and reused several times. It is a way to represent memory location through
symbols so that it can be easily identified.
Syntax: data data_type variable_name;
Example: int a=20,b=30;//declaring 2 variable of integer type
float f=20.9;
char c='A';
3. OPERATIONS
4
Multiplication (*): Multiplies two operands.
int product = 5 * 3; // product is 15
Division (/): Divides the first operand by the second.
int quotient = 15 / 3; // quotient is 5
Modulus (%): Returns the remainder of division.
int remainder = 15 % 4; // remainder is 3
2. Relational Operations
Relational operations compare two values and return a boolean result (true or false):
Equal to (==): Checks if two values are equal.
int result = (5 == 3); // result is 0 (false)
Not equal to (!=): Checks if two values are not equal.
int result = (5 != 3); // result is 1 (true)
Greater than (>): Checks if the first value is greater than the second.
int result = (5 > 3); // result is 1 (true)
Less than (<): Checks if the first value is less than the second.
int result = (5 < 3); // result is 0 (false)
Greater than or equal to (>=): Checks if the first value is greater than or equal to
the second.
int result = (5 >= 5); // result is 1 (true)
Less than or equal to (<=): Checks if the first value is less than or equal to the
second.
int result = (5 <= 3); // result is 0 (false)
3. Logical Operations
Logical operations combine boolean expressions:
Logical AND (&&): Returns true if both expressions are true.
int result = (5 > 3 && 8 > 6); // result is 1 (true)
Logical OR (||): Returns true if at least one of the expressions is true.
5
int result = (5 > 3 || 8 < 6); // result is 1 (true)
Logical NOT (!): Returns true if the expression is false.
int result = !(5 > 3); // result is 0 (false)
4. Bitwise Operations
Bitwise operations work on the binary representation of integers:
Bitwise AND (&): Performs a bitwise AND operation.
int result = 5 & 3; // result is 1 (binary 0101 & 0011 = 0001)
Bitwise OR (|): Performs a bitwise OR operation.
int result = 5 | 3; // result is 7 (binary 0101 | 0011 = 0111)
Bitwise XOR (^): Performs a bitwise XOR operation.
int result = 5 ^ 3; // result is 6 (binary 0101 ^ 0011 = 0110)
Bitwise NOT (~): Performs a bitwise NOT operation (inverts bits).
int result = ~5; // result is -6 (binary inversion)
Left Shift (<<): Shifts bits to the left.
int result = 5 << 1; // result is 10 (binary 0101 << 1 = 1010)
Right Shift (>>): Shifts bits to the right.
int result = 5 >> 1; // result is 2 (binary 0101 >> 1 = 0010)
5. Assignment Operations
Assignment operations assign values to variables:
Simple Assignment (=): Assigns the value of the right-hand side to the left-hand
side.
int a = 5; // a is 5
Add and Assign (+=): Adds the right-hand side to the left-hand side and assigns
the result.
int a = 5;
a += 3; // a is now 8
6
Subtract and Assign (-=): Subtracts the right-hand side from the left-hand side
and assigns the result.
int a = 5;
a -= 3; // a is now 2
Multiply and Assign (*=): Multiplies the left-hand side by the right-hand side and
assigns the result.
int a = 5;
a *= 3; // a is now 15
Divide and Assign (/=): Divides the left-hand side by the right-hand side and
assigns the result.
int a = 6;
a /= 3; // a is now 2
Modulus and Assign (%=): Calculates the modulus of the left-hand side by the
right-hand side and assigns the result.
int a = 5;
a %= 3; // a is now 2
6. Increment and Decrement Operations
Increment (++): Increases the value of a variable by 1.
int a = 5;
a++; // a is now 6
Decrement (--): Decreases the value of a variable by 1.
int a = 5;
a--; // a is now 4
Prefix and Postfix:
Prefix (++a or --a): Increments or decrements the value before using it.
Postfix (a++ or a--): Increments or decrements the value after using it.
Example Code:
Here's a simple C program that demonstrates various operations:
#include <stdio.h>
7
int main() {
int a = 10, b = 5;
// Arithmetic operations
printf("Addition: %d\n", a + b); // 15
printf("Subtraction: %d\n", a - b); // 5
printf("Multiplication: %d\n", a * b); // 50
printf("Division: %d\n", a / b); // 2
printf("Modulus: %d\n", a % b); // 0
// Relational operations
printf("Equal to: %d\n", a == b); // 0 (false)
printf("Not equal to: %d\n", a != b); // 1 (true)
printf("Greater than: %d\n", a > b); // 1 (true)
printf("Less than: %d\n", a < b); // 0 (false)
// Logical operations
printf("Logical AND: %d\n", (a > b && b > 0)); // 1 (true)
printf("Logical OR: %d\n", (a > b || b < 0)); // 1 (true)
printf("Logical NOT: %d\n", !(a > b)); // 0 (false)
// Bitwise operations
printf("Bitwise AND: %d\n", a & b); // 0
printf("Bitwise OR: %d\n", a | b); // 15
printf("Bitwise XOR: %d\n", a ^ b); // 15
printf("Bitwise NOT: %d\n", ~a); // -11 (bitwise inversion)
printf("Left Shift: %d\n", a << 1); // 20
printf("Right Shift: %d\n", a >> 1); // 5
8
printf("Increment: %d\n", ++a); // 11
printf("Decrement: %d\n", --b); // 4
return 0;
}
This program demonstrates the basic operations available in C and their usage.
Types of Expressions:
Arithmetic Expressions: Perform mathematical operations.
Example: 3 + 4 * 5 evaluates to 23.
Relational Expressions: Compare values and return a boolean result (true or
false).
Example: 5 > 3 evaluates to 1 (true).
Logical Expressions: Combine boolean values using logical operators.
Example: (5 > 3) && (2 < 4) evaluates to 1 (true).
Bitwise Expressions: Perform bitwise operations on integer values.
Example: 5 & 3 evaluates to 1.
Assignment Expressions: Assign values to variables.
Example: x = 10 assigns 10 to x.
Conditional Expressions (Ternary Operator): Provide a compact way to
evaluate conditions.
Syntax: condition ? expression1 : expression2
Example: int max = (a > b) ? a : b; assigns the greater of a or b to max.
Function Call Expressions: Invoke functions and return values.
Example: sqrt(16) evaluates to 4.0.
9
4.1 Conditional Statements in C
1. if statement in C
2. if-else statement in C
3. if else-if ladder in C
4. nested if statement in C
Example
#include<stdio.h>
int main(){
int num=8;
if(num%2==0){
printf("%d is even number",num);
}
return 0;
}
Output: 8 is even number
if … else statements
It is an extension of the if statement. Here, there is an if block and an else block.
When one wants to print output for both cases - true and false, use the if-else statement.
10
Syntax
if(test condition){
//code to be executed if condition is true
}else{
//code to be executed if condition is false
}
Example:
#include <stdio.h>
int main() {
int num = 10;
if(num < 5) {
printf("Number is less than 5\n");
}
else if(num < 10) {
printf("Number is between 5 and 9\n");
}
else {
printf("Number is 10 or greater\n");
}
return 0;
}
Output: Number is 10 or greater
if else-if ladder in C
It is an extension of the if-else
statement. If we want to check multiple
conditions if the first “if” condition becomes
false, use the if else-if ladder. If all the if
conditions become false the else block gets
executed.
Syntax
if(test condition1){
//code to be executed if condition1 is true
}else if(test condition2){
//code to be executed if condition2 is true
}
else if(test condition3){
//code to be executed if condition3 is true
}
...
11
else{
//code to be executed if all the conditions are false
}
Example:
#include <stdio.h>
int main(){
int number=5;
if(number==20){
printf("number is equals to 20");
}
else if(number==50){
printf("number is equal to 50");
}
else if(number==100){
printf("number is equal to 100");
}
else{
printf("number is not equal to 20, 50 or 100");
}
return 0;
}
Output : number is not equal to 20, 50 or 100
12
Example
#include <stdio.h>
int main()
{
int a = 10; int b = 5;
if (a > b)
{
// control goes to the nested if
if (a % 2 == 0) {
printf("%d is even\n",a);
}
else { printf("%d is odd\n",a);
} }
else
{ printf("%d is not greater than %d\n",a,b);
}
return 0; }
Output: 10 is even
Switch Statement in C
A switch statement tests a variable for equality against a list of values. Each value is
called a case, and the variable being switched on is checked for each switch case.
Syntax
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
13
Example
#include <stdio.h>
int main()
{
int var = 3;
switch (var) {
case 1:
printf("Case 1 is executed");
break;
case 2:
printf("Case 2 is executed");
break;
case 3:
printf("Case 3 is executed");
break;
default:
printf("Default Case is
executed");
break;
}
return 0;
}
Output : Case 3 is executed
Jump Statements in C
C language provides the flexibility of jumping from one statement to another. There are
four kinds of jump statements in C:
1. break
In C, break is used to prematurely exit
from a loop or switch statement, before the
block has been fully executed.
Syntax
//loop or switch case
break;
14
Example of break statement
#include <stdio.h>
main( ){
int i;
for (i=1; i<=5; i++){
printf ("%d ", i );
if (i==5)
break;
}
}
Output : 1 2 3 4 5
Continue
//loop statements
continue;
//some lines of the code which is to be
skipped
#include <stdio.h>
int main( ){
int i;
for (i=1; i<=8; i++){
if (i==5)
continue;
printf("%d ", i);
}
return 0;
}
Output 1 2 3 4 6 7 8
15
goto
It is used after the normal sequence of program execution by transferring the control to
some other part of the program.
Syntax of goto statement in C
goto label;
// ...
label:
// Statement(s) to execute
return
It terminates the execution of the function and returns the control of the calling function.
Syntax of return statement in C
return expression;
Example of return statement in C
#include <stdio.h>
int multiply(int x, int y) {
return x * y;
}
int main() {
int z = multiply(8,9);
printf("The product is: %d\n", z);
return 0; }
Output: The product is: 72
16
5. FUNCTIONS
In c, divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}. A function can be
called multiple times to provide reusability and modularity to the C program. The
collection of functions creates a program. The function is also known as procedure or
subroutine in other programming languages.
Advantage of functions in C
By using functions, we can avoid rewriting same logic/code again and again in a
program.
We can call C functions any number of times in a program and from any place in a
program.
We can track a large C program easily when it is divided into multiple functions.
Reusability is the main achievement of C functions.
However, Function calling is always a overhead in a C program.
Types of Functions
There are two types of functions in C programming:
Library Functions: are the functions which are declared in the C header files such as
scanf(), printf(), gets(), puts(), ceil(), floor() etc.
User-defined functions: are the functions which are created by the C programmer, so
that he/she can use it many times. It reduces the complexity of a big program and
optimizes the code.
Function Aspects
There are three aspects of a C function.
Function call: Function can be called from anywhere in the program. The parameter list
must not differ in function calling and function declaration. We must pass the same
number of functions as it is declared in the function declaration.
Function definition: It contains the actual statements which are to be executed. It is the
most important aspect to which the control comes when the function is called. Here, we
must notice that only one value can be returned from the function.
17
Definition of a Function
A function in C is defined by specifying its return type, name, parameters (if any), and
body. The body of the function contains the statements that perform the function’s task.
Example 1: int sum(int a, int b); // Function declaration with parameter names
int sum(int , int); // Function declaration without parameter names
Example 2:
// Function declaration
int myFunction(int x, int y);
// The main method
int main() {
int result = myFunction(5, 3); // call the function
printf("Result is = %d", result);
return 0;
}
// Function definition
int myFunction(int x, int y) {
return x + y; }
Function Definition
The function definition includes the actual body of the function. It must match the
function declaration.
18
Example:
// Function declaration
void myFunction();
// Function definition
void myFunction() {
printf("I just got executed!");
}
Function Call
A function call is a statement that instructs the compiler to execute the function. We use
the function name and parameters in the function call.
Syntax: function_name(arguments);
Example 1:
int main() {
int result=add(5,3); // Function call
printf("The sum is %d\n", result);
return 0;}
Example 2:
// Create a function
void myFunction() {
printf("I just got executed!");
}
int main() {
myFunction(); // call the function
return 0;
}
Output: I just got executed!
Depending on whether the function accepts arguments or not and returns a value or not,
there can be four different aspects of C function calls, which are:
19
Functions Without Arguments and Return Value
Functions with No Arguments But has a Return Value
Functions With Arguments But No Return Value
Functions That Accept Arguments and Give a Return Value
#include<stdio.h>
void main (){
printf("Welcome to ");
printName();
}
void printName(){
printf("Simplilearn");
}
Output: Functions_in_C_Programming_2.
#include<stdio.h>
void main(){
int area = rect_Area();
printf("The area of the Rectangle is: %d\n",area);
}
int rect_Area(){
int len, wid;
printf("Enter the length of the rectangle: ");
scanf("%d",&len);
printf("Enter the width of the rectangle: ");
scanf("%d",&wid);
return len * wid;
}
Output: Functions_in_C_Programming_3
20
Functions With Arguments But No Return Value
C functions may accept arguments but not provide any return value. Given below is an
example of such a function.
#include<stdio.h>
void main(){
int x,y;
printf("Enter the two numbers to add:");
scanf("%d %d",&x,&y);
add(x,y);
}
// Accepting arguments with void return type
void add(int x, int y){
printf("The sum of the numbers is %d",x+y);
}
Output: Functions_in_C_Programming_4
scanf("%d %d",&x,&y);
res = add(x,y);
printf("The sum of the numbers is %d",res);
}
int add(int x, int y){
return x+y;
}
Output: Functions_in_C_Programming_5.
21
6. ARRAYS
Array Declaration
To declare the array like any other variable before using it. To declare an array by
specifying its name, the type of its elements and the size of its dimensions. When declare
an array in C, the compiler allocates the memory block of the specified size to the array
name.
Syntax
data_type array_name [size];
or
data_type array_name [size1] [size2]...[sizeN];
where N is the number of dimensions.
The C arrays are static in nature, i.e., they are allocated memory at the compile time.
Example
#include <stdio.h>
int main()
{
// declaring array of integers
int arr_int[5];
// declaring array of characters
char arr_char[5];
return 0;
}
Array Initialization
Initialization in C is the process to assign some initial value to the variable. When the
array is declared or allocated memory, the elements of the array contain some garbage
22
value. So, we need to initialize the array to some meaningful value. There are multiple
ways in which we can initialize an array in C.
1. Array Initialization with Declaration
In this method, we initialize the array along with its declaration. We use an initializer
list to initialize multiple elements of the array. An initializer list is the list of values
enclosed within braces { } separated b a comma.
data_type array_name [size] = {value1, value2, ... valueN};
25
7. SINGLE AND MULTI-DIMENSIONAL ARRAYS
Single-Dimensional Arrays
A single-dimensional array is a list of elements, all of the same type, accessed by an
index. The size of the array is fixed.
Declaration and Initialization:
Declaration:
type arrayName[arraySize];
Example:
int numbers[5]; // Declares an array of 5 integers
Initialization:
type arrayName[arraySize] = {value1, value2, value3, ...};
Example:
int numbers[5] = {1, 2, 3, 4, 5}; // Initializes the array with 5 integers
Accessing Elements:
Elements are accessed using their index:
int firstNumber = numbers[0]; // Accesses the first element
numbers[2] = 10; // Sets the third element to 10
Multi-Dimensional Arrays
Multi-dimensional arrays are arrays of arrays. The most common multi-dimensional array
is the two-dimensional array, which is often used to represent matrices or grids.
Declaration and Initialization:
Two-Dimensional Array:
type arrayName[rows][columns];
Example:
int matrix[3][4]; // Declares a 3x4 matrix (3 rows and 4 columns)
26
Initialization:
type arrayName[rows][columns] = {
{value11, value12, value13, value14},
{value21, value22, value23, value24},
{value31, value32, value33, value34}
};
Example:
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
Accessing Elements:
Elements are accessed using row and column indices:
int value = matrix[1][2]; // Accesses the element at row 1, column 2
matrix[2][3] = 20; // Sets the element at row 2, column 3 to 20
29