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

Unit 1

CPDS unit1

Uploaded by

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

Unit 1

CPDS unit1

Uploaded by

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

UNIT I C PROGRAMMING FUNDAMENTALS

Data Types – Variables – Operations – Expressions and Statements – Conditional


Statements – Functions – Recursive Functions – Arrays – Single and Multi-Dimensional
Arrays.

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.

Types of Data Types in C:

Data Type Example of Data Type


Primary Data Primitive data types are the most basic data types that are used for
Type representing simple values such as integers, float, characters, etc.
The data types that are derived from the primitive or built-in data
Derived Data
types are referred to as Derived Data Types. Example Union,
Type
structure, array, etc.
User Defined
The user-defined data types are defined by the user himself.
Data Types

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

Data Type Modifiers in C

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.

Size of Data Types in C


The size of each data type is defined in bits or bytes (8 bits). Each data type in C is
associated with a specific range of values defined as below:

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

signed int %d, %i -32,767 to 32,767 (same as int) 16 or 32

short int %hd -32,767 to 32,767 16

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

In C programming, operations are the actions performed on variables and values.


1. Arithmetic Operations
Arithmetic operations involve basic mathematical operations:
 Addition (+): Adds two operands.
int sum = 5 + 3; // sum is 8
 Subtraction (-): Subtracts the second operand from the first.
int difference = 5 - 3; // difference is 2

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

// Increment and Decrement

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.

4. EXPRESSIONS AND STATEMENTS

Expressions: An expression is a combination of variables, constants, operators and


functions that evaluates to a value. Expressions can be simple or complex and they are
used to perform operations and produce results.

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

The conditional statements are also known as decision-making statements. They


are of the type if statement, if-else, if else-if ladder, switch, etc. These statements
determine the flow of the program execution.
There are four variants of if-else 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

if statement in To print any code only upon the


satisfaction of a given condition, go with the simple if
statement.
Syntax:
if(test condition){
//code to be executed
}

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

Nested if…else statement in C


include an if-else block in the body of another if-else block. This becomes a nested if-
else statement.
Syntax
if(test condition1)
{ //if condition1 becomes true
if(test condition1.1)
{ //code executes if both condition1 and condition 1.1 becomes true
}
else
{ //code executes if condition1 is true but condition 1.1 is false
}
}
else
{ //code executes if condition1 becomes false
}

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

In contrast to the break statement, instead


of terminating the loop, continue forces to
execute the next iteration of the loop.

Syntax of continue statement in C

//loop statements
continue;
//some lines of the code which is to be
skipped

Example of continue statement in C

#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

Example of goto statement in C


#include <stdio.h>
int main( ) {
printf("Welcome ");
goto l1;
printf("How's the experience?");
l1: printf("to ScholarHat");
return 0;
}

Output: Welcome to ScholarHat

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 declaration: A function must be declared globally in a c program to tell the


compiler about the function name, function parameters, and return type.

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.

Syntax: return_type function_name(parameters) {


// body of the function
}
Example:
int add(int a, int b) {
return a + b;
}

Function Declaration (Prototype)


Before a function is used in a program, it should be declared (prototyped). This informs
the compiler about the function's name, return type, and parameters.
Syntax: return_type function_name(parameters);

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

// The main method


int main() {
myFunction(); // call the function
return 0;
}

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

Different Ways of Calling a Function

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

Functions Without Arguments and Return Value


A function in C programming may not accept an argument and return a value. Here’s an
example of such a function.

#include<stdio.h>
void main (){
printf("Welcome to ");
printName();
}
void printName(){
printf("Simplilearn");
}
Output: Functions_in_C_Programming_2.

Functions with No Arguments But has a Return Value


A function can return a value without accepting any arguments. Here’s an example of
calculating and returning the area of a rectangle without taking any argument.

#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

Functions That Accept Arguments and Give a Return Value


Most C functions will accept arguments and provide a return value. The following
program demonstrates a function in C programming that takes arguments and returns a
value.
#include<stdio.h>
void main(){
int x,y,res;
printf("Enter the two numbers to add:");

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

An array is a collection of elements of the same type, stored in contiguous memory


locations. Arrays are used to store multiple values in a single variable, which can be
accessed using indices.

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

2. Array Initialization with Declaration without Size


If we initialize an array using an initializer list, we can skip declaring the size of the array
as the compiler can automatically deduce the size of the array in these cases. The size of
the array in these cases is equal to the number of elements present in the initializer list as
the compiler can automatically deduce the size of the array.
data_type array_name[] = {1,2,3,4,5};
The size of the above arrays is 5 which is automatically deduced by the compiler.
3. Array Initialization after Declaration (Using Loops)
We initialize the array after the declaration by assigning the initial value to each element
individually. We can use for loop, while loop, or do-while loop to assign the value to each
element of the array.
for (int i = 0; i < N; i++) {
array_name[i] = valuei;
}
Example of Array Initialization in C
// C Program to demonstrate array initialization
#include <stdio.h>
int main()
{
// array initialization using initialier list
23
int arr[5] = { 10, 20, 30, 40, 50 };
// array initialization using initializer list without
// specifying size
int arr1[] = { 1, 2, 3, 4, 5 };
// array initialization using for loop
float arr2[5];
for (int i = 0; i < 5; i++) {
arr2[i] = (float)i * 2.1;
}
return 0;
}

Access Array Elements


To access any element of an array in C using the array subscript operator [ ] and the index
value i of the element.
array_name [index];
One thing to note is that the indexing in the array always starts with 0, i.e., the first
element is at index 0 and the last element is at N – 1 where N is the number of elements
in the array.

Example of Accessing Array Elements using Array Subscript Operator


// C Program to illustrate element access using array
// subscript
#include <stdio.h>
int main()
24
{
// array declaration and initialization
int arr[5] = { 15, 25, 35, 45, 55 };
// accessing element at index 2 i.e 3rd element
printf("Element at arr[2]: %d\n", arr[2]);
// accessing element at index 4 i.e last element
printf("Element at arr[4]: %d\n", arr[4]);
// accessing element at index 0 i.e first element
printf("Element at arr[0]: %d", arr[0]);
return 0;
}
Output
Element at arr[2]: 35
Element at arr[4]: 55
Element at arr[0]: 15

Update Array Element


We can update the value of an element at the given index i in a similar way to accessing
an element by using the array subscript operator [ ] and assignment operator =.
array_name[i] = new_value;
C Array Traversal
Traversal is the process in which we visit every element of the data structure. For C array
traversal, we use loops to iterate through each element of the array.

Array Traversal using for Loop


for (int i = 0; i < N; i++) {
array_name[i];
}

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

Example for single dimensional array


#include <stdio.h>
int main() {
// Declaration and initialization of a single-dimensional array
int numbers[5] = {10, 20, 30, 40, 50};

// Access and print elements of the array


printf("Array elements are:\n");
for (int i = 0; i < 5; i++) {
printf("Element at index %d: %d\n", i, numbers[i]);
}
27
// Modify an element in the array
numbers[2] = 100;

// Print the updated array


printf("\nUpdated array elements are:\n");
for (int i = 0; i < 5; i++) {
printf("Element at index %d: %d\n", i, numbers[i]);
}
return 0;
}
Output
Array elements are:
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50

Updated array elements are:


Element at index 0: 10
Element at index 1: 20
Element at index 2: 100
Element at index 3: 40
Element at index 4: 50

Example for multidimensional array


#include <stdio.h>
int main() {
28
// Declaration and initialization of a 2x3 two-dimensional array
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};

// Access and print elements of the array


printf("Matrix elements are:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("Element at [%d][%d]: %d\n", i, j, matrix[i][j]);
}
}

// Modify an element in the array


matrix[1][2] = 10;

// Print the updated matrix


printf("\nUpdated matrix elements are:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("Element at [%d][%d]: %d\n", i, j, matrix[i][j]);
}
}
return 0;
}
****************

29

You might also like