Unit-3 CMP
Unit-3 CMP
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.
data_type array_name[rows][columns];
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}};
#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
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
56 10 30
34 21 34
45 56 78
int main() {
int values[5];
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.
#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0, average;
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
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:
Matrix subtraction:
Matrix multiplication:
#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]);
}
Output
return 0;
}
Output
#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];
if (n != p)
printf(“\nThe matrices can’t be multiplied with each other.\n”);
else
{
printf(“\nEnter elements of matrix2\n”);
Output
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.
Example1
#include <stdio.h>
void my_function() {
printf("This is a function that takes no argument, and returns nothing.");
}
main() {
my_function();
}
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 () {
return 0;
}
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");
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>
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;
}