0% found this document useful (0 votes)
4 views23 pages

FYUGPModule 3

The document provides an overview of arrays in C programming, including one-dimensional, two-dimensional, and multidimensional arrays, along with their syntax, initialization, and element access. It also covers string handling in C, detailing string declaration, initialization, and common string functions like strlen, strcpy, strcat, and strcmp. Additionally, the document discusses functions in C, including user-defined functions, their types, and examples of function prototypes, definitions, and calls.

Uploaded by

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

FYUGPModule 3

The document provides an overview of arrays in C programming, including one-dimensional, two-dimensional, and multidimensional arrays, along with their syntax, initialization, and element access. It also covers string handling in C, detailing string declaration, initialization, and common string functions like strlen, strcpy, strcat, and strcmp. Additionally, the document discusses functions in C, including user-defined functions, their types, and examples of function prototypes, definitions, and calls.

Uploaded by

sutheeshs881
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

MODULE: 4

ARRAYS

The array is a data structure in C programming, which can store a fixed-size


sequential collection of elements of the same data type.

For example, if you want to store ten numbers then instead of defining ten
variables, it's easy to define an array of 10 lengths.

In the C programming language, an array can be One-Dimensional, Two-


Dimensional and Multidimensional.

Syntax:

type arrayName [ size ];

Example:

double amount[5];

Array initialization:

Arrays can be initialized at declaration time:

int age[5]={22,25,30,32,35};

0 1 2 3 4

22 25 30 32 35
age

Accessing array elements:

int myArray[5];

int n = 0;
// Initializing elements of array seperately

for(n=0;n<sizeof(myArray);n++)

myArray[n] = n;

int a = myArray[3]; // Assigning 3rd element of array value to integer 'a'.

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. However, 2D arrays are created to implement a relational database
lookalike data structure. 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];
Example:

• int twodimen[4][3];

Here, 4 is the number of rows, and 3 is the number of columns.


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.
#include<stdio.h>
int main(){
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++){
for(j=0;j<3;j++){
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}//end of j
}//end of i
return 0;
}
OUTPUT:
arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

Multi Dimensional Array:

A multidimensional array is declared using the following syntax:


type array_name[d1][d2][d3][d4]………[dn];
Example:

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

void main()
{
int i, j, k;
int arr[3][3][3]=
{
{
{11, 12, 13},
{14, 15, 16},
{17, 18, 19}
},
{
{21, 22, 23},
{24, 25, 26},
{27, 28, 29}
},
{
{31, 32, 33},
{34, 35, 36},
{37, 38, 39}
},
};
clrscr();
printf(":::3D Array Elements:::\n\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
{
printf("%d\t",arr[i][j][k]);
}
printf("\n");
}
printf("\n");
}
getch();
}

STRING IN C
In C programming, the one-dimensional array of characters are called
strings, which is terminated by a null character '\0'.

String declaration:

char name[6];

String Initialization:

char name[6] = {'C', 'l', 'o', 'u', 'd', '\0'};


or
char name[] = "Cloud";

Memory representation of above example:

C L o u d \0

String Handling Functions:

Few commonly used string handling functions are

Function Work of Function


strlen HYPERLINK
"[Link]
Calculates the length of string
-programming/library-
function/strlen"()
strcpy HYPERLINK
"[Link]
Copies a string to another string
-programming/library-
function/strcpy"()
strcat HYPERLINK
"[Link]
Concatenates(joins) two strings
-programming/library-
function/strcat"()
strcmp HYPERLINK
"[Link]
Compares two string
-programming/library-
function/strcmp"()
strlwr() Converts string to lowercase
strupr() Converts string to uppercase

• Strlen() : The strlen() function calculates the length of a given string.

Example:

#include <stdio.h>
#include <string.h>
int main()
{
char a[20]="Program";
char b[20]={'P','r','o','g','r','a','m','\0'};
char c[20];
printf("Enter string: ");
gets(c);
printf("Length of string a = %d \n",strlen(a));
//calculates the length of string before null charcter.
printf("Length of string b = %d \n",strlen(b));
printf("Length of string c = %d \n",strlen(c));
return 0;
}
OUTPUT:
Enter string: String

Length of string a = 7

Length of string b = 7

Length of string c = 6
• Strcat()

The function strcat() concatenates two strings. It takes two arguments, i.e,
two strings or character arrays, and stores the resultant concatenated string in the
first string specified in the argument.

Example:

#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "This is ", str2[] = "[Link]";
//concatenates str1 and str2 and resultant string is stored in str1.
strcat(str1,str2);
puts(str1);
puts(str2);
return 0;
}
OUTPUT: This is [Link]

[Link]

• strcmp()
The strcmp() function compares two strings and returns 0 if both strings are
identical. The strcmp() function takes two strings and return an integer.

The strcmp() compares two strings character by character. If the first


character of two strings are equal, next character of two strings are compared. This
continues until the corresponding characters of two strings are different or a null
character '\0' is reached.
Return Value Remarks
0 if both strings are identical (equal)
if the ASCII value of first unmatched character is less than
Negative
second.
positive if the ASCII value of first unmatched character is greater than
integer second.

Example:

#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";
int result;
// comparing strings str1 and str2
result = strcmp(str1, str2);
printf("strcmp(str1, str2) = %d\n", result);
// comparing strings str1 and str3
result = strcmp(str1, str3);
printf("strcmp(str1, str3) = %d\n", result);
return 0;
}
OUTPUT:
strcmp(str1, str2) = 32

strcmp(str1, str3) = 0

The first unmatched character between string str1 and str2 is third character.
The ASCII value of 'c' is 99 and the ASCII value of 'C' is 67. Hence, when
strings str1 and str2 are compared, the return value is 32. When
strings str1 and str3 are compared, the result is 0 because both strings are identical.

• strcpy()
The strcpy() function copies the string to the another character array.
The strcpy() function copies the string pointed by source (including the null
character) to the character array destination.

Example:

#include <stdio.h>
#include <string.h>
int main()
{
char str1[10]= "awesome";
char str2[10];
char str3[10];
strcpy(str2, str1);
strcpy(str3, "well");
puts(str2);
puts(str3);
return 0;
}
Output:
awesome

well

FUNCTIONS IN C
C function is a self-contained block of statements that can be executed
repeatedly whenever we need it.

Benifits of using function:

• The function provides modularity.


• The function provides reusable code.
• In large programs, debugging and editing tasks is easy with the use of
functions.
• The program can be modularized into smaller parts.
• Separate function independently can be developed according to the needs.

There are two types of functions in C


1. Built-in(Library) Functions
• The system provided these functions and stored in the library. Therefore it is
also called Library Functions.
e.g. scanf(), printf(), strcpy, strlwr, strcmp, strlen, strcat etc.
• To use these functions, you just need to include the appropriate C header
files.
2. User Defined Functions These functions are defined by the user at the time of
writing the program.
Parts of function:
• Function Prototype (function declaration)
• Function Definition
• Function Call

1. Function Prototype
Syntax:

dataType functionName (Parameter List)

Example:
int addition();
• Function Definition
Syntax:
returnType functionName(Function arguments){
//body of the function
}
Example:
int addition()
{

}
• Calling a function:
Example:
#include<stdio.h>

/* function declaration */int addition();

int main()
{
/* local variable definition */ int answer;

/* calling a function to get addition value */ answer = addition();

printf("The addition of two numbers is: %d\n",answer);


return 0;
}

/* function returning the addition of two numbers */int addition()


{
/* local variable definition */ int num1 = 10, num2 = 5;
return num1+num2;
}
Output:
The addition of two numbers is: 15

C Function Arguments:

While calling a function, the arguments can be passed to a function in two


ways, Call by value and call by reference.

Type Description

Call by Value • The actual parameter is passed to a


function.
• New memory area created for the
passed parameters, can be used
only within the function.
• The actual parameters cannot be
modified here.
Call by Reference • Instead of copying variable;
an address is passed to function as
parameters.
• Address operator(&) is used in the
parameter of the called function.
• Changes in function reflect the
change of the original variables.

Call by value:

Example:

#include<stdio.h>

/* function declaration */int addition(int num1, int num2);

int main()
{
/* local variable definition */ int answer;
int num1 = 10;
int num2 = 5;

/* calling a function to get addition value */ answer =


addition(num1,num2);

printf("The addition of two numbers is: %d\n",answer);


return 0;
}

/* function returning the addition of two numbers */int addition(int a,int


b)
{
return a + b;
}

Output:
The addition of two numbers is: 15

Call by reference:

Example:

#include<stdio.h>

/* function declaration */int addition(int *num1, int *num2);

int main()
{
/* local variable definition */ int answer;
int num1 = 10;
int num2 = 5;

/* calling a function to get addition value */ answer =


addition(&num1,&num2);

printf("The addition of two numbers is: %d\n",answer);


return 0;
}

/* function returning the addition of two numbers */int addition(int *a,int


*b)
{
return *a + *b;
}

Output:
The addition of two numbers is: 15

Type of User-defined Functions in C

There can be 4 different types of user-defined functions, they are:


• Function with no arguments and no return value

• Function with no arguments and a return value

• Function with arguments and no return value

• Function with arguments and a return value

Below, we will discuss about all these types, along with program examples.
Function with no arguments and no return value

Such functions can either be used to display information or they are completely
dependent on user inputs.
Below is an example of a function, which takes 2 numbers as input from user, and
display which is the greater number.

#include<stdio.h>

void greatNum(); // function declaration


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

void greatNum() // function definition


{
int i, j;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
if(i > j) {
printf("The greater number is: %d", i);
}
else {
printf("The greater number is: %d", j);
}
}

Function with no arguments and a return value

We have modified the above example to make the function greatNum() return the
number which is greater amongst the 2 input numbers.

#include<stdio.h>

int greatNum(); // function declaration


int main()
{
int result;
result = greatNum(); // function call
printf("The greater number is: %d", result);
return 0;
}

int greatNum() // function definition


{
int i, j, greaterNum;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
if(i > j) {
greaterNum = i;
}
else {
greaterNum = j;
}
// returning the result
return greaterNum;
}

Function with arguments and no return value

We are using the same function as example again and again, to demonstrate that to
solve a problem there can be many different ways.
This time, we have modified the above example to make the
function greatNum() take two intvalues as arguments, but it will not be returning
anything.

#include<stdio.h>

void greatNum(int a, int b); // function declaration

int main()
{
int i, j;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
greatNum(i, j); // function call
return 0;
}

void greatNum(int x, int y) // function definition


{
if(x > y) {
printf("The greater number is: %d", x);
}
else {
printf("The greater number is: %d", y);
}
}

Function with arguments and a return value

This is the best type, as this makes the function completely independent of inputs
and outputs, and only the logic is defined inside the function body.
#include<stdio.h>
int greatNum(int a, int b); // function declaration
int main()
{
int i, j, result;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
result = greatNum(i, j); // function call
printf("The greater number is: %d", result);
return 0;
}
int greatNum(int x, int y) // function definition
{
if(x > y) {
return x;
}
else {
return y;
}
}

Nesting of Functions

C language also allows nesting of functions i.e to use/call one function


inside another function's body. We must be careful while using nested functions,
because it may lead to infinite nesting.

function1()
{
// function1 body here

function2();

// function1 body here


}

If function2() also has a call for function1() inside it, then in that case, it will
lead to an infinite nesting. They will keep calling each other and the program will
never terminate.
Lets consider that inside the main() function, function1() is called and its
execution starts, then inside function1(), we have a call for function2(), so the
control of program will go to the function2(). But as function2() also has a call to
function1() in its body, it will call function1(), which will again call function2(),
and this will go on for infinite times, until you forcefully exit from program
execution.

Variable scope in functions:

A scope is a region of the program, and the scope of variables refers to the
area of the program where the variables can be accessed after its declaration. In C
each and every variable defined in a scope. You can define scope as the section or
region of a program where a variable has its existence; moreover, that variable
cannot be used or accessed beyond that region.

In C programming, variable declared within a function is different from a


variable declared outside of a function. The variable can be declared in three
places. These are:

Position Type

Inside a function or a block. local variables


Out of all functions. Global variables

In the function parameters. Formal parameters

Local Variable:

Variables that are declared within the function block and can be used only
within the function is called local variables.

Example:

#include <stdio.h>

int main ()
{
/* local variable definition and initialization */ int x,y,z;

/* actual initialization */ x = 20;


y = 30;
z = x + y;

printf ("value of x = %d, y = %d and z = %d\n", x, y, z);

return 0;
}

Global Variable:

Global variables are defined outside a function or any specific block, in most
of the case, on the top of the C program. These variables hold their values all
through the end of the program and are accessible within any of the functions
defined in your program.

Any function can access variables defined within the global scope, i.e., its
availability stays for the entire program after being declared.
Example:

#include <stdio.h>

/* global variable definition */int z;

int main ()
{
/* local variable definition and initialization */ int x,y;

/* actual initialization */ x = 20;


y = 30;
z = x + y;

printf ("value of x = %d, y = %d and z = %d\n", x, y, z);

return 0;
}

C RECURSION

Recursion is a special way of nesting functions, where a function calls itself


inside it. We must have certain conditions in the function to break out of the
recursion, otherwise recursion will occur infinite times.
Syntax:

function1()
{
// function1 body
function1();
// function1 body
}

Example :Factorial

#include<stdio.h>
int factorial(int x); //declaring the function

void main()
{
int a, b;

printf("Enter a number...");
scanf("%d", &a);
b = factorial(a); //calling the function named factorial
printf("%d", b);
}

int factorial(int x) //defining the function


{
int r = 1;
if(x == 1)
return 1;
else
r = x*factorial(x-1); //recursion, since the function calls
itself

return r;
}

Passing array to function

Example:

#include <stdio.h>
void disp( char ch)
{
printf("%c ", ch);
}
int main()
{
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
for (int x=0; x<10; x++)
{
/* I’m passing each element one by one using subscript*/
disp (arr[x]);
}

return 0;
}

You might also like