0% found this document useful (0 votes)
3 views

Module-3

This document provides an overview of functions in C programming, including their declaration, calling, definition, and types. It explains concepts such as function return values, parameter passing methods (call by value and call by reference), and the use of storage classes. Additionally, it includes examples of various function types and storage class specifiers, highlighting their scope and lifetime.

Uploaded by

anil-csbs
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Module-3

This document provides an overview of functions in C programming, including their declaration, calling, definition, and types. It explains concepts such as function return values, parameter passing methods (call by value and call by reference), and the use of storage classes. Additionally, it includes examples of various function types and storage class specifiers, highlighting their scope and lifetime.

Uploaded by

anil-csbs
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

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, datatype2


parameter2, ................, datatype n parameter n);

Ex: int sum (int a, int b);

float sum (float a, float b);

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, datatype2
parameter2, ................, datatype n parameter n)
{
Statements;
}

Ex:
int sum (int a, int b)
{
Variable declaration;
Input statement; Function Body
Processing statements;
Output statements;
}
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() float get() char get()


{ { {
return 5; return 5.5; 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); Function Declaration
int main()
{
int a,b,result;
printf("\nEnter two numbers:");
scanf("%d %d", &a,&b);
result = sum(a,b); Function Call
printf("\nThe sum is : %d",result);
}
int sum(int a, int b)
{
Function Body
int r;
r=a+b;
return r;
}
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 ()
{ Output
printf("Hello ");
printName(); 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"); Output
scanf("%d %d",&a,&b);
printf("The sum is %d",a+b); 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()
{ Going to calculate the sum of two numbers:
int a,b; Enter two numbers 10
printf("\nEnter two numbers"); 24
scanf("%d %d",&a,&b); The sum is 34
return a+b;
}
#include<stdio.h>
int sum(); Example 2
void main()
{
printf("Going to calculate the area of the
square\n");
float area = square();
printf("The area of the square: %f\n",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) Output:
{
Going to calculate the sum of two numbers:
printf("\nThe sum is %d",a+b);
Enter two numbers 10
} 24
The sum is 34
Example 2
#include<stdio.h>
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:");
Output
scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
average(a,b,c,d,e); Going to calculate the average of five
} numbers:
void average(int a, int b, int c, int d, int e) Enter five numbers:10
{ 20
float avg; 30
avg = (a+b+c+d+e)/5; 40
printf("The average of given five numbers : 50
%f",avg); The average of given five numbers :
30.000000
}
4) Function with parameter and with return value

Example 1
#include<stdio.h>
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); Output
printf("\nThe sum is : %d",result);
} Going to calculate the sum of two
int sum(int a, int b) numbers:
Enter two numbers:10
{
20
return a+b; The sum is : 30
}
#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;
printf("\nGoing to check whether a number is }
even or odd"); else
printf("\nEnter the number: "); {
scanf("%d",&n); return 0;
flag = even_odd(n); }
if(flag == 0) }
{
printf("\nThe number is odd");
} Output
else
{ Going to check whether a number is even or odd
printf("\nThe number is even"); Enter the number: 100
} The number is even
}
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=%d\n", a, b);
Output:
return 0;
x=20 y=10
}
a=10 b=20
void swapx(int x, int y)
{
int t;
t = x;
x = y;
y = t;
printf("x=%d y=%d\n", 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=%d\n", a, b); Output:
return 0; x=20 y=10
} a=20 b=10
void swapx(int* x, int* y)
{
int t;
t = *x;
*x = *y;
*y = t;
printf("x=%d y=%d\n", *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: %d\nRemainder is: %d\n", 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("%d\n", age1);
printf("%d\n", 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("%d\n", 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);
}
321
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.
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++;
Output
b++;
a=1b=1
printf("\na = %d , \nb = %d",a,b);
a=2b=1
} a=3b=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.

Second File: support.c Here, extern is being used to declare


First File: main.c count in the second file, where as it
has its definition in the first file, main.c.
#include <stdio.h> #include <stdio.h>
Now, compile these two files as follows

int count ; extern int count;
extern void write_extern(); $gcc main.c support.c
void write_extern(void) { It will produce the executable program
main() { printf("count is %d\n", a.out. When this program is executed,
count); it produces the following result −
count = 5;
write_extern(); }
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 find_factorial(int n)
{ {
int num, fact; //Factorial of 0 is 1
printf("\nEnter any integer number:"); if(n==0)
scanf("%d",&num); 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> //recursive function
int gcd(int x, int y); //function prototype int gcd(int x, int y)
{
int main() if (y == 0) //recursion
{ termination condition
int num1, num2, hcf, lcm; {
return x;
printf("Enter two integer Values:\n"); }
scanf("%d %d", &num1, &num2); else
{
hcf = gcd(num1, num2); return gcd(y, x % y); //calls
printf("GCD: %d", hcf); itself
printf("\nLCM: %d", (num1 * num2) / }
hcf); }
return 0;
}
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 Fibonacci(int n)
int main()
{
{
if ( n == 0 )
int n, i = 0, c;
scanf("%d",&n); return 0;
printf("Fibonacci series\n"); else if ( n == 1 )
for ( c = 1 ; c <= n ; c++ ) return 1;
{ else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
printf("%d\n", 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() if (i == 1)
{ {
int num, check; return 1;
printf("Enter a number: "); }
scanf("%d", &num); else
check = primeno(num, num / 2); {
if (check == 1)
if (num % i == 0)
{
printf("%d is a prime number\n", num);
{
} return 0;
else }
{ else
printf("%d is not a prime number\n", num); {
} return primeno(num, i - 1);
return 0; }
} }
}
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 a, int b)


int product(int, int); {
int main() if (a < b)
{ {
int a, b, result; return product(b, a);
}
printf("Enter two numbers to find their product: else if (b != 0)
"); {
scanf("%d%d", &a, &b); return (a + product(a, b - 1));
result = product(a, b); }
printf("Product of %d and %d is %d\n", a, b, else
result); {
return 0; 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]; // size= max count of elements that can be stored inside array.

// 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];
(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] arr[1] arr[2] arr[3] arr[4]
arr[0] = 5;
arr[2] = -10;
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
raryint the elements stored in the array
//rP
#include <stdio.h>
2 4 3 5 7
int main()
{ Values[0] Values[1] Values[2] Values[3] Values[4]
int values[10];
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("%d\n", values[i]);
}
return 0;
}
// Program to find the average of n numbers using arrays
#include <stdio.h>
int main() { Output
int marks[10], i, n, sum = 0, average;
Enter number1= 2
printf("Enter number of elements: ");
Enter number2= 3
scanf("%d", &n); // n=4 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


:325

for(i=0;i<n;++i)
{
scanf("%d",&a[i]); // 3 2 5
}
for(int i = n-1; i >=0; --i)
{
printf("%d\n", 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"); Output
for ( i=0; i<3; i++) // based on row position The output is stated below −
{
for (j=0;j<3; j++) // based on col position elements of the array are:
{ 10 20 30
printf("%d \t", a[i][j]); 40 50 60
} 70 80 90
printf("\n");
}
}
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++){ Output
scanf("%d", &a[i] [j] ); The output is stated below −
}
} Enter elements of array :
printf("elements of the array are"); 123456789
for ( i=0; i<3; i++){ Elements of the array are
for (j=0;j<3; j++){ 123
printf("%d\t", a[i] [j] ); 456
} 789
printf("\n");
}
}
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); printf("Enter elements into the array B: \n");
scanf("%d",&A[i][j]); for(i=0;i<2;i++){
} for(j=0;j<3;j++){
printf("\n"); printf("B[%d][%d] :",i,j);
} scanf("%d",&B[i][j]);
}
printf("\n");
}
Output:
//Calculating sum and printing output// Enter elements into the array A:
printf("Sum array is : \n"); A[0][0] :2
for(i=0;i<2;i++){ A[0][1] :3
for(j=0;j<3;j++){ A[0][2] :1
sum[i][j]=A[i][j]+B[i][j]; A[1][0] :2
printf("%d\t",sum[i][j]); A[1][1] :4
} A[1][2] :5
Enter elements into the array B:
printf("\n");
B[0][0] :1
}
B[0][1] :2
B[0][2] :3
//Calculating product and printing output// B[1][0] :5
printf("Product array is : \n"); B[1][1] :6
for(i=0;i<2;i++){ B[1][2] :7
for(j=0;j<3;j++){ Sum array is :
product[i][j]=A[i][j]*B[i][j]; 354
printf("%d\t",product[i][j]); 7 10 12
Product array is :
}
263
printf("\n"); 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
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> // Printing values with proper index.


int main()
{ printf("\nDisplaying values:\n");
int test[2][3][2]; for (int i = 0; i < 2; ++i)
{
printf("Enter 12 values: \n"); for (int j = 0; j < 3; ++j)
{
for (int i = 0; i < 2; ++i) for (int k = 0; k < 2; ++k)
{ {
for (int j = 0; j < 3; ++j) printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]);
{ }
for (int k = 0; k < 2; ++k) }
{ }
scanf("%d", 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

You might also like