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

C Programming Unit 3

Uploaded by

akashtj.y
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

C Programming Unit 3

Uploaded by

akashtj.y
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

Unit 3: Arrays and

Functions

By
Dr.Sreeparna C
Syllabus
Arrays - One dimensional array; Linear search ; Bubble sort;
Two dimensional array.

Handling of character strings - Declaring and initializing string


variables; Reading string from terminal; Writing string to
screen; Arithmetic operations on characters; String handling
functions.

Functions - Need for user defined functions; Writing functions


in C; Return statement; Calling a function; Category of
functions; Nesting of functions; Recursion; Functions with
arrays.
Storage Classes in C:automatic; static; external and register
C Array
• An array is defined as the collection of similar type of
data items stored at contiguous memory locations.

• Arrays are the derived data type in C programming


language which can store the primitive type of data such
as int, char, double, float, etc.

• The array is the simplest data structure where each data


element can be randomly accessed by using its index
number.
ARRAYS
▪ An array is a collection of elements of the same type that are
referenced by a common name.

▪ Compared to the basic data type (int, float) it is an


aggregate or derived data type.

▪ All the elements of an array occupy a set of contiguous


memory locations.

▪ Why need to use array type?

▪ Consider the following issue:

 "We have a list of 1000 students' marks of an


integer type. If using the basic data type
(int), we will declare something like the
following…"

 int studMark0, studMark1, ...studMark999


▪ Ca n you imagine how long we have to
write the declaration part by using
normal variable declaration?

int main(void)
{
int studMark1, studMark2, studMark3,
studMark4, …, …, studMark998, stuMark999,
studMark1000;


return 0;
}
▪ By using an array, we just declare like this,

 int studMark[1000];
▪ This will reserve 1000 contiguous memory locations for
storing the students’ marks.
▪ Graphically, this can be depicted as in the following
figure.
Declaration of C Array

• We can declare an array in the c language in the following


way:
data_type array_name[array_size];

• Now, let us see the example to declare the array.


int marks[5];
Initialization of C Array
• The simplest way to
initialize an array is by
using the index of each
element.
• We can initialize each
element of the array by
using the index.
• Consider the following
example.
marks[0]=80;
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
#include <stdio.h>
void main(){
int i, marks[5];
printf("Enter marks for students:\n”);
for(i = 0; i < 5; i++){
scanf("%d", &marks[i]); // storing input in the array
}

// Traversal of array and printing the values


printf("\nThe entered marks are:\n");
for(i = 0; i < 5; i++){
Enter marks for students:
printf("%d \n", marks[i]);
21389
}
}
The entered marks are:
2
1
3
8
9
C Array: Declaration with Initialization

• We can initialize the C array at the time of declaration.


Let's see the code:
int marks[5]={20,30,40,50,60};

• In such case, there is no requirement to define the


size.
• So it may also be written as the following code:
int marks[]={20,30,40,50,60};
Two Dimensional Array in C

• The two-dimensional array can be defined as an array of


arrays.
• The 2D array is organized as matrices which can be
represented as the collection of rows and columns.
• It provides ease of holding the bulk of data at once which
can be passed to any number of functions wherever
required.
Declaration of two dimensional Array in C

• The syntax to declare the 2D array is given below.


data_type array_name[rows][columns];
Consider the following example:
int twodimen[4][3];
Initialization of 2D Array in C
• In the 1D array, we don't need to specify the size of the
array if the declaration and initialization are being
done simultaneously.
• However, this will not work with 2D arrays.
• We will have to define at least the second dimension of
the array.

• The two-dimensional array can be declared and


defined in the following way:
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
OR
int arr[][3] = {{1, 2, 3}, {2, 3, 4}, {3, 4, 5}, {4, 5, 6}};
#include <stdio.h>
void main() {
int i, j, arr[4][3]; // Declaration of the array
printf("Enter value for arr:”);
for (i = 0; i < 4; i++) {
for (j = 0; j < 3; j++) {
scanf("%d", &arr[i][j]); // Input each element
}
}

// Traversing and displaying the 2D array


printf("Array elements are:\n");
for (i = 0; i < 4; i++) {
for (j = 0; j < 3; j++) {
printf("arr[%d][%d] = %d \n", i, j, arr[i][j]);
}
}
}
Linear Search Algorithm
• The linear search algorithm is defined as a sequential
search algorithm that starts at one end and goes
through each element of a list until the desired element
is found; otherwise, the search continues till the end of
the dataset.
Linear Search Algorithm
Linear Search Algorithm

START
Step1: Begin at the first element of the collection of
elements.
Step2: Compare the current element with the desired
element.
Step3: If the current element is equal to the desired
element, return true or index to the current element,
otherwise, move to the next element in the collection.
Step4: Repeat steps 2-4 until we have reached the end of
collection.
Step5: If the end of the collection is reached without
finding the desired element, return that the desired
element is not in the array.
STOP
Linear Search Algorithm
#include <stdio.h>
void main()
{
int array[100], search, i, n;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d integer(s)\n", n);
for (i = 0; i < n; i++)
scanf("%d", &array[i]);
printf("Enter a number to search\n");
scanf("%d", &search);
for (i = 0;i < n; i++)
{
if (array[i] == search)
{
printf("%d is present at location %d.\n", search,i+1);
break;
}
}
if (i == n)
printf("%d isn't present in the array.\n", search);
}
Bubble Sort Algorithm
• Bubble Sort is the simplest sorting algorithm that works
by repeatedly swapping the adjacent elements if they
are in the wrong order.
• This algorithm is not suitable for large data sets.
Bubble Sort Algorithm
Bubble Sort Algorithm

• START
• Step1: Begin from the start of the list or array.
• Step2: Compare the first two elements. If the first is bigger
than the second, swap them.
• Step3: If not, leave them as they are.
• Step4: Move to the next pair of elements and repeat the
comparison and swap if needed.
• Step5: Repeat Step 2-4 until you reach the end of the list. At
this point, the largest number will be at the end.
• Step6: Repeat Step 1-5 but ignore the last element, since
it's already in the correct place. Move the next largest number
to its correct position at the end with each pass.
• The process ends when all the elements from 2nd to last are at
correct places.
• STOP
Bubble Sort Algorithm
#include <stdio.h>

void bubbleSort(int arr[], int n) {


Int I,j,temp;
for (i = 0; i < n-1; i++)
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1]) {
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
void main() {
int arr[] = {5, 1, 4, 2};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
Handling of character strings - Declaring and
initializing string variables
• In C, strings are essentially arrays of characters terminated by a null
character ('\0’).
• Here's how you can declare and initialize string variables:
• Declaring and Initializing String Variables:
• Using Character Arrays:
• You can declare a string as an array of characters, with an explicit size
or implicit size based on the initialization.
• The string must always end with a null character ('\0'), which indicates
the end of the string.
• char str1[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Explicitly adding '\0'
• char str2[] = "Hello"; // Automatically adds '\0' at the end
Handling of character strings - Reading string
from terminal
Reading strings from the terminal can be done using a few common
functions, depending on how you want to handle input.
Here are some ways to do this:
1. Using scanf:
•“scanf” is used to read input from the terminal.
•For strings, it automatically adds the null terminator ('\0') at the end.

#include <stdio.h>
void main() {
char str[100]; // Allocate enough space for the string
printf("Enter a string: ");
scanf("%s", str); // Reads input until the first space
printf("You entered: %s\n", str);
}
Handling of character strings Reading string
from terminal
2. Using gets:
•gets reads an entire line of input, including space.

Example:
#include <stdio.h>
void main() {
char str[100];
printf("Enter a string: ");
gets(str);
printf("You entered: %s\n", str);
}
Handling of character strings Writing string to
screen
1. Using printf:
•The printf function is used to output formatted text to the terminal.
•When printing a string, %s format specifier is used.

#include <stdio.h>
void main() {
char str[] = "Hello, World!";
printf("%s\n", str); // Prints the string with a newline
}
Handling of character strings Writing string to
screen
2. Using puts:
•The puts function is a simple way to output a string.
•It automatically appends a newline character after printing the string.

#include <stdio.h>

void main() {
char str[] = "Hello, C programming!";
puts(str); // Prints the string followed by a newline
}
Handling of character strings: Arithmetic
operations on characters
Character arithmetic is used to implement arithmetic operations like
addition, subtraction, multiplication, and division on characters in C
language.
In character arithmetic character converts into an integer value to
perform the task. For this ASCII value is used.
It is used to perform actions on the strings.

// C program to demonstrate character arithmetic.


#include <stdio.h>
void main()
{
char ch1 = 125, ch2 = 10;
printf("%c\n", ch1 - ch2 - 4);
}

Output:
o
Handling of character strings: Arithmetic
operations on characters
#include <stdio.h>

void main()
{
char a = 'A';
char b = ‘!';

printf("a = %c\n", a);


printf("b = %c\n", b);
printf("a + b = %c\n", a + b);
}

Output
a=A
b=!
a+b=b
Handling of character strings: String handling
functions
• The C string functions are built-in functions that can be used for
various operations and manipulations on strings.
• These string functions can be used to perform tasks such as string
copy, concatenation, comparison, length, etc.
• The <string.h> header file contains these string functions.
Handling of character strings: String handling
functions
1. strcat() Function
The strcat() function in C is used for string concatenation. It will append
a copy of the source string to the end of the destination string.
char* strcat(char* dest, const char* src);

The terminating character at the end of dest is replaced by the first


character of src.
Parameters
•dest: Destination string
•src: Source string

Return value
•The strcat() function returns a pointer to the dest string.
Handling of character strings: String handling
functions
// C Program to illustrate the strcat function
#include <stdio.h>
#include <string.h>
void main()
{
char dest[50] = "This is an";
char src[50] = " example";
printf("dest Before: %s\n", dest);

// concatenating src at the end of dest


strcat(dest, src);
printf("dest After: %s", dest);
}

Output:
dest Before: This is an dest
After: This is an example
Handling of character strings: String handling
functions
2. strlen() Function
The strlen() function calculates the length of a given string. It doesn’t
count the null character ‘\0’.
Syntax
int strlen(const char *str);

Parameters
•str: It represents the string variable whose length we have to find.
[const qualifier means that the pointer str points to a string that cannot
be modified by the function strlen().In other words, strlen() is only
supposed to read the string, not change its contents.]
Return Value
•strlen() function in C returns the length of the string.
Handling of character strings: String handling
functions
// C program to demonstrate the strlen() function
#include <stdio.h>
#include <string.h>

int main()
{
char str[] = "GeeksforGeeks";

int length = strlen(str);

// Print the length of the string


printf("String: %s\n", str);

printf("Length: %d\n", length);

return 0;
}
Handling of character strings: String handling
functions
3. strcmp() Function
The strcmp() is a built-in library function in C. This function takes two
strings as arguments and compares these two strings
lexicographically.

Syntax
int strcmp(const char *str1, const char *str2);Parameters
•str1: This is the first string to be compared.
•str2: This is the second string to be compared.

Return Value
•If str1 is less than str2, the return value is less than 0.
•If str1 is greater than str2, the return value is greater than 0.
•If str1 is equal to str2, the return value is 0.
Handling of character strings: String handling
functions
// C program to demonstrate the strcmp() function
#include <stdio.h>
#include <string.h>

void main()
{
char str1[] = "Geeks";
char str2[] = "For";

int result1 = strcmp(str1, str2);

printf("Comparison of str1 and str2: %d\n", result1);

return;
}
Handling of character strings: String handling
functions
4. stcpy()
The strcpy() is a standard library function in C and is used to copy one
string to another. In C, it is present in <string.h>header file.
Syntax
char* strcpy(char* dest, const char* src);Parameters
•dest: Pointer to the destination array where the content is to be
copied.
•src: string which will be copied.
Return Value
•strcpy() function returns a pointer pointing to the output string.
Handling of character strings: String handling
functions
// C program to illustrate the use of strcpy()
#include <stdio.h>
#include <string.h>

int main()
{
char source[] = ”C";
char dest[20];

strcpy(dest, source);

printf("Source: %s\n", source);


printf("Destination: %s\n", dest);

return 0;
}
Unit 3- Function
A function is a block of code that performs a specific task.
Suppose, you need to create a program to create a circle and color it. You can create two functions to
solve this problem:
•create a circle function
•create a color function
Dividing a complex problem into smaller chunks makes our program easy to understand and reuse.

Definition

In c, we can 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. In other
words, we can say that 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

There are the following advantages of C functions.

• 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.


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 that 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.
Types of Functions
There are two types of functions in C programming:
Library Functions or Predefined function: 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.
SN C function aspects Syntax

1 Function declaration return_type function_name

(argument list);

2 Function call function_name (argument_list)

3 Function definition return_type

function_name (argument list) {function body;}

Return Value

A C function may or may not return a value from the function. If you don't have to
return any value from the function, use void for the return type
Predefined Functions

So it turns out you already know what a function is. You have been using it the whole time. For
example, main() is a function, that is used to execute code, and printf() is a function; used to
output/print text to the screen:

Example
#include <stdio.h>

int main()
{
printf("Hello World!");
return 0;
}
Create a Function

To create (often referred to as declare) your own function, specify the name of the

function, followed by parentheses () and curly brackets {}:


Syntax

void myFunction()

// code to be executed
Example Explained
}
myFunction() is the name of the function
void means that the function does not have a return value.
Inside the function (the body), add code that defines what the function should do
Call a Function

Declared functions are not executed immediately. They are "saved for later use", and will
be executed when they are called.
To call a function, write the function's name followed by two parentheses () and a
semicolon ;

In the following example, myFunction() is used to print a text (the action), when it is
called
A function can be called multiple times

#include <stdio.h> #include <stdio.h>


// Create a function
// Create a function void myFunction()
void myFunction() {
{ printf("I just got executed!\n");
printf("I just got executed!"); }
}
int main()
int main() {
{ myFunction(); // call the function
myFunction(); // call the function myFunction(); // call the function
return 0; myFunction(); // call the function
} return 0;
#include <stdio.h>

// Create a function
void calculateSum()
{
int x = 5;
int y = 10;
int sum = x + y;
printf("The sum of x + y is: %d", sum);
}

int main()
{
calculateSum(); // call the function
return 0;
}
C Function Parameters
Parameters and Arguments
Information can be passed to functions as a parameter. Parameters act as variables inside
the function.
Parameters are specified after the function name, inside the parentheses. You can add as
many parameters as you want, just separate them with a comma:
Syntax #include <stdio.h>

returnType functionName(parameter1, void myFunction(char name[], int


parameter2, parameter3) age)
{ {
// code to be executed printf("Hello %s. You are %d years
} old\n", name, age);
}

int main()
{
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}
Nesting of Functions

• In C programming, nesting of functions refers to the practice of calling one function


from within another function.
• However, in C, function declarations cannot be nested, meaning you can't define one
function inside the body of another.
• But you can call a function from within another function.
• This structure is useful to divide code into reusable chunks, making it easier to
maintain and debug.
Nesting of Functions

#include <stdio.h>
void print(int c) {
printf(“Sum: %d\n”, c);
}

void add(int a, int b) { Output


int c = a + b; Sum: 15
print(c);
}

void main() {
int result;
// Calling the add function inside main function
add(5, 10);
}
Recursion

• Recursion in C refers to a function calling itself in order to solve a problem.


• It is a powerful tool for solving problems that can be broken down into smaller,
similar problems.
• A recursive function has a base case (to stop the recursion) and a recursive case
(where the function calls itself).

• Base Case: This defines the condition under which the recursion stops.
• Recursive Case: This is where the function calls itself to continue the process.
Recursion

#include<stdio.h>
#include<conio.h>
long int multiplyNumbers(int n);
void main() {
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
}
long int multiplyNumbers(int n) {
if (n>=1)
return n*multiplyNumbers(n-1);
else
return 1;
}
Functions and arrays

• In C, functions can accept arrays as parameters, allowing for passing large amounts
of data to a function.
• When you pass an array to a function, what actually gets passed is the pointer to the
first element of the array.
• Therefore, any modifications made to the array inside the function are reflected
outside the function as well.
• Array names are pointers: When you pass an array to a function, you are passing
the memory address of the first element of the array.
• Array size: The size of the array is not passed to the function, so you should also
pass the array size explicitly if needed.
• Multidimensional arrays: You can also pass multidimensional arrays to functions,
though you need to specify all but the first dimension.
Functions and arrays

#include <stdio.h>

// Function to print array elements


void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

void main() {
int numbers[] = {1, 2, 3, 4, 5};
int size = sizeof(numbers) / sizeof(numbers[0]);

printf("Original array: ");


printArray(numbers, size);
}

You might also like