0% found this document useful (0 votes)
59 views98 pages

C Programming: Functions and Arrays

This document outlines Module 3 of the Introduction to C Programming course, focusing on functions and arrays. It covers topics such as function definition, declaration, calling, and the importance of functions for code reusability, as well as array operations. Additionally, it provides examples of function usage, parameter passing methods, and variable scope in C programming.

Uploaded by

hema
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)
59 views98 pages

C Programming: Functions and Arrays

This document outlines Module 3 of the Introduction to C Programming course, focusing on functions and arrays. It covers topics such as function definition, declaration, calling, and the importance of functions for code reusability, as well as array operations. Additionally, it provides examples of function usage, parameter passing methods, and variable scope in C programming.

Uploaded by

hema
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

RajaRajeswari College of Engineering

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Autonomous institution, Affiliated to Visvesvaraya Technological University“Jnana Sangama”,
Belgaum – 560 018
Ms. Thilagavalli S, Assistant Professor
Subject Name: “Introduction to C Programming”

Subject Code: “B24ESCK245”


“Module-3”
Semester: II
Section: ECE A,B
MODULE 3

• Functions: Introduction using functions, Function definition, function declaration,


function call, return statement, passing parameters to functions, scope of variables,
Storage classes, Recursion.
• Arrays: array Declaration and Initialization of arrays, accessing the elements of
an array, storing values in arrays- One dimensional, two dimensional, Operations
on arrays-Searching and sorting.
Introduction to Functions

• Functions in C are the basic building blocks of a C program.

• A function is a set of statements enclosed within curly brackets ({}) that take
inputs, do the computation, and provide the resultant output.

• You can call a function multiple times, thereby allowing reusability in C


programming.

• It means that instead of writing the same code again and again for different
arguments.
Introduction to Functions

• you can simply enclose the code and make it a function and then call it
multiple times by merely passing the various arguments.

• C enables its programmers to break up a program into segments


commonly known as functions.

• A function is a block of code which only runs when it is called.

• You can pass data, known as parameters, into a function.


Introduction to Functions
Why Do We Need Functions in C Programming?

• Enables reusability and reduces redundancy.


• The program becomes easy to understand and manage.
• Dividing the program into separate well defined functions.
• This simplifies the process of getting the total program to work.
• Understanding, coding and testing multiple separate functions are far easier than doing
the same for one huge function.
• If a big program has to be developed without the use of any function (except main()),
then there will be countless lines in the main() .
Introduction to Functions
• Predefined Functions

• For example, printf() is a function; used to display output/print text to the screen:

#include <stdio.h>
int main()
{
printf("Hello World!");
return 0;
}
Output:
Hello World!
main() is a function, which is used to execute code
Function Definition
• Function definition consists of a function header that identifies the function.

• followed by the body of the function containing the executable code for that function
When a function defined.

• The syntax of a function definition can be given as:

return_data_type function_name(data_type arg1, data_type arg2,.. argn)


{
………….
statements
………….
return( variable);
}
Function Definition
In the above syntax:
•return_type: we declare the data type of the value returned by functions. However, not
all functions return a value. In such cases, the keyword void indicates to the compiler that
the function will not return any value.

•function_name: This is the function’s name that helps the compiler identify it whenever
we call it.

•arg1, arg2, ...argn: It is the argument or parameter list that contains all the parameters to
be passed into the function. A function may or may not require parameters. Hence, the
parameter list is optional.

•Body: The function’s body contains all the statements to be processed and executed
whenever the function is called.
EXAMPLE:1

Example 1: Function with Return Value

int addNumbers(int a, int b)


{
int sum = a + b; // Calculate the sum of two numbers
return sum; // Return the result
}

Explanation:

•int: The function returns an integer.


•addNumbers: Name of the function.
•(int a, int b): The function takes two integer parameters.
•Inside the body ({}), the function calculates the sum of a and b and returns the result
Example 2: Function Without Return Value

void greet()
{
printf("Hello, welcome!\n");
}

Explanation:

•void: The function does not return any value.


•greet: Name of the function.
•() indicates the function does not take any parameters.
•Inside the body, it simply prints a greeting message.
EXAMPLE 3
#include <stdio.h> int main() {
int num1, num2, sum, difference, product;

// Function to add two numbers printf("Enter two numbers: ");


int add(int a, int b) { scanf("%d %d", &num1, &num2);
return a + b; // Return the sum of a and b
// Calling functions and storing the results
} sum = add(num1, num2); // Calls add() function
difference = subtract(num1, num2); // Calls subtract() function
// Function to subtract two numbers product = multiply(num1, num2); // Calls multiply() function
int subtract(int a, int b) {
// Displaying the results
return a - b; // Return the difference of a and b printf("Sum: %d\n", sum);
} printf("Difference: %d\n", difference);
printf("Product: %d\n", product);
// Function to multiply two numbers
return 0;
int multiply(int a, int b) { }
return a * b; // Return the product of a and b
OUTPUT: Enter two numbers: 5 3
} Sum: 8
Difference: 2
Product: 15
Example: Function to Calculate the Factorial of a Number
#include <stdio.h>
long long int factorial(int n) {
if (n <= 1)
return 1;
else
return n * factorial(n - 1);
}
int main() {
int num = 5;
printf("Factorial of %d is %lld\n", num, factorial(num)); // Reusable
return 0;
}
Output:
Factorial of 5 is 120
Example: Function to Calculate the Square of a Number
#include <stdio.h>

int square(int num) {


return num * num;
}
int main() {
int a = 4, b = 7;

// Using the square function at two places


printf("Square of %d is %d\n", a, square(a)); // Reused
printf("Square of %d is %d\n", b, square(b)); // Reused

return 0;
}
Output: Square of 4 is 16
Square of 7 is 49
Function Declaration

• Function declaration is a declaration statement that identifies a function with its


name, a list of arguments that it accepts and the type of data it returns.

• The general format for declaring a function that accepts some arguments and
returns some value as result can be given as:

• return_data_type function_name(data_type arg1, data_type arg2,.. argn);

• Example, float avg ( int a, int b);


Function Declaration

• Example:-2
int large (int x, int y);
• is a function declaration with function_name “large” with return _type “integer” and has two arguments “x” and
“y” of integer type.
Why and where we need function declaration: (Extra)
• If the function is defined before it is used:
• If you define the function before its usage, there is no need for a function declaration, as the
compiler can directly read the function's definition and understand how to call it.
• For Ex:
• The factorial() function is defined before the main() function.
• The factorial() function is used in main() after it has already been defined.
• No function declaration is needed because the compiler can directly read the function definition
before it is used.

• If the function is used before its definition:


• Without a function declaration, if a function is used before it is defined, the compiler will not
know how to handle the function call. This will cause a compilation error, specifically a "implicit
declaration" error.
• For ex:
• The factorial() function is used in main() before it is defined.
• The compiler will throw an implicit declaration error because it does not know what the
factorial() function looks like yet.
Example:
#include <stdio.h>
long long int factorial(int n); // Function Declaration (Prototype)

int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
printf("Factorial of %d is %lld\n", number, factorial(number)); // Call the factorial function and display the result
return 0;
}

// Function Definition
long long int factorial(int n) {
if (n <= 1) {
return 1;
} else {
return n * factorial(n - 1); // Recursive call
}
}
Function Call
Function Call
Return Statement
• It is used at the end of a function to end or terminate it with or without a value.

• It can only be used in function that is declared with a return type such as int, float,
double etc.

• The function declared with void type does not return any value.

• Example 1:
int sum()
{

return variable;
}
Return Statement
Example 2: (No return value)
Void value()
{
printf(“ hello ”);
}

Example 3:
double large(double a, double b) {
if (a > b)
return a;
else return b;
}
Return Statement
Example 4:
/* C program to demonstrate Function with argument and with return value */

#include<stdio.h>
int add(int a, int b);
void main()
{
int a,b,sum;
printf("Enter two numbers\n");
scanf("%d%d",&a,&b);
sum=add(a,b);
printf("The Sum of two numbers=%d\n",sum);
}

int add(int a, int b)


{
int sum;
sum=a+b;
return sum;
}
Types of Parameters in C Functions
1. Formal Parameters
2. Actual Parameters
1. Formal Parameters:
• These are the parameters listed in the function declaration and definition.
• They act as placeholders for the values provided when the function is called.
• Example:
void add(int a, int b) { // 'a' and 'b' are formal parameters
printf("Sum: %d\n", a + b);
}
2. Actual Parameters:
• These are the real values or variables passed to the function when it is called.
• They correspond to the formal parameters.
• Example:
int main() {
int x = 5, y = 10;
add(x, y); // 'x' and 'y' are actual parameters
return 0;
}
Passing parameters to the functions
• There are two ways in which arguments or parameters can be passed to the called
function.

1. Call by value
2. Call by reference

1. Call by value :Value of actual parameter will be copied to formal parameters


and these two different parameters store value in different location.
int a=10, b=20;
int func(a,b) int func(int x, int y)
10 20 20 10
a b x y
address location(1024) address location(1025) address location(2048) address location(1029)
•A copy of the value is passed to the function.
•Changes made inside the function do not affect the original data.
Example:
#include <stdio.h>
void modifyValue(int a) {
a = a + 10; // Modify the value
printf("Inside function: a = %d\n", a);
}
int main() {
int num = 5;
printf("Before function call: num = %d\n", num);
modifyValue(num);
printf("After function call: num = %d\n", num); // Unchanged
return 0;
}
• Example: swapping two numbers using call by value
#include <stdio.h>
// Function to swap two numbers using call by value
void swap(int a, int b) {

int temp;
Output:
temp = a;
Enter two numbers:
a = b; 5 10
b = temp; Before swapping: x = 5, y = 10
printf("Inside swap function: a = %d, b = %d\n", a, b); Inside swap function: a = 10, b = 5
} After swapping (in main): x = 5, y = 10
int main() {
int x, y;
printf("Enter two numbers:\n");
scanf("%d %d", &x, &y)
printf("Before swapping: x = %d, y = %d\n", x, y);
swap(x, y);
printf("After swapping (in main): x = %d, y = %d\n", x, y);
return 0;
}
Passing parameters to the functions
2. Call by Reference: Here both actual and formal parameters refer to same
memory location. Therefore any changes made to the formal parameters will get
reflected to actual parameters.

int a=10, b=20;


int func(a,b) int func(int x, int y)
10 20 10 20

a b x y
address location(1024) address location(1025) address location(1024) address location(1025)
• A reference (address) is passed to the function.
• Changes made inside the function affect the original data.

Example:
#include <stdio.h>
Output:
void modifyValue(int *a) {
Before function call: num = 5
*a = *a + 10; // Modify the value at the address Inside function: *a = 15
printf("Inside function: *a = %d\n", *a); After function call: num = 15
}

int main() {
int num = 5;
printf("Before function call: num = %d\n", num);
modifyValue(&num); // Passing address of num
printf("After function call: num = %d\n", num); // Changed
return 0;
}
Passing parameters to the functions
• Example: swapping two numbers using call by reference
#include<stdio.h>
void swap(int *a, int *b);
int main()
{
int a=10, b=20; // a=10 //b=20
printf(“a=%d b=%d",a,b);
swap(&a, &b); //Address passed
printf(“x=%d y=%d",a,b); //After swapping now, a=20, b=10
}
void swap(int *x, int *y) //Actual Arguments will get Altered.
{
int temp;
temp=*x; // x=20
*x=*y; // y=10
*y=temp;
}
VARIABLES SCOPE
• In C, all constants and variables have a defined scope.

• By scope we mean the accessibility and visibility of the variables at different points in
the program.

• A variable or a constant in C has four types of scope: block, function, file and program
scope.
VARIABLES SCOPE
1. BLOCK SCOPE
• A statement block is a group of statements enclosed within an opening and closing curly brackets ({ }). If a variable is
declared within a statement block then, as soon as the control exits that block, the variable will also exist. Such a variable also
known as a local variable and is said to have a block scope.
• A variable declared inside a block (typically enclosed by curly braces {}) has block scope. This means the variable is
accessible only within that block and not outside it.
Example:
#include <stdio.h>

int main() {
int x = 10; // x has block scope in main
if (x == 10) {
int y = 20; // y has block scope inside the 'if' block
printf("y inside block: %d\n", y);
}
// printf("y outside block: %d\n", y); // Error: 'y' is not visible here
printf("x inside main: %d\n", x);
return 0;
}
• Example:
#include <stdio.h>
int main()
{
int i;
int x = 10;
printf("\n The value of x outside the while loop is %d", x);
while (i<3)
{
int x = i;
printf("\n The value of x inside the while loop is %d", x);
i++;
}
return 0;
}
• 2. FUNCTION SCOPE
• Function scope is applicable only with goto label names.
• The programmer can not have the same label name inside a function.
• Using goto statements is not recommended as it is not considered to be a good
programming practice. We will not discuss the goto statement in detail here but we will
take a look at an example code that demonstrates the function scope.
• Example:
int main() {
loop: /* A goto label has function scope */
goto loop; /* the goto statement */
return 0;
}
• In this example, the label Loop is visible from the beginning to the end of the main()
function. Therefore, there should not be more than one label having the same name within
the main() function.
VARIABLES SCOPE
3. PROGRAM SCOPE
• Global variables are those variables that can be accessed from any point in the program.
#include<stdio.h>
int x = 10;
void display();
int main()
{
int x = 2;
printf("\n The value of local variable x is= %d", x);
display();
}
void display()
{
printf("\n The value of global variable x is = %d", x);
}
VARIABLES SCOPE
4. FILE SCOPE

• When a global variable is accessible until the end of the file, the variable is said to have file

scope.

• To allow a variable to have file scope, declare that variable with the static keyword before

specifying its data type, like this:

static int x = 10;

• A global static variable can be used any where from the file in which it is declared but it is not

accessible by any other files.

• Such variables are useful when the programmer writes his own header files.
Storage Classes
1. auto (Automatic) Storage Class

•Default Storage Class: If no storage class is specified, the variable is assumed to have auto storage class by defaul
•Scope: Local to the function or block in which it is declared.
•Lifetime: Exists only during the function/block execution.
•Initialization: Initialized by default to garbage values.
•Usage: Primarily used for local variables inside a function.
•Example:
#include <stdio.h>

void myFunction() {
auto int x = 10; // auto is default, so it can be omitted
printf("Inside function: x = %d\n", x); Output:
} Inside function: x = 10
Explanation: The auto storage class is the default for local
int main() { variables. It is not explicitly required to use auto because local
myFunction(); variables are automatically considered as auto. They are created
return 0; when the function is called and destroyed when the function
} exits.
2. register Storage Class
• Scope: Local to the function or block where it is declared.
• Lifetime: Exists only during the function/block execution.
• Purpose: Indicates that the variable should be stored in a CPU register (if possible), providing
faster access compared to memory.
• Example:
#include <stdio.h>
void myFunction() {
register int x = 5; // register suggests storage in CPU register
printf("Inside function: x = %d\n", x);
}
int main() {
Explanation: The register keyword suggests that the
myFunction(); variable x should be stored in a CPU register for faster
return 0; access, although the compiler may choose not to use a
} register depending on available resources.
.

Output:
Inside function: x = 5
[Link] Storage Class

•Scope: If declared inside a function, the variable has local scope but retains its value across function calls. If
declared outside any function, it has file scope, meaning it is only visible within the file it is declared in.
•Lifetime: The variable exists for the lifetime of the program, i.e., it is created when the program starts and destroyed
when the program ends.
•Purpose: Used for retaining values between function calls (for local variables) and limiting visibility of
variables/functions to the current file (for global variables/functions).
•Initialization: Initialized to zero by default if not explicitly initialized.
•Example:
#include <stdio.h>

static int x = 10; // Static variable with file scope

void printX() { Explanation: The variable x is only


printf("Value of x: %d\n", x); accessible within the current file due to its
} static storage class. It cannot be accessed
int main() { from other files in the program.
printX();
return 0;
}
Output:
Value of x: 10
4. extern Storage Class

•Scope: extern variables or functions are visible across multiple files. It allows a
variable or function to be defined in one file but accessed in other files.
•Lifetime: Exists for the lifetime of the program.
•Purpose: Used to declare variables or functions that are defined in another file.
•Initialization: The extern declaration does not allocate memory for the variable but
tells the compiler that the variable is defined elsewhere.
Example :
File 1 (main.c):
#include <stdio.h>
extern int x; // Declare the variable defined in another file
int main() {
printf("Value of x: %d\n", x); // Accessing variable defined externally
return 0;
}

File 2 (data.c):
#include <stdio.h>
int x = 10; // Define the variable

•Output (when compiled together):


• Value of x: 10
•Explanation: The extern keyword in main.c tells the compiler that x is defined in another
file (data.c). The variable x is initialized to 10 in data.c.
Recursive Functions
Programmers use two approaches to write repetitive algorithms:
 One approach is to use loops
 The other uses recursion

• The recursion is similar to iteration.


• Recursive functions have two parts:
1. Base case
2. Recursive case
Recursive Functions
1. Base case:

the base case is a specific condition in the function. When it is met, it terminates the recursion. It is used
to make sure that the program will terminate. Otherwise, it goes into an infinite loop.

2. Recursive case: The part of code inside the recursive function executed repeatedly while calling the
recursive function is known as the recursive case.
Recursive Functions
Program to find a factorial of number using recursion.
Recursive Functions
Program to find a factorial of number using recursion.
#include<stdio.h>
int fact(int);
void main( )
{
int n,result;
printf(“Enter a number”);
scanf(“%d”,&n);
result=fact(n);
printf(“Factorial = %d”,result);
}
int fact(int n)
{
if(n==0)
return 1;
else
return (n*fact(n-1));
}
Example: Program to find nCr value using recursion

#include <stdio.h>
int factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}
int nCr(int n, int r) {
return factorial(n) / (factorial(r) * factorial(n - r));
}
int main() {
int n, r, result;
printf("Enter a value for n and r: ");
scanf("%d %d", &n, &r);
result = nCr(n, r);
printf("nCr Value = %d\n", result);
return 0;
}
Arrays
• Arrays are used to store multiple values in a single variable, instead of declaring separate variables for
each value.

• To create an array, define the data type (like int) and specify the name of the array followed by square
brackets [].

• To insert values to it, use a comma-separated list, inside curly braces:

• int myNumbers[] = {25, 50, 75, 100};

• We have now created a variable that holds an array of four integers.



Arrays
Why Arrays?
Consider a situation, where we need to store 5 integer numbers. If we use simple
variable and data type concepts, then we need 5 variables of int data type and program will be
something as follows:

#include<stdio.h>
void main()
{
int number1;
int number2;
int number3;
int number4;
int number5;
Arrays
number1 = 10;
number2 = 20;
number3 = 30;
number4 = 40;
number5 = 50;
printf( "number1: %d \n", number1);
printf( "number2: %d \n", number2);
printf( "number3: %d \n", number3);
printf( "number4: %d \n", number4);
printf( "number5: %d ", number5);
}

• But if we are using arrays it will be simple as,

int numbers[] = {10,20,30,40,50};


Arrays
Definition of an Array:-The array is a collection of elements of same data type. The elements
are stored sequentially one after the other in memory.

Any element can be accessed by using:

→ name of the array

→ position of element in the array (index)


Arrays
C language provides a concept called the ARRAY

Examples where arrays can be used are

• List of temperatures recorded every hour in a day, or a month, or a year

• List of employees in an organization

• List of products and their cost sold by a store

• Test scores of a class of students


Declaration of Arrays
Types of array :-

• Single dimensional array or One dimensional array

• Two dimensional array

• Multi dimensional array

Single Dimensional Array :- An Array which has only one subscript is known as Single

dimensional array or One dimensional array

• The individual array elements are processed by using a common array name with different

index values that start with Zero and ends with array_size-1

• Syntax of Declaring Single Dimensional Arrays

data_type array_name[array_size];
Declaration of Arrays
• data_type: can be int, float or char….

• array_name: is name of the array

• array_size : an integer constant indicating the maximum number of data elements to be stored.

• Example: int a[5];

• Here a is an Integer Array that can hold up to 5 values in it.

Array Representation
Declaration of Arrays
a[0] holds the first element in the array

a[1] holds second element in the array

a[2] holds third element in the array

and so on..

Initializing Arrays

You can initialize an array in C either one by one or using a single statement as follows −

double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};


Accessing array elements
EXTRA…
Reading, Writing the elements of an array:

How to Read and Write Elements of an Array in C


[Link] Elements: You can read (or access) an element of an array by referencing its index. In C, array
indices start at 0.
[Link] Elements: You can assign a value to an element in the array by specifying its index.
Basic Syntax:
•Reading an element: array[index]
•Writing an element: array[index] = value
•Example:
#include <stdio.h>
int main() {
// Declare an array of size 5
int arr[5];
// Writing elements to the array
arr[0] = 10; // Writing 10 to arr[0]
arr[1] = 20; // Writing 20 to arr[1]
arr[2] = 30; // Writing 30 to arr[2]
arr[3] = 40; // Writing 40 to arr[3]
arr[4] = 50; // Writing 50 to arr[4]
Continuation….
// Reading and printing elements of the array
printf("Array elements are:\n");
printf("arr[0] = %d\n", arr[0]); // Reading arr[0]
printf("arr[1] = %d\n", arr[1]); // Reading arr[1] OUTPUT:
printf("arr[2] = %d\n", arr[2]); // Reading arr[2] Array elements are:
arr[0] = 10
printf("arr[3] = %d\n", arr[3]); // Reading arr[3]
arr[1] = 20
printf("arr[4] = %d\n", arr[4]); // Reading arr[4] arr[2] = 30
arr[3] = 40
// Alternatively, you can use a loop to read the elements arr[4] = 50
printf("\nUsing a loop to print the array elements:\n");
for (int i = 0; i < 5; i++) { Using a loop to print the array elements:
arr[0] = 10
printf("arr[%d] = %d\n", i, arr[i]); // Reading each element
arr[1] = 20
} arr[2] = 30
arr[3] = 40
return 0; arr[4] = 50
}
//C Program to Find the Largest Number in an Array

#include <stdio.h> // Initialize the largest number to the first element


int main() { int largest = arr[0];
int n, i;

// Traverse through the array to find the largest number


// Ask the user for the number of elements in the array
for (i = 1; i < n; i++) {
printf("Enter the number of elements: ");
scanf("%d", &n); if (arr[i] > largest) {
largest = arr[i]; // Update largest if current element is
// Declare an array to hold the numbers larger }
int arr[n];
}
// Print the largest number
// Input the elements of the array
printf("Enter %d numbers: \n", n); printf("The largest number is: %d\n", largest);
for (i = 0; i < n; i++) { return 0;
scanf("%d", &arr[i]); }
}
Output:
Enter the number of elements: 5
Enter 5 numbers:
10 2 34 5 8
The largest number is: 34

Explanation:
Input:
•The program first asks the user to input the number of elements (n) in the array.
•Then it takes n integers from the user and stores them in an array called arr.
Finding the Smallest Number:
•The smallest number is initially assumed to be the first element (arr[0]).
•The program then iterates through the rest of the array, comparing each element with the current
smallest number. If a smaller number is found, it updates the smallest variable.
Output:
•The program prints the smallest number after completing the iteration through the array.
Two Dimension arrays
Two Dimension arrays
Two Dimension arrays
Two Dimension arrays
Operation on two-dimension arrays
Operation on two-dimension arrays
Storing values in arrays
Storing values in arrays

1. Initializing Arrays During Declaration


• This involves assigning values to an array at the time of its declaration.
Syntax:
data_type array_name[size] = {value1, value2, ..., valueN};
Example:
int arr[5] = {10, 20, 30, 40, 50};
Explanation:
• The array arr is initialized with values 10, 20, 30, 40, 50 at the time of declaration.
• If fewer values are provided than the array size, the remaining elements are automatically
initialized to 0.

Example with Partial Initialization:


int arr[5] = {1, 2}; // The remaining elements are set to 0: {1, 2, 0, 0, 0}
2. Inputting Values from the Keyboard
• This method involves allowing the user to input values into the array during program
execution.
• If the values are not known by the programmer in advance then the user makes use of run time
initialization.
• It helps the programmer to read unknown values from the end users of the program from
keyboard by using input function scanf().

• Example: /* C program to demonstrate run time initialization*/


#include<stdio.h>
void main()
{
int b[5],i;
printf(“Enter 5 elements\n”);
for(i=0;i<5;i++)
{
scanf(“%d”,&b[i]);
}
}
Example: 2
#include <stdio.h>

int main() {
int arr[5]; // Declare an array of size 5
printf("Enter 5 integers:\n");

for (int i = 0; i < 5; i++) {


scanf("%d", &arr[i]); // Input values from the user
}

printf("The array elements are:\n");


for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]); // Print the array elements
}
return 0;
}
3. Assigning Values to Individual Elements
• You can assign values to specific elements of the array using their indices.
• Example:
int arr[5]; // Declare an array of size 5

arr[0] = 10; // Assign value 10 to the first element


arr[1] = 20; // Assign value 20 to the second element
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
This method is useful when values are determined or calculated during runtime.
Accessing Values:
printf("%d\n", arr[0]); // Output: 10
printf("%d\n", arr[1]); // Output: 20
• Combining All Three Methods :- Here’s a complete example combining the three approaches:

#include <stdio.h>

int main() {
// 1. Initializing during declaration
int arr1[3] = {5, 10, 15};

// 2. Inputting values from the keyboard


int arr2[3];
printf("Enter 3 integers:\n");
for (int i = 0; i < 3; i++) {
scanf("%d", &arr2[i]);
}

// 3. Assigning to individual elements


int arr3[3];
arr3[0] = 100;
arr3[1] = 200;
arr3[2] = 300;
OPERATIONS PERFORMED ON ONE_DIMENSIONAL ARRAY

• SORTING: It is the process of arranging elements in the list according to their values in
ascending or
descending order. A sorted list is called an ordered list.
• Ex: Bubble Sort, Selection Sort, Insertion Sort, Quick Sort.
• 1. Bubble sort will start by comparing the first element of the array with the second element, if
the first element is greater than the second element,
• it will swap both the elements, and then move on to compare the second and the third element, and
so on.
Operations on arrays
[Link] sort: This is an in-place comparison based algorithm It is comparison based algorithm

in which list is divided into 2 parts.

• The sorted part at left and unsorted part at right end. Initially sorted part is empty and

unsorted part is entire list.

• The smallest element is taken from the unsorted array and swapped with the left most

element and the element becomes the part of sorted array


Operations on arrays
Algorithm for Linear Search in Arrays

[Link].
[Link] the array elements and the target element to be searched.
[Link] a loop counter i = 0.
[Link] the following steps while i < n (size of the array):
•If arr[i] == target, return the index i (element found).
•Otherwise, increment i by 1.
[Link] the loop completes without finding the target, return "Element not found".
[Link].

// Linear Search Example


#include <stdio.h>

int search(int array[], int n, int x)


{

// Going through array sequencially


for (int i = 0; i < n; i++)
if (array[i] == x)
return i;
return -1;
}
Operations on arrays

(Right R)

(Left L)
Find the middle element:
•Calculate the middle index:
. mid = low + (high - low) / 2

Compare the target value with


the middle element:
• If the target value matches the
middle element,. return the
index
• If the target value is smaller
than the middle element, narrow
the search to the left half by
setting
high = mid - 1.
• If the target value is larger
than the middle element, narrow
the search to the right half by
setting
low = mid + 1.
Repeat the process until the low
pointer exceeds the high pointer,
meaning the element isn't in the
array, or you find the target.
Linear Search Binary Search

1. In linear search input data need not to be in [Link] binary search input data need to be in sorted
sorted. order.

[Link] is also called half-interval search. Divide


2. It is also called sequential search.
and Conquer method

3. The time complexity of linear search O(n). [Link] time complexity of binary search O(log n).

4. Multidimensional array can be used. 4. Only single dimensional array is used.

5. Linear search performs equality comparisons 5. Binary search performs ordering comparisons

6. It is less complex. 6. It is more complex.

7. It is very slow process. 7. It is very fast process.


Extra…

1. Traversing an Array:- Traversing means visiting each element of the array for processing.
Algorithm:
Step 1: [INITIALIZATION] SET I = lower_bound
Step 2: Repeat Steps 3 to 4 while I< = upper_bound
Step 3: Apply Process to A[I]
Step 4: SET I=I+1
[END OF Loop]
Step 5: EXIT

Explanation:
•Initialization: Set the loop counter I to the lower bound (starting index).
•Iteration: Continuously process each array element at A[I] while I <= upper_bound (end index),
incrementing I after each step.
•Completion: The loop ends when all elements are processed, and the program exits
• Example:
• #include <stdio.h>
• int main() {
• int arr[] = {10, 20, 30, 40, 50}; Output:
Array elements are:
• int n = sizeof(arr) / sizeof(arr[0]);
10 20 30 40 50

• printf("Array elements are:\n");


• for (int i = 0; i < n; i++) {
• printf("%d ", arr[i]);
• }
• return 0;
• }

You might also like