0% found this document useful (0 votes)
10 views21 pages

Unit-3 CMP

The document explains the concept of two-dimensional arrays in C, detailing their declaration, initialization, and basic operations such as input/output and matrix arithmetic. It provides examples of how to create, traverse, and manipulate 2D arrays, along with user-defined functions for various tasks. Additionally, it covers function definitions, declarations, and return types in C programming.

Uploaded by

Dr. Salma
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)
10 views21 pages

Unit-3 CMP

The document explains the concept of two-dimensional arrays in C, detailing their declaration, initialization, and basic operations such as input/output and matrix arithmetic. It provides examples of how to create, traverse, and manipulate 2D arrays, along with user-defined functions for various tasks. Additionally, it covers function definitions, declarations, and return types in C programming.

Uploaded by

Dr. Salma
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/ 21

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

Consider the following 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.

int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};

Two-dimensional array example in C

#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

C 2D array example: Storing elements in a matrix and printing it.

1. #include <stdio.h>
2. void main ()
3. {
4. int arr[3][3],i,j;
5. for (i=0;i<3;i++)
6. {
7. for (j=0;j<3;j++)
8. {
9. printf("Enter a[%d][%d]: ",i,j);
10. scanf("%d",&arr[i][j]);
11. }
12. }
13. printf("\n printing the elements ....\n");
14. for(i=0;i<3;i++)
15. {
16. printf("\n");
17. for (j=0;j<3;j++)
18. {
19. printf("%d\t",arr[i][j]);
20. }
21. }
22. }

Output

Enter a[0][0]: 56
Enter a[0][1]: 10
Enter a[0][2]: 30
Enter a[1][0]: 34
Enter a[1][1]: 21
Enter a[1][2]: 34

Enter a[2][0]: 45
Enter a[2][1]: 56
Enter a[2][2]: 78

printing the elements ....

56 10 30
34 21 34
45 56 78

Input and Output Array Elements


Here's how you can take input from the user and store it in an array element.

// take input and store it in the 3rd element


scanf("%d", &mark[2]);

// take input and store it in the ith element


scanf("%d", &mark[i-1]);

Here's how you can print an individual element of an array.

// print the first element of the array


printf("%d", mark[0]);

// print the third element of the array


printf("%d", mark[2]);

// print ith element of the array


printf("%d", mark[i-1]);

Example 1: Array Input/Output


// Program to take 5 values from the user and store them in an array
// Print the elements stored in the array
#include <stdio.h>

int main() {
int values[5];

printf("Enter 5 integers: ");

// taking input and storing it in an array


for(int i = 0; i < 5; ++i) {
scanf("%d", &values[i]);
}

printf("Displaying integers: ");

// printing elements of an array


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

Output

Enter 5 integers: 1
-3
34
0
3
Displaying integers: 1
-3
34
0
3

Here, we have used a for loop to take 5 inputs from the user and store them in an array. Then,
using another for loop, these elements are displayed on the screen.

Example 2: Calculate Average


// Program to find the average of n numbers using arrays

#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0, average;

printf("Enter number of elements: ");


scanf("%d", &n);

for(i=0; i<n; ++i)


{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);

// adding integers entered by the user to the sum variable


sum += marks[i];
}

average = sum/n;
printf("Average = %d", average);

return 0;
}

Output

Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39

Here, we have computed the average of n numbers entered by the user.

Program to perform matrix addition, matrix


subtraction, matrix multiplication
Programs to perform all the basic Matrix operations like Matrix addition, matrix subtraction,
matrix multiplication are discussed here.

Matrix Addition
mat1 = {{1, 2}, {3, 4}}mat2 = {{1, 2}, {3, 4}}mat1 + mat2 = {{2, 4}, {6, 8}}

Matrix Subtraction
mat1 = {{1, 2}, {3, 4}}mat2 = {{1, 2}, {3, 4}}mat1 - mat2 = {{0, 0}, {0, 0}}

Matrix Multiplication
mat1 = {{1, 2}, {3, 4}}mat2 = {{1, 2}, {3, 4}}mat1 * mat2 = {{7, 10}, {15, 22}}
Algorithm to perform matrix addition, matrix subtraction,
matrix multiplication
Matrix addition:

1. Input the order of the matrix.


2. Input the matrix 1 elements.
3. Input the matrix 2 elements.
4. Repeat from i = 0 to m
5. Repeat from j = 0 to n
6. mat3[i][j] = mat1[i][j] + mat2[i][j]
7. Print mat3.

Matrix subtraction:

1. Input the order of the matrix.


2. Input the matrix 1 elements.
3. Input the matrix 2 elements.
4. Repeat from i = 0 to m
5. Repeat from j = 0 to n
6. mat3[i][j] = mat1[i][j] - mat2[i][j]
7. Print mat3.

Matrix multiplication:

1. Input the order of the matrix1 ( m * n).


2. Input the order of matrix2 (p * q).
3. Input the matrix 1 elements.
4. Input the matrix 2 elements.
5. Repeat from i = 0 to m
6. Repeat from j = 0 to q
7. repeat from k = 0 to p
8. sum=sum+ mat1[c][k] * mat2[k][d];
9. mat3[c][d]=sum
10. Print mat3.
Program to perform matrix operations | Matrix addition

#include <stdio.h>
int main()
{
//fill your code
int m, n;
scanf(“%d %d”,&m,&n);
int i, j;
int mat1[m][n], mat2[m][n], mat3[m][n];
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
scanf(“%d”,&mat1[i][j]);
}
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
scanf(“%d”,&mat2[i][j]);
}

for(i = 0; i < m; i++)


{
for(j = 0; j < n; j++)
{
mat3[i][j] = mat1[i][j] + mat2[i][j];
}
}
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
printf(“%d “, mat3[i][j]);
printf(“\n”);
}
return 0;
}

Output

2 2 (order of the matrix)


1 2 3 4 (matrix 1 elements)
2 3 4 5 (matrix 2 elements)
3 5 (resultant matrix)
79
Program to perform basic matrix operations | Matrix
Subtraction
#include <stdio.h>
int main()
{
int m, n;
scanf(“%d %d”,&m,&n);
int i, j;
int mat1[m][n], mat2[m][n], mat3[m][n];
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
scanf(“%d”,&mat1[i][j]);
}
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
scanf(“%d”,&mat2[i][j]);
}

for(i = 0; i < m; i++)


{
for(j = 0; j < n; j++)
{
mat3[i][j] = mat1[i][j] – mat2[i][j];
}
}

for(i = 0; i < m; i++)


{
for(j = 0; j < n; j++)
printf(“%d “, mat3[i][j]);
printf(“\n”);
}

return 0;
}

Output

2 2 (order of the matrix)


5 6 7 8 (matrix 1 elements)
1 2 3 4 (matrix 2 elements)
4 4 (resultant matrix)
44
Program to perform basic matrix operations | Matrix
multiplication

#include <stdio.h>

int main()
{
int m, n, p, q, c, d, k, sum = 0;
int mat1[10][10], mat2[10][10], mat3[10][10];

printf(“Enter number of rows and columns of mat1 matrix\n”);


scanf(“%d%d”, &m, &n);
printf(“Enter elements of matrix 1\n”);

for (c = 0; c < m; c++)


for (d = 0; d < n; d++)
scanf(“%d”, &mat1[c][d]);

printf(“\nEnter number of rows and columns of mat2 matrix\n”);


scanf(“%d%d”, &p, &q);

if (n != p)
printf(“\nThe matrices can’t be multiplied with each other.\n”);
else
{
printf(“\nEnter elements of matrix2\n”);

for (c = 0; c < p; c++)


for (d = 0; d < q; d++)

Output

Enter number of rows and columns of mat1 matrix


22
Enter elements of matrix 1
2345
Enter number of rows and columns of mat2 matrix
22
Enter elements of matrix 2
1234
Product of the matrices:
11 16
19 28
User Defined Functions
A function is a group of statements that together perform a task. Every C program has at least
one function, which is main(), and all the most trivial programs can define additional functions.
You can divide up your code into separate functions. How you divide up your code among
different functions is up to you, but logically the division is such that each function performs a
specific task.
A function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function.
The C standard library provides numerous built-in functions that your program can call. For
example, strcat() to concatenate two strings, memcpy() to copy one memory location to another
location, and many more functions.
A function can also be referred as a method or a sub-routine or a procedure, etc.

Defining a Function
The general form of a function definition in C programming language is as follows −
return_type function_name( parameter list ) {
body of the function
}
A function definition in C programming consists of a function header and a function body. Here
are all the parts of a function −
 Return Type − A function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.
 Function Name − This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
 Parameters − A parameter is like a placeholder. When a function is invoked, you pass a
value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.
 Function Body − The function body contains a collection of statements that define what
the function does.
Function Declarations
A function declaration tells the compiler about a function name and how to call the function.
The actual body of the function can be defined separately.
A function declaration has the following parts −
return_type function_name( parameter list );
For the above defined function max(), the function declaration is as follows −
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so the
following is also a valid declaration −
int max(int, int);
Function declaration is required when you define a function in one source file and you call that
function in another file. In such case, you should declare the function at the top of the file calling
the function.

Return Values and their Types


A function either can take some arguments, or nothing is taken. Similarly, a function can return
something, otherwise does not return anything. So we can categorize them into four types.
 Function with No argument and No return type.
 Function with No argument and Return something.
 A function that takes argument but returns nothing.
 Functions that take an argument and also return something.

Example1
#include <stdio.h>
void my_function() {
printf("This is a function that takes no argument, and returns nothing.");
}
main() {
my_function();
}

Output: This is a function that takes no argument, and returns nothing.


Here this function is not taking any input argument, and also the return type is void. So this
returns nothing.

Example2
#include <stdio.h>
int my_function() {
printf("This function takes no argument, But returns 50\n");
return 50;
}
main() {
int x;
x = my_function();
printf("Returned Value: %d", x);
}

Output
This function takes no argument, But returns 50
Returned Value: 50

Here this function is not taking any input argument, but its return type is int. So this returns a
value.

Example3
#include <stdio.h>
void my_function(int x) {
printf("This function is taking %d as argument, but returns nothing", x);
return 50;
}
main() {
int x;
x = 10;
my_function(x);
}

Output
This function is taking 10 as argument, but returns nothing

Here this function is taking an input argument, but its return type is void. So this returns nothing.
Example4
#include <stdio.h>
int my_function(int x) {
printf("This will take an argument, and will return its squared value\n");
return x * x;
}
main() {
int x, res;
x = 12;
res = my_function(12);
printf("Returned Value: %d", res);
}

Output
This function is taking 10 as argument, but returns nothing

Here this function is taking any input argument, and also returns value.

Calling a Function
While creating a C function, you give a definition of what the function has to do. To use a
function, you will have to call that function to perform the defined task.
When a program calls a function, the program control is transferred to the called function. A
called function performs a defined task and when its return statement is executed or when its
function-ending closing brace is reached, it returns the program control back to the main
program.
To call a function, you simply need to pass the required parameters along with the function
name, and if the function returns a value, then you can store the returned value.

Example

#include <stdio.h>

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

int main () {

/* local variable definition */


int a = 100;
int b = 200;
int ret;
/* calling a function to get max value */
ret = max(a, b);

printf( "Max value is : %d\n", ret );

return 0;
}

/* function returning the max between two numbers */


int max(int num1, int num2) {

/* local variable declaration */


int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}
We have kept max() along with main() and compiled the source code. While running the final
executable, it would produce the following result −
Max value is : 200

Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.
Formal parameters behave like other local variables inside the function and are created upon
entry into the function and destroyed upon exit.
While calling a function, there are two ways in which arguments can be passed to a function −
Sr.No. Call Type & Description
Call by value
This method copies the actual value of an argument into the formal parameter of the
1
function. In this case, changes made to the parameter inside the function have no effect
on the argument.
Call by reference
2 This method copies the address of an argument into the formal parameter. Inside the
function, the address is used to access the actual argument used in the call. This means
that changes made to the parameter affect the argument.
By default, C uses call by value to pass arguments. In general, it means the code within a
function cannot alter the arguments used to call the function.

Category of Functions
There are basically two types of functions:
Library functions Ex. printf( ), scanf( ), etc.
User-defined functions Ex. argentina( ), brazil( ), etc.
As the name suggests, library functions are nothing but commonly required functions grouped
together and stored in a Library file on the disk. These library of functions come ready-made with
development environments like Turbo C, Visual Studio, NetBeans, gcc, etc. The procedure for calling
both types of functions is exactly same.

Nesting of Functions
Some programmer thinks that defining a function inside an another function is known as “nested
function”. But the reality is that it is not a nested function, it is treated as lexical scoping. Lexical
scoping is not valid in C because the compiler cant reach/find the correct memory location of the
inner function.
Nested function is not supported by C because we cannot define a function within another
function in C. We can declare a function inside a function, but it’s not a nested function.
Because nested functions definitions can not access local variables of the surrounding blocks,
they can access only global variables of the containing module. This is done so that lookup of
global variables doesn’t have to go through the directory. As in C, there are two nested scopes:
local and global (and beyond this, built-ins). Therefore, nested functions have only a limited use.
If we try to approach nested function in C, then we will get compile time error.
// C program to illustrate the
// concept of Nested function.
#include <stdio.h>
int main(void)
{
printf("Main");
int fun()
{
printf("fun");

// defining view() function inside fun() function.


int view()
{
printf("view");
}
return 1;
}
view();
}
Output:
Compile time error: undefined reference to `view'
An extension of the GNU C Compiler allows the declarations of nested functions. The
declarations of nested functions under GCC’s extension need to be prefix/start with the auto
keyword.
// C program of nested function
// with the help of gcc extension
#include <stdio.h>
int main(void)
{
auto int view(); // declare function with auto keyword
view(); // calling function
printf("Main\n");

int view()
{
printf("View\n");
return 1;
}

printf("GEEKS");
return 0;
}
Output:
view
Main
GEEKS

Recursion
In C, it is possible for the functions to call themselves. A function iscalled ‘recursive’ if a
statement within the body of a function calls the same function. Sometimes called ‘circular
definition’, recursion is thus the process of defining something in terms of itself.
Recursion is the process of repeating items in a self-similar way. In programming languages, if a
program allows you to call a function inside the same function, then it is called a recursive call of
the function.
void recursion() {
recursion(); /* function calls itself */
}

int main() {
recursion();
}
The C programming language supports recursion, i.e., a function to call itself. But while using
recursion, programmers need to be careful to define an exit condition from the function,
otherwise it will go into an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as calculating
the factorial of a number, generating Fibonacci series, etc.

Number Factorial
The following example calculates the factorial of a given number using a recursive function −
Live Demo
#include <stdio.h>

unsigned long long int factorial(unsigned int i) {

if(i <= 1) {
return 1;
}
return i * factorial(i - 1);
}

int main() {
int i = 12;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}
When the above code is compiled and executed, it produces the following result −
Factorial of 12 is 479001600

ANSI C Functions
The American National Standards Institute oversees standards and conformity assessment
activities in the United states.
ANSI's mission is to enhance both the global competitiveness of U.S. business and the U.S.
quality of life by promoting and facilitating voluntary consensus standards and conformity
assessment systems, and safeguarding their integrity.
ANSI C is the standards for the C programming language published by the American National Standards
Institute (ANSI). Software developers writing in C are encouraged to conform to the standards, as doing
so helps portability between compilers.

ANSI C provides function prototypes. This allows the compiler to check the type and number of
arguments to functions, and avoids default argument promotions. To prototype functions, declare
the type and name of each function in the function definition. Then provide a prototype
declaration (including at least the types) before the function is called.

The prototype and data definitions of these functions are present in their respective header files.
To use these functions we need to include the header file in our program. For example,

If you want to use the printf() function, the header file <stdio.h> should be included.

#include <stdio.h>
int main()
{
printf("Catch me if you can.");
}

If you try to use printf() without including the stdio.h header file, you will get an error.
Function Declaration in C
A function (method) is a block of code that can be called from another location in the program or
class. It is used to reduce the repetition of multiple lines of code.

Syntax
returnType functionName(parameterTypes); //function prototype
//main code
returnType functionName (functionParameters) { //function implementation
//statements that execute when called
return value;
}

In any version ANSI C and above, a function prototype should be declared. This ensures the
correct number and type of input parameters for the function in main.
Function Name is defined by the programmer, returnType is the data type returned from calling
the function (void if no return). functionParameters are the inputs needed for the function to
execute. Parameters are defined as: (dataType parameterName), which is the data type of the
input parameter and the name of the parameter as seen within the function. There can be multiple
parameters seperated by a comma.

Example
int findMaximum(int, int); //prototype
void main(){
int maxNumber = findMaximum(5, 7); //calling a function
}
int findMaximum(int number1, int number2) { //implementation
int maximum = number2;
if (number1 > number2) maximum = number1;
return maximum;
}

You might also like