SlideShare a Scribd company logo
Module 3
Function
It is a building block that contains set of programming statements to
perform a particular task.
Aspects of the 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 which 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.
Function Declaration
Syntax:
return-type function-name(datatype1 parameter1,
parameter2,................, datatype n parameter n);
Ex: int sum (int a, int b);
float sum (float a, float b);
datatype2
int mul (int a, int b, int c);
Function Call
Syntax:
function-name (parameter1,parameter2, ........... ,parameter n);
Ex: sum (a, b);
sum (a, b);
mul (a, b, c);
Function Definition
Syntax:
return-type function-name(datatype1 parameter1,
parameter2,................, datatype n parameter n)
{
Statements;
}
datatype2
Ex:
int sum (int a, int b)
{
Variable declaration;
Input statement;
Processing statements;
Output statements;
}
Function Body
Function Return value
--If the function doesn’t return any value, then the return type can be
mentioned as ‘void’.
Example:
void show()
{
printf(“Hello”);
}
--If the function return any specific value, then the corresponding
datatype can be mentioned as the return type can be mentioned such
as int, float, char, double etc.
int get()
{
return 5;
}
float get()
{
return 5.5;
}
char get()
{
return ‘c’;
}
Function Type
Two types of functions:
• Library Function
The functions which are already defined in C library/header files.
Example: printf(), scanf(), gets(), puts(), getchar(), putchar(), sqrt(),
pow(), tolower(), toupper(), islower(), isupper()
• User Defined Function
The functions which are created by the programmer.
These functions must be declared before usage.
These functions’ definition must be written by the programmer.
Function Declaration, Call, Definition Example:
#include<stdio.h>
int sum(int a, int b);
int main()
{
int a,b,result;
printf("nEnter two numbers:");
scanf("%d %d", &a,&b);
result = sum(a,b);
printf("nThe sum is : %d",result);
}
Function Declaration
Function Call
int sum(int a, int b)
{
int r;
r=a+b;
return r;
}
Function Body
Categories of Function Prototype/Declaration
1) Function without parameter and without return value
2) Function without parameter and with return value
3) Function with parameter and without return value
4) Function with parameter and with return value
1) Function without parameter and without return value
Example 1
#include<stdio.h>
void printName();
void main ()
{
printf("Hello ");
printName();
}
Output
Hello Bangalore
void printName()
{
printf("Bangalore");
}
Example 2
#include<stdio.h>
void sum();
void main()
{
printf("nGoing to calculate the sum of two numbers:");
sum();
}
void sum()
{
int a,b;
printf("nEnter two numbers");
scanf("%d %d",&a,&b);
printf("The sum is %d",a+b);
}
Output
Going to calculate the sum of two numbers:
Enter two numbers 10
24
The sum is 34
2) Function without parameter and with return value
Example 1
#include<stdio.h>
int sum();
void main()
{
int result;
printf("nGoing to calculate the sum of two numbers:");
result = sum();
printf("%d",result);
} Output
int sum()
{
int a,b;
printf("nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}
Going to calculate the sum of two numbers:
Enter two numbers 10
24
The sum is 34
#include<stdio.h>
int sum();
void main()
{
Example 2
printf("Going to calculate the area of the
squaren");
float area = square();
printf("The area of the square: %fn",area);
}
int square()
{
float side;
printf("Enter the length of the side in meters: ");
scanf("%f",&side);
return side * side;
} Output
Going to calculate the area of the square
Enter the length of the side in meters: 10
The area of the square: 100.000000
3) Function with parameter and without return value
Example 1
#include<stdio.h>
void sum(int, int);
void main()
{
int a,b;
printf("nGoing to calculate the sum of two numbers:");
printf("nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b)
{
printf("nThe sum is %d",a+b);
}
Output:
Going to calculate the sum of two numbers:
Enter two numbers 10
24
The sum is 34
#include<stdio.h>
Example 2
void average(int, int, int, int, int);
void main()
{
int a,b,c,d,e;
printf("nGoing to calculate the average of five
numbers:");
printf("nEnter five numbers:");
scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
average(a,b,c,d,e);
}
void average(int a, int b, int c, int d, int e)
{
float avg;
avg = (a+b+c+d+e)/5;
printf("The average of given five numbers :
%f",avg);
}
Output
Going to calculate the average of five
numbers:
Enter five numbers:10
20
30
40
50
The average of given five numbers :
30.000000
4) Function with parameter and with return value
#include<stdio.h>
Example 1
int sum(int, int);
void main()
{
int a,b,result;
printf("nGoing to calculate the sum of two numbers:");
printf("nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
}
Output
Going to calculate the sum of two
numbers:
Enter two numbers:10
20
The sum is : 30
printf("nGoing to check whether a number is }
even or odd");
printf("nEnter the number: ");
scanf("%d",&n);
flag = even_odd(n);
if(flag == 0)
{
printf("nThe number is odd");
}
else
}
Output
else
{
return 0;
}
{
printf("nThe number is even");
}
}
Going to check whether a number is even or odd
Enter the number: 100
The number is even
#include<stdio.h> Example 2 int even_odd(int n)
int even_odd(int); {
void main() if(n%2 == 0)
{ {
int n,flag=0; return 1;
Formal Parameter & Actual Parameter
1. Actual Parameters :
The arguments that are passed in a function call are called actual
arguments. These arguments are defined in the calling function.
These are the variables or expressions referenced in the parameter
list of a subprogram call. There is no need to specify datatype in
actual parameter.
2. Formal Parameters :
These are the variables or expressions referenced in the parameter list
of a subprogram specification. The datatype of the receiving value must
be defined. The scope of formal arguments is local to the function
definition in which they are used.
Call by Value and Call by Reference
Functions can be invoked in two ways: Call by Value or Call by Reference. These two
ways are generally differentiated by the type of values passed to them as parameters.
Call By Value: In this parameter passing method, values of actual parameters are copied
to function’s formal parameters and the two types of parameters are stored in different
memory locations. So any changes made inside functions are not reflected in actual
parameters of the caller.
Call by Reference: Both the actual and formal parameters refer to the same locations, so
any changes made inside the function are actually reflected in actual parameters of the
caller.
// C program to illustrate call by value
#include<stdio.h>
void swapx(int x, int y);
int main()
{
int a = 10, b = 20;
swapx(a, b);
printf("a=%d b=%dn", a, b);
return 0;
}
void swapx(int x, int y)
{
Output:
x=20 y=10
a=10 b=20
int t;
t = x;
x = y;
y = t;
printf("x=%d y=%dn", x, y);
}
// C program to illustrate Call by Reference
#include <stdio.h>
void swapx(int*, int*);
int main()
{
int a = 10, b = 20;
swapx(&a, &b);
printf("a=%d b=%dn", a, b);
return 0;
}
void swapx(int* x, int* y)
{
Output:
x=20 y=10
a=20 b=10
int t;
t = *x;
*x = *y;
*y = t;
printf("x=%d y=%dn", *x, *y);
}
Function that returns multiple values
In C or C++, we cannot return multiple values from a function
directly.
We can return more than one values from a function by using the
method called “call by address”, or “call by reference”.
In the invoker function, we will use two variables to store the results,
and the function will take pointer type data. So we have to pass the
address of the data.
Example Program
#include<stdio.h>
void div(int a, int b, int *quotient, int *remainder) ;
main() {
int a = 76, b = 10;
int q, r;
div(a, b, &q, &r);
printf("Quotient is: %dnRemainder is: %dn", q, r);
}
void div(int a, int b, int *quotient, int *remainder)
{
*quotient = a / b;
*remainder = a % b;
}
Pass arrays to a function in C
Example 1: Pass Individual Array Elements
#include <stdio.h>
void display(int age1, int age2) {
printf("%dn", age1);
printf("%dn", age2);
}
int main() {
int ageArray[] = {2, 8, 4, 12};
// pass second and third elements to display()
display(ageArray[1], ageArray[2]);
return 0;
}
Example 2: Pass Arrays to Functions
// Program to calculate the sum of array elements by passing to a function
#include <stdio.h>
float calculateSum(float num[]);
int main() {
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};
// num array is passed to calculateSum()
result = calculateSum(num);
printf("Result = %.2f", result);
return 0;
}
float calculateSum(float num[]) {
float sum = 0.0;
for (int i = 0; i < 6; ++i) {
sum += num[i];
}
return sum;
}
Example 3: Pass two-dimensional arrays
#include <stdio.h>
void displayNumbers(int num[2][2]);
int main() {
int num[2][2];
printf("Enter 4 numbers:n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
scanf("%d", &num[i][j]);
}
}
// pass multi-dimensional array to a function
displayNumbers(num);
return 0;
}
void displayNumbers(int num[2][2]) {
printf("Displaying:n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
printf("%dn", num[i][j]);
}}}
Storage Classes in C: Auto, Extern, Static, Register (Examples)
A storage class represents the visibility and a lifetime of a variable.
A storage class in C is used to describe the following things:
• The variable scope.
• The location where the variable will be stored.
• The initialized value of a variable.
• A lifetime of a variable.
Thus a storage class is used to represent the information about a
variable.
Scope of a Variable
Scope defines the visibility of an variable. It defines where an variable can be
accessed.
The scope variable is local or global
#include<stdio.h>
void fun();
int c= 30; /* global area */
main ( ) {
int a = 10; //local scope//
printf ("a=%d,c=%d"a,c);
fun ( );
}
oid fun ( ){
printf ("c=%d",c); //global variable
}
a =10, c = 30
c = 30
Lifetime of a Variable
The lifetime of a variable defines the duration for which the computer allocates
memory for it (the duration between allocation and deallocation of memory).
#include<stdio.h>
main ( ){
auto int i=1;{
auto int i=2;{
auto int i=3;
printf ("%d",i)
}
printf("%d", i);
}
printf("%d", i);
}
3 2 1
Storage Class Specifiers
There are four types of storage classes in C that are known as
storage class specifiers.
• Automatic (auto)
• Register (register)
• External (extern)
• Static (static)
Syntax of Class Storage Specifier in C
<Class Storage Specifier> <data type> <variable name>;
Example:
auto int x;
What are the Types of Storage Classes in C?
There are total four types of standard storage classes. The table below
represents the storage classes in C.
Principals of Programming in CModule -5.pdfModule-3.pdf
1) auto
The auto keyword is applied to all local variables automatically. It is the default
storage class that is why it is known as automatic variable. It's default value is
Garbage Value.
Example :-
void main()
{
int b = 5;
auto int a = 5; // Same as above . Auto keyword is default keyword.
printf(" %d, %d ", a,b);
}
Output :-
5 , 5
Auto keyword is present by default. No matter whether you write it or not. It stores
the value in RAM.
2) static variables in c
static variables are initialised only once in a lifetime of program. That means it gets
initialsed only once when function is called . It's default value is zero.
Example
#include <stdio.h>
void function()
{
static int a = 0; /* This statement gets initialised only once then it is ignored. */
int b = 0;
a++;
b++;
printf("na = %d , nb = %d",a,b);
}
Output
a = 1 b = 1
a = 2 b = 1
a = 3 b = 1
int main ()
{
function ();
function ();
function ();
return 0; }
3) register
register variables are mostly used in places where we need fast execution .
Because it is stored in register and registers are always fast than RAM. It is mostly
used in incrementing the counter or in loops.
register int counter=0;
#include <stdio.h>
void main()
{
int b = 5;
register int a = 5;
printf(“%d%d”,a,b);
}
Output
5 5
4) extern : The extern storage class is used to give a reference of a global variable that
is visible to ALL the program files. When you use 'extern', the variable cannot be
initialized however, it points the variable name at a storage location that has been
previously defined.
The extern modifier is most commonly used when there are two or more files sharing
the same global variables or functions as explained below.
First File: main.c
#include <stdio.h>
int count ;
extern void write_extern();
Second File: support.c
#include <stdio.h>
extern int count;
void write_extern(void) {
Here, extern is being used to declare
count in the second file, where as it
has its definition in the first file, main.c.
Now, compile these two files as follows
−
$gcc main.c support.c
It will produce the executable program
main() {
count = 5;
write_extern();
}
printf("count is %dn",
count);
}
a.out. When this program is executed,
it produces the following result −
count is 5
Recursive Function
Recursion:
In programming terms, a recursive function can be defined as a routine
that calls itself directly or indirectly.
Recursion Function Programs:
1) Factorial
2) Gcd with Lcm
3) Prime number
4) Fibonacci
5) Multiplication
6) Binary to Decimal ( Lab Program 11)
Factorial Program using Recursion
Recursive Solution:
Factorial can be calculated using following recursive formula.
n! = n * (n-1)!
n! = 1 if n = 0 or n = 1
#include<stdio.h>
int find_factorial(int);
int main()
{
int num, fact;
printf("nEnter any integer number:");
scanf("%d",&num);
int find_factorial(int n)
{
//Factorial of 0 is 1
if(n==0)
return(1);
fact =find_factorial(num); //Function calling itself: recursion
return(n*find_factorial(n-1));
printf("nfactorial of %d is: %d",num, fact); }
return 0;
}
GCD & LCM using Recursion
#include <stdio.h>
int gcd(int x, int y); //function prototype
//recursive function
int gcd(int x, int y)
{
int main() if (y == 0) //recursion
{
int num1, num2, hcf, lcm;
termination condition
{
printf("Enter two integer Values:n");
scanf("%d %d", &num1, &num2);
return x;
}
else
hcf = gcd(num1, num2);
printf("GCD: %d", hcf);
printf("nLCM: %d", (num1 * num2) /
hcf);
return 0;
{
return gcd(y, x % y);
itself
}
}
//calls
}
Fibonacci Series using recursive function
Fibonacci Series in C: In case of Fibonacci series, next number is the sum of previous
two numbers for example 0, 1, 1, 2, 3, 5, 8, 13, 21 etc. The first two numbers of fibonacci
series are 0 and 1.
#include<stdio.h>
int Fibonacci(int);
int main()
{
int n, i = 0, c;
scanf("%d",&n);
printf("Fibonacci seriesn");
for ( c = 1 ; c <= n ; c++ )
{
int Fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
printf("%dn", Fibonacci(i));
i++;
}
}
return 0;
}
Finding Prime number using recursive function
int primeno(int num, int i)
#include <stdio.h>
int primeno(int, int);
int main()
{
int num, check;
printf("Enter a number: ");
scanf("%d", &num);
check = primeno(num, num / 2);
if (check == 1)
{
printf("%d is a prime numbern", num);
}
else
{
printf("%d is not a prime numbern", num);
}
return 0;
}
{
if (i == 1)
{
return 1;
}
else
{
if (num % i == 0)
{
return 0;
}
else
{
return primeno(num, i - 1);
}
}
}
Write a C recursive function for multiplying two integers where a
function call is passed with two integers m and n.
#include <stdio.h>
int product(int, int);
int main()
{
int a, b, result;
int product(int a, int b)
{
if (a < b)
{
return product(b, a);
}
printf("Enter two numbers to find their product:
");
scanf("%d%d", &a, &b);
result = product(a, b);
printf("Product of %d and %d is %dn", a, b,
result);
return 0;
}
else if (b != 0)
{
return (a + product(a, b - 1));
}
else
{
return 0;
}
}
Array
An array is a collection of similar data items stored at contiguous memory locations
and elements can be accessed randomly using indices of an array. They can be
used to store collection of primitive data types such as int, float, double, char, etc of
any particular type.
Why do we need arrays?
We can use normal variables (v1, v2, v3, ..) when we have a small
number of objects, but if we want to store a large number of
instances, it becomes difficult to manage them with normal
variables. The idea of an array is to represent many instances in
one variable.
Array declaration, initialization and accessing
Array declaration syntax:
data_type arr_name [arr_size];
Array initialization
data_type arr_name *arr_size+=(value1, value2,value3,….);
Array accessing syntax:
arr_name[index];
One Dimensional Array ( 1-D Array)
(1) 1-D Array declaration by specifying size
Syntax:
datatype array[size];
// Array declaration by specifying size
int arr1[10];
// With recent C/C++ versions, we can also declare an array of user specified size
int n = 10;
int arr2[n];
// size= max count of elements that can be stored inside array.
(2) 1-D Array declaration by initializing elements
// Array declaration by initializing elements
int arr[ ] = { 10, 20, 30, 40 };
// Compiler creates an array of size 4.
// above is same as "int arr[4] = {10, 20, 30, 40}"
(3) 1-D Array declaration by specifying size and initializing elements
// Array declaration by specifying size and initializing
// elements
int arr[6] = { 10, 20, 30, 40 };
// Compiler creates an array of size 6, initializes first 4 elements as specified by user and
rest two elements as 0. above is same as "int arr[] = {10, 20, 30, 40, 0, 0}"
#include <stdio.h>
int main()
{
int arr[5];
arr[0] = 5;
arr[2] = -10;
arr[0] arr[1] arr[2] arr[3] arr[4]
arr[3 / 2] = 2; // this is same as arr[1] = 2
arr[3] = arr[0];
printf("%d %d %d %d", arr[0], arr[1], arr[2], arr[3]);
return 0;
}
// Program to take 5 values from the user and store them in an
//rP
ra
ry
int the elements stored in the array
#include <stdio.h>
int main()
{
int values[10];
Values[0] Values[1] Values[2] Values[3] Values[4]
printf("Enter 5 integers: "); // 2 4 3 5 7
// taking input and storing it in an array
for(int i = 0; i < 5; ++i)
{
scanf("%d", &values[i]); // Reading 2 4 3 5 7
}
printf("Displaying integers: ");
// printing elements of an array
for(int i = 0; i < 5; ++i)
{
printf("%dn", values[i]);
}
return 0;
}
2 4 3 5 7
// Program to find the average of n numbers using arrays
#include <stdio.h>
int main() { Output
int marks[10], i, n, sum = 0, average;
printf("Enter number of elements: ");
scanf("%d", &n); // n=4
Enter number1= 2
Enter number2= 3
Enter number3= 1
Enter number4= 0
for(i=0; i < n; ++i) // n=4, i= 0 to 3
{
Average=1
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]); // reading 2 3 1 0
// adding integers entered by the user to the sum variable
sum += marks[i]; // sum= sum+marks[i]= 6+0=6
}
average = sum / n; // 6/4=1
printf("Average = %d", average); // Average=1
return 0;
}
Read n number of values in an array and display it in reverse order
#include <stdio.h>
void main()
{
int i, n, a[100];
printf("Input the number of elements to store in the array :");
scanf("%d",&n); // n=3
printf("Input %d number of elements in the array :n",n); // 3 numbers
: 3 2 5
for(i=0;i<n;++i)
{
scanf("%d",&a[i]); // 3 2 5
}
for(int i = n-1; i >=0; --i)
{
printf("%dn", a[i]); // 5 2 3
}
Two Dimensional Array ( 2-D Array)
The two dimensional (2D) array in C programming is also known as
matrix. A matrix can be represented as a table of rows and columns.
Syntax:
Row major order:
datatype array_ name [row-size] [column-size];
Col major order:
datatype array_ name [column-size] [row-size];
// int array[10][12] // 10= row size, 12= col size
Declaration of two dimensional Array in
C
We can declare an array in the c language in the following way.
data_type array_name[size1][size2];
A simple example to declare two dimensional array is given below.
int twodimen[4][3];
Here, 4 is the row number and 3 is the column number.
Two Dimensional Array ( 2-D Array)
Accessing elements of a 2-D Array
Initialization
We have two different methods in initializing the values in C. The methods only
differ syntactically.
Below is one of them.
Another way of initializing is as follows:
Generally, the first method of initialization is preferred as we can clearly understand and
visualize the rows and columns of 2-D Arrays in C.
An array can be initialized in two ways, which are as follows −
• Compile time initialization.
• Runtime initialization.
Following is the C Program for compile time initialization ( Read & Display array elements) −
#include<stdio.h>
main ( ){
int a[3][3] = {10,20,30,40,50,60,70,80,90};
int i,j; // i= row position, j= col position
printf ("elements of the array are");
for ( i=0; i<3; i++) // based on row position
{
for (j=0;j<3; j++) // based on col position
{
printf("%d t", a[i][j]);
}
printf("n");
Output
The output is stated below −
elements of the array are:
10 20 30
40 50 60
70 80 90
}
}
Following is the C program for runtime initialization(Read & Display Array Elements) −
#include<stdio.h>
main ( ){
int a[3][3] ,i, j;
printf ("enter elements of array");
for ( i=0; i<3; i++){
for (j=0;j<3; j++){
scanf("%d", &a[i] [j] );
Output
The output is stated below −
}
} Enter elements of array :
printf("elements of the array are");
for ( i=0; i<3; i++){
for (j=0;j<3; j++){
printf("%dt", a[i] [j] );
}
printf("n");
1 2 3 4 5 6 7 8 9
Elements of the array are
1 2 3
4 5 6
7 8 9
}
}
C program to calculate sum and product of all elements in an array using run time
compilation
#include<stdio.h>
void main(){
//Declaring the array - run time//
int A[2][3],B[2][3],i,j,sum[i][j],product[i][j];
//Reading elements into the array's A and B using for loop//
printf("Enter elements into the array A: n");
for(i=0;i<2;i++){
for(j=0;j<3;j++){
printf("A[%d][%d] :",i,j);
scanf("%d",&A[i][j]);
}
printf("n");
}
printf("Enter elements into the array B: n");
for(i=0;i<2;i++){
for(j=0;j<3;j++){
printf("B[%d][%d] :",i,j);
scanf("%d",&B[i][j]);
}
printf("n");
}
//Calculating sum and printing output//
printf("Sum array is : n");
for(i=0;i<2;i++){
for(j=0;j<3;j++){
sum[i][j]=A[i][j]+B[i][j];
printf("%dt",sum[i][j]);
}
printf("n");
}
Output:
Enter elements into the array A:
A[0][0] :2
A[0][1] :3
A[0][2] :1
A[1][0] :2
A[1][1] :4
A[1][2] :5
Enter elements into the array B:
B[0][0] :1
B[0][1] :2
//Calculating product and printing output//
printf("Product array is : n");
for(i=0;i<2;i++){
for(j=0;j<3;j++){
product[i][j]=A[i][j]*B[i][j];
printf("%dt",product[i][j]);
}
printf("n");
}
B[0][2] :3
B[1][0] :5
B[1][1] :6
B[1][2] :7
Sum array is :
3 5 4
7 10 12
Product array is :
2 6 3
10 24 35
}
Multi Dimensional Array ( 2-D / 3-D
Array)
The general form of declaring N-dimensional arrays:
data_type array_name[size1][size2] ...[sizeN];
data_type: Type of data to be stored in the array.
Here data_type is valid C data type
array_name: Name of the array
size1, size2, ..,sizeN: Sizes of the dimensions
Principals of Programming in CModule -5.pdfModule-3.pdf
Initializing Three-Dimensional Array: Initialization in a Three-Dimensional array is
the same as that of Two-dimensional arrays. The difference is as the number of
dimensions increases so the number of nested braces will also increase.
Method 1:
int x[2][3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23};
Better Method:
int x[2][3][4] =
{
{ {0,1,2,3}, {4,5,6,7}, {8,9,10,11} },
{ {12,13,14,15}, {16,17,18,19}, {20,21,22,23} }
};
Accessing elements in Three-Dimensional Arrays:
Accessing elements in Three-Dimensional Arrays is also similar to that of Two-
Dimensional Arrays. The difference is we have to use three loops instead of two
loops for one additional dimension in Three-dimensional Arrays.
C Program to store and print 12 values entered by the user
#include <stdio.h>
int main()
{
int test[2][3][2];
// Printing values with proper index.
printf("nDisplaying values:n");
for (int i = 0; i < 2; ++i)
{
printf("Enter 12 values: n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
scanf("%d", test[i][j][k]);
} } }
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
printf("test[%d][%d][%d] = %dn", i, j, k, test[i][j][k]);
}
}
}
return 0; }
Output
Enter 12 values:
1
2
3
4
5
6
7
8
9
10
11
12
Displaying Values:
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12

More Related Content

PDF
function in in thi pdf you will learn what is fu...
PPTX
Functions.pptx, programming language in c
DOC
Functions struct&union
PPTX
Detailed concept of function in c programming
PPTX
UNIT3.pptx
PPTX
Programming_in_C_language_Unit5.pptx course ATOT
DOCX
PPS 6.6.FUNCTION INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONS
PPTX
unit_2 (1).pptx
function in in thi pdf you will learn what is fu...
Functions.pptx, programming language in c
Functions struct&union
Detailed concept of function in c programming
UNIT3.pptx
Programming_in_C_language_Unit5.pptx course ATOT
PPS 6.6.FUNCTION INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONS
unit_2 (1).pptx

Similar to Principals of Programming in CModule -5.pdfModule-3.pdf (20)

DOC
Unit 4 (1)
PDF
Unit 4.pdf
PPT
Functions and pointers_unit_4
PPTX
9 functions.pptxFunction that are used in
PPT
Functions in c
PPTX
unit_2.pptx
PPTX
C function
PPTX
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
PPTX
luckfuckfunctioneekefkfejewnfiwnfnenf.pptx
PPTX
Function in c program
PPTX
Fundamentals of functions in C program.pptx
PPTX
presentation_c_basics_1589366177_381682.pptx
PPTX
Presentation on function
PPT
Functions and pointers_unit_4
PPTX
Functions IN CPROGRAMMING OF ENGINEERING.pptx
DOCX
PDF
Functions
PPTX
PDF
USER DEFINED FUNCTIONS IN C.pdf
PDF
Functions
Unit 4 (1)
Unit 4.pdf
Functions and pointers_unit_4
9 functions.pptxFunction that are used in
Functions in c
unit_2.pptx
C function
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
luckfuckfunctioneekefkfejewnfiwnfnenf.pptx
Function in c program
Fundamentals of functions in C program.pptx
presentation_c_basics_1589366177_381682.pptx
Presentation on function
Functions and pointers_unit_4
Functions IN CPROGRAMMING OF ENGINEERING.pptx
Functions
USER DEFINED FUNCTIONS IN C.pdf
Functions
Ad

More from anilcsbs (6)

PDF
Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdf
PDF
Module 2_PPT_P1 POP Notes module 2 fdfd.pdf
PDF
Module 1_Chapter 2_PPT (1)sasaddsdsds.pdf
PDF
Principals of Programming in CModule -5.pdfModule-4.pdf
PDF
Principals of Programming in CModule -5.pdf
PDF
Module 1 _Chapter 1_PPT (1) (1) POP .pdf
Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdf
Module 2_PPT_P1 POP Notes module 2 fdfd.pdf
Module 1_Chapter 2_PPT (1)sasaddsdsds.pdf
Principals of Programming in CModule -5.pdfModule-4.pdf
Principals of Programming in CModule -5.pdf
Module 1 _Chapter 1_PPT (1) (1) POP .pdf
Ad

Recently uploaded (20)

PPTX
Construction Project Organization Group 2.pptx
PDF
Human-AI Collaboration: Balancing Agentic AI and Autonomy in Hybrid Systems
PPTX
CH1 Production IntroductoryConcepts.pptx
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPTX
UNIT 4 Total Quality Management .pptx
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PPTX
Current and future trends in Computer Vision.pptx
PPTX
Safety Seminar civil to be ensured for safe working.
PPT
Project quality management in manufacturing
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PPT
Mechanical Engineering MATERIALS Selection
PDF
Unit I ESSENTIAL OF DIGITAL MARKETING.pdf
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PDF
composite construction of structures.pdf
PPTX
bas. eng. economics group 4 presentation 1.pptx
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Construction Project Organization Group 2.pptx
Human-AI Collaboration: Balancing Agentic AI and Autonomy in Hybrid Systems
CH1 Production IntroductoryConcepts.pptx
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
UNIT 4 Total Quality Management .pptx
Automation-in-Manufacturing-Chapter-Introduction.pdf
Current and future trends in Computer Vision.pptx
Safety Seminar civil to be ensured for safe working.
Project quality management in manufacturing
Operating System & Kernel Study Guide-1 - converted.pdf
Mechanical Engineering MATERIALS Selection
Unit I ESSENTIAL OF DIGITAL MARKETING.pdf
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
composite construction of structures.pdf
bas. eng. economics group 4 presentation 1.pptx
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk

Principals of Programming in CModule -5.pdfModule-3.pdf

  • 1. Module 3 Function It is a building block that contains set of programming statements to perform a particular task. Aspects of the 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 which 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.
  • 2. Function Declaration Syntax: return-type function-name(datatype1 parameter1, parameter2,................, datatype n parameter n); Ex: int sum (int a, int b); float sum (float a, float b); datatype2 int mul (int a, int b, int c);
  • 3. Function Call Syntax: function-name (parameter1,parameter2, ........... ,parameter n); Ex: sum (a, b); sum (a, b); mul (a, b, c);
  • 4. Function Definition Syntax: return-type function-name(datatype1 parameter1, parameter2,................, datatype n parameter n) { Statements; } datatype2 Ex: int sum (int a, int b) { Variable declaration; Input statement; Processing statements; Output statements; } Function Body
  • 5. Function Return value --If the function doesn’t return any value, then the return type can be mentioned as ‘void’. Example: void show() { printf(“Hello”); } --If the function return any specific value, then the corresponding datatype can be mentioned as the return type can be mentioned such as int, float, char, double etc. int get() { return 5; } float get() { return 5.5; } char get() { return ‘c’; }
  • 6. Function Type Two types of functions: • Library Function The functions which are already defined in C library/header files. Example: printf(), scanf(), gets(), puts(), getchar(), putchar(), sqrt(), pow(), tolower(), toupper(), islower(), isupper() • User Defined Function The functions which are created by the programmer. These functions must be declared before usage. These functions’ definition must be written by the programmer.
  • 7. Function Declaration, Call, Definition Example: #include<stdio.h> int sum(int a, int b); int main() { int a,b,result; printf("nEnter two numbers:"); scanf("%d %d", &a,&b); result = sum(a,b); printf("nThe sum is : %d",result); } Function Declaration Function Call int sum(int a, int b) { int r; r=a+b; return r; } Function Body
  • 8. Categories of Function Prototype/Declaration 1) Function without parameter and without return value 2) Function without parameter and with return value 3) Function with parameter and without return value 4) Function with parameter and with return value
  • 9. 1) Function without parameter and without return value Example 1 #include<stdio.h> void printName(); void main () { printf("Hello "); printName(); } Output Hello Bangalore void printName() { printf("Bangalore"); }
  • 10. Example 2 #include<stdio.h> void sum(); void main() { printf("nGoing to calculate the sum of two numbers:"); sum(); } void sum() { int a,b; printf("nEnter two numbers"); scanf("%d %d",&a,&b); printf("The sum is %d",a+b); } Output Going to calculate the sum of two numbers: Enter two numbers 10 24 The sum is 34
  • 11. 2) Function without parameter and with return value Example 1 #include<stdio.h> int sum(); void main() { int result; printf("nGoing to calculate the sum of two numbers:"); result = sum(); printf("%d",result); } Output int sum() { int a,b; printf("nEnter two numbers"); scanf("%d %d",&a,&b); return a+b; } Going to calculate the sum of two numbers: Enter two numbers 10 24 The sum is 34
  • 12. #include<stdio.h> int sum(); void main() { Example 2 printf("Going to calculate the area of the squaren"); float area = square(); printf("The area of the square: %fn",area); } int square() { float side; printf("Enter the length of the side in meters: "); scanf("%f",&side); return side * side; } Output Going to calculate the area of the square Enter the length of the side in meters: 10 The area of the square: 100.000000
  • 13. 3) Function with parameter and without return value Example 1 #include<stdio.h> void sum(int, int); void main() { int a,b; printf("nGoing to calculate the sum of two numbers:"); printf("nEnter two numbers:"); scanf("%d %d",&a,&b); sum(a,b); } void sum(int a, int b) { printf("nThe sum is %d",a+b); } Output: Going to calculate the sum of two numbers: Enter two numbers 10 24 The sum is 34
  • 14. #include<stdio.h> Example 2 void average(int, int, int, int, int); void main() { int a,b,c,d,e; printf("nGoing to calculate the average of five numbers:"); printf("nEnter five numbers:"); scanf("%d %d %d %d %d",&a,&b,&c,&d,&e); average(a,b,c,d,e); } void average(int a, int b, int c, int d, int e) { float avg; avg = (a+b+c+d+e)/5; printf("The average of given five numbers : %f",avg); } Output Going to calculate the average of five numbers: Enter five numbers:10 20 30 40 50 The average of given five numbers : 30.000000
  • 15. 4) Function with parameter and with return value #include<stdio.h> Example 1 int sum(int, int); void main() { int a,b,result; printf("nGoing to calculate the sum of two numbers:"); printf("nEnter two numbers:"); scanf("%d %d",&a,&b); result = sum(a,b); printf("nThe sum is : %d",result); } int sum(int a, int b) { return a+b; } Output Going to calculate the sum of two numbers: Enter two numbers:10 20 The sum is : 30
  • 16. printf("nGoing to check whether a number is } even or odd"); printf("nEnter the number: "); scanf("%d",&n); flag = even_odd(n); if(flag == 0) { printf("nThe number is odd"); } else } Output else { return 0; } { printf("nThe number is even"); } } Going to check whether a number is even or odd Enter the number: 100 The number is even #include<stdio.h> Example 2 int even_odd(int n) int even_odd(int); { void main() if(n%2 == 0) { { int n,flag=0; return 1;
  • 17. Formal Parameter & Actual Parameter 1. Actual Parameters : The arguments that are passed in a function call are called actual arguments. These arguments are defined in the calling function. These are the variables or expressions referenced in the parameter list of a subprogram call. There is no need to specify datatype in actual parameter. 2. Formal Parameters : These are the variables or expressions referenced in the parameter list of a subprogram specification. The datatype of the receiving value must be defined. The scope of formal arguments is local to the function definition in which they are used.
  • 18. Call by Value and Call by Reference Functions can be invoked in two ways: Call by Value or Call by Reference. These two ways are generally differentiated by the type of values passed to them as parameters. Call By Value: In this parameter passing method, values of actual parameters are copied to function’s formal parameters and the two types of parameters are stored in different memory locations. So any changes made inside functions are not reflected in actual parameters of the caller. Call by Reference: Both the actual and formal parameters refer to the same locations, so any changes made inside the function are actually reflected in actual parameters of the caller.
  • 19. // C program to illustrate call by value #include<stdio.h> void swapx(int x, int y); int main() { int a = 10, b = 20; swapx(a, b); printf("a=%d b=%dn", a, b); return 0; } void swapx(int x, int y) { Output: x=20 y=10 a=10 b=20 int t; t = x; x = y; y = t; printf("x=%d y=%dn", x, y); }
  • 20. // C program to illustrate Call by Reference #include <stdio.h> void swapx(int*, int*); int main() { int a = 10, b = 20; swapx(&a, &b); printf("a=%d b=%dn", a, b); return 0; } void swapx(int* x, int* y) { Output: x=20 y=10 a=20 b=10 int t; t = *x; *x = *y; *y = t; printf("x=%d y=%dn", *x, *y); }
  • 21. Function that returns multiple values In C or C++, we cannot return multiple values from a function directly. We can return more than one values from a function by using the method called “call by address”, or “call by reference”. In the invoker function, we will use two variables to store the results, and the function will take pointer type data. So we have to pass the address of the data.
  • 22. Example Program #include<stdio.h> void div(int a, int b, int *quotient, int *remainder) ; main() { int a = 76, b = 10; int q, r; div(a, b, &q, &r); printf("Quotient is: %dnRemainder is: %dn", q, r); } void div(int a, int b, int *quotient, int *remainder) { *quotient = a / b; *remainder = a % b; }
  • 23. Pass arrays to a function in C Example 1: Pass Individual Array Elements #include <stdio.h> void display(int age1, int age2) { printf("%dn", age1); printf("%dn", age2); } int main() { int ageArray[] = {2, 8, 4, 12}; // pass second and third elements to display() display(ageArray[1], ageArray[2]); return 0; }
  • 24. Example 2: Pass Arrays to Functions // Program to calculate the sum of array elements by passing to a function #include <stdio.h> float calculateSum(float num[]); int main() { float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18}; // num array is passed to calculateSum() result = calculateSum(num); printf("Result = %.2f", result); return 0; } float calculateSum(float num[]) { float sum = 0.0; for (int i = 0; i < 6; ++i) { sum += num[i]; } return sum; }
  • 25. Example 3: Pass two-dimensional arrays #include <stdio.h> void displayNumbers(int num[2][2]); int main() { int num[2][2]; printf("Enter 4 numbers:n"); for (int i = 0; i < 2; ++i) { for (int j = 0; j < 2; ++j) { scanf("%d", &num[i][j]); } } // pass multi-dimensional array to a function displayNumbers(num); return 0; } void displayNumbers(int num[2][2]) { printf("Displaying:n"); for (int i = 0; i < 2; ++i) { for (int j = 0; j < 2; ++j) { printf("%dn", num[i][j]); }}}
  • 26. Storage Classes in C: Auto, Extern, Static, Register (Examples) A storage class represents the visibility and a lifetime of a variable. A storage class in C is used to describe the following things: • The variable scope. • The location where the variable will be stored. • The initialized value of a variable. • A lifetime of a variable. Thus a storage class is used to represent the information about a variable.
  • 27. Scope of a Variable Scope defines the visibility of an variable. It defines where an variable can be accessed. The scope variable is local or global #include<stdio.h> void fun(); int c= 30; /* global area */ main ( ) { int a = 10; //local scope// printf ("a=%d,c=%d"a,c); fun ( ); } oid fun ( ){ printf ("c=%d",c); //global variable } a =10, c = 30 c = 30
  • 28. Lifetime of a Variable The lifetime of a variable defines the duration for which the computer allocates memory for it (the duration between allocation and deallocation of memory). #include<stdio.h> main ( ){ auto int i=1;{ auto int i=2;{ auto int i=3; printf ("%d",i) } printf("%d", i); } printf("%d", i); } 3 2 1
  • 29. Storage Class Specifiers There are four types of storage classes in C that are known as storage class specifiers. • Automatic (auto) • Register (register) • External (extern) • Static (static) Syntax of Class Storage Specifier in C <Class Storage Specifier> <data type> <variable name>; Example: auto int x;
  • 30. What are the Types of Storage Classes in C? There are total four types of standard storage classes. The table below represents the storage classes in C.
  • 32. 1) auto The auto keyword is applied to all local variables automatically. It is the default storage class that is why it is known as automatic variable. It's default value is Garbage Value. Example :- void main() { int b = 5; auto int a = 5; // Same as above . Auto keyword is default keyword. printf(" %d, %d ", a,b); } Output :- 5 , 5 Auto keyword is present by default. No matter whether you write it or not. It stores the value in RAM.
  • 33. 2) static variables in c static variables are initialised only once in a lifetime of program. That means it gets initialsed only once when function is called . It's default value is zero. Example #include <stdio.h> void function() { static int a = 0; /* This statement gets initialised only once then it is ignored. */ int b = 0; a++; b++; printf("na = %d , nb = %d",a,b); } Output a = 1 b = 1 a = 2 b = 1 a = 3 b = 1 int main () { function (); function (); function (); return 0; }
  • 34. 3) register register variables are mostly used in places where we need fast execution . Because it is stored in register and registers are always fast than RAM. It is mostly used in incrementing the counter or in loops. register int counter=0; #include <stdio.h> void main() { int b = 5; register int a = 5; printf(“%d%d”,a,b); } Output 5 5
  • 35. 4) extern : The extern storage class is used to give a reference of a global variable that is visible to ALL the program files. When you use 'extern', the variable cannot be initialized however, it points the variable name at a storage location that has been previously defined. The extern modifier is most commonly used when there are two or more files sharing the same global variables or functions as explained below. First File: main.c #include <stdio.h> int count ; extern void write_extern(); Second File: support.c #include <stdio.h> extern int count; void write_extern(void) { Here, extern is being used to declare count in the second file, where as it has its definition in the first file, main.c. Now, compile these two files as follows − $gcc main.c support.c It will produce the executable program main() { count = 5; write_extern(); } printf("count is %dn", count); } a.out. When this program is executed, it produces the following result − count is 5
  • 36. Recursive Function Recursion: In programming terms, a recursive function can be defined as a routine that calls itself directly or indirectly.
  • 37. Recursion Function Programs: 1) Factorial 2) Gcd with Lcm 3) Prime number 4) Fibonacci 5) Multiplication 6) Binary to Decimal ( Lab Program 11)
  • 38. Factorial Program using Recursion Recursive Solution: Factorial can be calculated using following recursive formula. n! = n * (n-1)! n! = 1 if n = 0 or n = 1 #include<stdio.h> int find_factorial(int); int main() { int num, fact; printf("nEnter any integer number:"); scanf("%d",&num); int find_factorial(int n) { //Factorial of 0 is 1 if(n==0) return(1); fact =find_factorial(num); //Function calling itself: recursion return(n*find_factorial(n-1)); printf("nfactorial of %d is: %d",num, fact); } return 0; }
  • 39. GCD & LCM using Recursion #include <stdio.h> int gcd(int x, int y); //function prototype //recursive function int gcd(int x, int y) { int main() if (y == 0) //recursion { int num1, num2, hcf, lcm; termination condition { printf("Enter two integer Values:n"); scanf("%d %d", &num1, &num2); return x; } else hcf = gcd(num1, num2); printf("GCD: %d", hcf); printf("nLCM: %d", (num1 * num2) / hcf); return 0; { return gcd(y, x % y); itself } } //calls }
  • 40. Fibonacci Series using recursive function Fibonacci Series in C: In case of Fibonacci series, next number is the sum of previous two numbers for example 0, 1, 1, 2, 3, 5, 8, 13, 21 etc. The first two numbers of fibonacci series are 0 and 1. #include<stdio.h> int Fibonacci(int); int main() { int n, i = 0, c; scanf("%d",&n); printf("Fibonacci seriesn"); for ( c = 1 ; c <= n ; c++ ) { int Fibonacci(int n) { if ( n == 0 ) return 0; else if ( n == 1 ) return 1; else return ( Fibonacci(n-1) + Fibonacci(n-2) ); printf("%dn", Fibonacci(i)); i++; } } return 0; }
  • 41. Finding Prime number using recursive function int primeno(int num, int i) #include <stdio.h> int primeno(int, int); int main() { int num, check; printf("Enter a number: "); scanf("%d", &num); check = primeno(num, num / 2); if (check == 1) { printf("%d is a prime numbern", num); } else { printf("%d is not a prime numbern", num); } return 0; } { if (i == 1) { return 1; } else { if (num % i == 0) { return 0; } else { return primeno(num, i - 1); } } }
  • 42. Write a C recursive function for multiplying two integers where a function call is passed with two integers m and n. #include <stdio.h> int product(int, int); int main() { int a, b, result; int product(int a, int b) { if (a < b) { return product(b, a); } printf("Enter two numbers to find their product: "); scanf("%d%d", &a, &b); result = product(a, b); printf("Product of %d and %d is %dn", a, b, result); return 0; } else if (b != 0) { return (a + product(a, b - 1)); } else { return 0; } }
  • 43. Array An array is a collection of similar data items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They can be used to store collection of primitive data types such as int, float, double, char, etc of any particular type.
  • 44. Why do we need arrays? We can use normal variables (v1, v2, v3, ..) when we have a small number of objects, but if we want to store a large number of instances, it becomes difficult to manage them with normal variables. The idea of an array is to represent many instances in one variable.
  • 45. Array declaration, initialization and accessing Array declaration syntax: data_type arr_name [arr_size]; Array initialization data_type arr_name *arr_size+=(value1, value2,value3,….); Array accessing syntax: arr_name[index];
  • 46. One Dimensional Array ( 1-D Array) (1) 1-D Array declaration by specifying size Syntax: datatype array[size]; // Array declaration by specifying size int arr1[10]; // With recent C/C++ versions, we can also declare an array of user specified size int n = 10; int arr2[n]; // size= max count of elements that can be stored inside array.
  • 47. (2) 1-D Array declaration by initializing elements // Array declaration by initializing elements int arr[ ] = { 10, 20, 30, 40 }; // Compiler creates an array of size 4. // above is same as "int arr[4] = {10, 20, 30, 40}" (3) 1-D Array declaration by specifying size and initializing elements // Array declaration by specifying size and initializing // elements int arr[6] = { 10, 20, 30, 40 }; // Compiler creates an array of size 6, initializes first 4 elements as specified by user and rest two elements as 0. above is same as "int arr[] = {10, 20, 30, 40, 0, 0}"
  • 48. #include <stdio.h> int main() { int arr[5]; arr[0] = 5; arr[2] = -10; arr[0] arr[1] arr[2] arr[3] arr[4] arr[3 / 2] = 2; // this is same as arr[1] = 2 arr[3] = arr[0]; printf("%d %d %d %d", arr[0], arr[1], arr[2], arr[3]); return 0; }
  • 49. // Program to take 5 values from the user and store them in an //rP ra ry int the elements stored in the array #include <stdio.h> int main() { int values[10]; Values[0] Values[1] Values[2] Values[3] Values[4] printf("Enter 5 integers: "); // 2 4 3 5 7 // taking input and storing it in an array for(int i = 0; i < 5; ++i) { scanf("%d", &values[i]); // Reading 2 4 3 5 7 } printf("Displaying integers: "); // printing elements of an array for(int i = 0; i < 5; ++i) { printf("%dn", values[i]); } return 0; } 2 4 3 5 7
  • 50. // Program to find the average of n numbers using arrays #include <stdio.h> int main() { Output int marks[10], i, n, sum = 0, average; printf("Enter number of elements: "); scanf("%d", &n); // n=4 Enter number1= 2 Enter number2= 3 Enter number3= 1 Enter number4= 0 for(i=0; i < n; ++i) // n=4, i= 0 to 3 { Average=1 printf("Enter number%d: ",i+1); scanf("%d", &marks[i]); // reading 2 3 1 0 // adding integers entered by the user to the sum variable sum += marks[i]; // sum= sum+marks[i]= 6+0=6 } average = sum / n; // 6/4=1 printf("Average = %d", average); // Average=1 return 0; }
  • 51. Read n number of values in an array and display it in reverse order #include <stdio.h> void main() { int i, n, a[100]; printf("Input the number of elements to store in the array :"); scanf("%d",&n); // n=3 printf("Input %d number of elements in the array :n",n); // 3 numbers : 3 2 5 for(i=0;i<n;++i) { scanf("%d",&a[i]); // 3 2 5 } for(int i = n-1; i >=0; --i) { printf("%dn", a[i]); // 5 2 3 }
  • 52. Two Dimensional Array ( 2-D Array) The two dimensional (2D) array in C programming is also known as matrix. A matrix can be represented as a table of rows and columns. Syntax: Row major order: datatype array_ name [row-size] [column-size]; Col major order: datatype array_ name [column-size] [row-size]; // int array[10][12] // 10= row size, 12= col size
  • 53. Declaration of two dimensional Array in C We can declare an array in the c language in the following way. data_type array_name[size1][size2]; A simple example to declare two dimensional array is given below. int twodimen[4][3]; Here, 4 is the row number and 3 is the column number.
  • 54. Two Dimensional Array ( 2-D Array) Accessing elements of a 2-D Array
  • 55. Initialization We have two different methods in initializing the values in C. The methods only differ syntactically. Below is one of them. Another way of initializing is as follows: Generally, the first method of initialization is preferred as we can clearly understand and visualize the rows and columns of 2-D Arrays in C.
  • 56. An array can be initialized in two ways, which are as follows − • Compile time initialization. • Runtime initialization. Following is the C Program for compile time initialization ( Read & Display array elements) − #include<stdio.h> main ( ){ int a[3][3] = {10,20,30,40,50,60,70,80,90}; int i,j; // i= row position, j= col position printf ("elements of the array are"); for ( i=0; i<3; i++) // based on row position { for (j=0;j<3; j++) // based on col position { printf("%d t", a[i][j]); } printf("n"); Output The output is stated below − elements of the array are: 10 20 30 40 50 60 70 80 90 } }
  • 57. Following is the C program for runtime initialization(Read & Display Array Elements) − #include<stdio.h> main ( ){ int a[3][3] ,i, j; printf ("enter elements of array"); for ( i=0; i<3; i++){ for (j=0;j<3; j++){ scanf("%d", &a[i] [j] ); Output The output is stated below − } } Enter elements of array : printf("elements of the array are"); for ( i=0; i<3; i++){ for (j=0;j<3; j++){ printf("%dt", a[i] [j] ); } printf("n"); 1 2 3 4 5 6 7 8 9 Elements of the array are 1 2 3 4 5 6 7 8 9 } }
  • 58. C program to calculate sum and product of all elements in an array using run time compilation #include<stdio.h> void main(){ //Declaring the array - run time// int A[2][3],B[2][3],i,j,sum[i][j],product[i][j]; //Reading elements into the array's A and B using for loop// printf("Enter elements into the array A: n"); for(i=0;i<2;i++){ for(j=0;j<3;j++){ printf("A[%d][%d] :",i,j); scanf("%d",&A[i][j]); } printf("n"); } printf("Enter elements into the array B: n"); for(i=0;i<2;i++){ for(j=0;j<3;j++){ printf("B[%d][%d] :",i,j); scanf("%d",&B[i][j]); } printf("n"); }
  • 59. //Calculating sum and printing output// printf("Sum array is : n"); for(i=0;i<2;i++){ for(j=0;j<3;j++){ sum[i][j]=A[i][j]+B[i][j]; printf("%dt",sum[i][j]); } printf("n"); } Output: Enter elements into the array A: A[0][0] :2 A[0][1] :3 A[0][2] :1 A[1][0] :2 A[1][1] :4 A[1][2] :5 Enter elements into the array B: B[0][0] :1 B[0][1] :2 //Calculating product and printing output// printf("Product array is : n"); for(i=0;i<2;i++){ for(j=0;j<3;j++){ product[i][j]=A[i][j]*B[i][j]; printf("%dt",product[i][j]); } printf("n"); } B[0][2] :3 B[1][0] :5 B[1][1] :6 B[1][2] :7 Sum array is : 3 5 4 7 10 12 Product array is : 2 6 3 10 24 35 }
  • 60. Multi Dimensional Array ( 2-D / 3-D Array) The general form of declaring N-dimensional arrays: data_type array_name[size1][size2] ...[sizeN]; data_type: Type of data to be stored in the array. Here data_type is valid C data type array_name: Name of the array size1, size2, ..,sizeN: Sizes of the dimensions
  • 62. Initializing Three-Dimensional Array: Initialization in a Three-Dimensional array is the same as that of Two-dimensional arrays. The difference is as the number of dimensions increases so the number of nested braces will also increase. Method 1: int x[2][3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23}; Better Method: int x[2][3][4] = { { {0,1,2,3}, {4,5,6,7}, {8,9,10,11} }, { {12,13,14,15}, {16,17,18,19}, {20,21,22,23} } };
  • 63. Accessing elements in Three-Dimensional Arrays: Accessing elements in Three-Dimensional Arrays is also similar to that of Two- Dimensional Arrays. The difference is we have to use three loops instead of two loops for one additional dimension in Three-dimensional Arrays. C Program to store and print 12 values entered by the user #include <stdio.h> int main() { int test[2][3][2]; // Printing values with proper index. printf("nDisplaying values:n"); for (int i = 0; i < 2; ++i) { printf("Enter 12 values: n"); for (int i = 0; i < 2; ++i) { for (int j = 0; j < 3; ++j) { for (int k = 0; k < 2; ++k) { scanf("%d", test[i][j][k]); } } } for (int j = 0; j < 3; ++j) { for (int k = 0; k < 2; ++k) { printf("test[%d][%d][%d] = %dn", i, j, k, test[i][j][k]); } } } return 0; }
  • 64. Output Enter 12 values: 1 2 3 4 5 6 7 8 9 10 11 12 Displaying Values: test[0][0][0] = 1 test[0][0][1] = 2 test[0][1][0] = 3 test[0][1][1] = 4 test[0][2][0] = 5 test[0][2][1] = 6 test[1][0][0] = 7 test[1][0][1] = 8 test[1][1][0] = 9 test[1][1][1] = 10 test[1][2][0] = 11 test[1][2][1] = 12