C Programming Unit 3
C Programming Unit 3
Functions
By
Dr.Sreeparna C
Syllabus
Arrays - One dimensional array; Linear search ; Bubble sort;
Two dimensional array.
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
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>
#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.
Output:
o
Handling of character strings: Arithmetic
operations on characters
#include <stdio.h>
void main()
{
char a = 'A';
char 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);
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);
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";
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";
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);
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
• 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.
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
• 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
(argument list);
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
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
// 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>
int main()
{
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}
Nesting of Functions
#include <stdio.h>
void print(int c) {
printf(“Sum: %d\n”, c);
}
void main() {
int result;
// Calling the add function inside main function
add(5, 10);
}
Recursion
• 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>
void main() {
int numbers[] = {1, 2, 3, 4, 5};
int size = sizeof(numbers) / sizeof(numbers[0]);