Multidimensional Arrays
In C programming, you can create an array of arrays. These arrays are known as
multidimensional arrays. For example,
float x[3][4];
Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think
the array as a table with 3 rows and each row has 4 columns.
Initializing a multidimensional array
Here is how you can initialize two-dimensional and three-dimensional arrays:
Initialization of a 2d array
// Different ways to initialize two-dimensional array
int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};
int c[][3] = {{1, 3, 0}, {-1, 5, 9}};
int c[2][3] = {1, 3, 0, -1, 5, 9};
// C program to store temperature of two cities of a week and display it.
#include <stdio.h>
const int CITY = 2;
const int WEEK = 7;
int main()
{
Page 1 of 15
int temperature[CITY][WEEK];
// Using nested loop to store values in a 2d array
for (int i = 0; i < CITY; ++i)
{
for (int j = 0; j < WEEK; ++j)
{
printf("City %d, Day %d: ", i + 1, j + 1);
scanf("%d", &temperature[i][j]);
}
}
printf("\nDisplaying values: \n\n");
// Using nested loop to display vlues of a 2d array
for (int i = 0; i < CITY; ++i)
{
for (int j = 0; j < WEEK; ++j)
{
printf("City %d, Day %d = %d\n", i + 1, j + 1, temperature[i][j]);
}
}
return 0;
}
Functions
A function is a block of code that performs a specific task.
Suppose, you need to create a program to create a circle and color it. You can create two
functions to solve this problem:
create a circle function
create a color function
Dividing a complex problem into smaller chunks makes our program easy to
understand and reuse.
Types of function
There are two types of function in C programming:
Standard library functions
User-defined functions
Page 2 of 15
Standard library functions
The standard library functions are built-in functions in C programming.
These functions are defined in header files. For example,
The printf() is a standard library function to send formatted output to the screen
(display output on the screen). This function is defined in the stdio.h header file.
Hence, to use the printf()function, we need to include the stdio.h header file
using #include <stdio.h>.
The sqrt() function calculates the square root of a number. The function is
defined in the math.h header file.
User-defined function
You can also create functions as per your need. Such functions created by the user are
known as user-defined functions.
How user-defined function works?
#include <stdio.h>
void functionName()
... .. ...
... .. ...
int main()
... .. ...
... .. ...
functionName();
Page 3 of 15
... .. ...
... .. ...
The execution of a C program begins from the main() function.
When the compiler encounters functionName();, control of the program jumps to
void functionName()
And, the compiler starts executing the codes inside functionName().
The control of the program jumps back to the main() function once code inside the
function definition is executed.
Here is an example to add two integers. To perform this task, we have created an user-
defined addNumbers().
#include <stdio.h>
int addNumbers(int a, int b); // function prototype
int main()
{
int n1,n2,sum;
printf("Enters two numbers: ");
scanf("%d %d",&n1,&n2);
sum = addNumbers(n1, n2); // function call
printf("sum = %d",sum);
return 0;
}
int addNumbers(int a, int b) // function definition
{
int result;
result = a+b;
return result; // return statement
}
Page 4 of 15
Passing arguments to a function
In programming, argument refers to the variable passed to the function. In the above
example, two variables n1 and n2 are passed during the function call.
The parameters a and b accepts the passed arguments in the function definition. These
arguments are called formal parameters of the function.
The type of arguments passed to a function and the formal parameters must match,
otherwise, the compiler will throw an error.
If n1 is of char type, a also should be of char type. If n2 is of float type, variable b also
should be of float type.
A function can also be called without passing an argument.
Return Statement
The return statement terminates the execution of a function and returns a value to the
calling function. The program control is transferred to the calling function after the
return statement.
In the above example, the value of the result variable is returned to the main function.
The sum variable in the main() function is assigned this value.
Page 5 of 15
#include <stdio.h>
int checkPrimeNumber(int n);
int main()
{
int n, flag;
printf("Enter a positive integer: ");
scanf("%d",&n);
// n is passed to the checkPrimeNumber() function
// the returned value is assigned to the flag variable
flag = checkPrimeNumber(n);
if(flag == 1)
printf("%d is not a prime number",n);
else
printf("%d is a prime number",n);
return 0;
}
// int is returned from the function
int checkPrimeNumber(int n)
{
int i;
for(i=2; i <= n/2; ++i)
Page 6 of 15
{
if(n%i == 0)
return 1;
}
return 0;
}
The input from the user is passed to the checkPrimeNumber() function.
The checkPrimeNumber() function checks whether the passed argument is prime or
not.
If the passed argument is a prime number, the function returns 0. If the passed
argument is a non-prime number, the function returns 1. The return value is assigned to
the flag variable.
Depending on whether flag is 0 or 1, an appropriate message is printed from
the main() function.
Pass arrays to a function
Passing array elements to a function is similar to passing variables to a function.
Passing an array
#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};
// Passing second and third elements to display()
display(ageArray[1], ageArray[2]);
return 0;
}
Page 7 of 15
Passing arrays to functions
// Program to calculate the sum of array elements by passing to a function
#include <stdio.h>
float calculateSum(float age[]);
int main() {
float result, age[] = {23.4, 55, 22.6, 3, 40.5, 18};
// age array is passed to calculateSum()
result = calculateSum(age);
printf("Result = %.2f", result);
return 0;
}
float calculateSum(float age[]) {
float sum = 0.0;
for (int i = 0; i < 6; ++i) {
sum += age[i];
}
return sum;
}
Recursion
A function that calls itself is known as a recursive function. And, this technique is known
as recursion.
Page 8 of 15
The recursion continues until some condition is met to prevent it.
To prevent infinite recursion, if...else statement (or similar approach) can be used
where one branch makes the recursive call, and other doesn't.
Sum of Natural Numbers Using Recursion
#include <stdio.h>
int sum(int n);
int main() {
int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number);
result = sum(number);
printf("sum = %d", result);
return 0;
}
int sum(int n) {
if (n != 0)
// sum() function calls itself
return n + sum(n-1);
else
return n;
}
Storage Class
Every variable in C programming has two properties: type and storage class.
Type refers to the data type of a variable. And, storage class determines the scope,
visibility and lifetime of a variable.
There are 4 types of storage class:
1. automatic
2. external
3. static
4. register
Page 9 of 15
Local Variable
The variables declared inside a block are automatic or local variables. The local
variables exist only inside the block in which it is declared.
Let's take an example.
#include <stdio.h>
int main(void) {
for (int i = 0; i < 5; ++i) {
printf("C programming");
}
// Error: i is not declared at this point
printf("%d", i);
return 0;
}
When you run the above program, you will get an error undeclared identifier i. It's
because i is declared inside the for loop block. Outside of the block, it's undeclared.
Let's take another example.
int main() {
int n1; // n1 is a local variable to main()
}
void func() {
int n2; // n2 is a local variable to func()
}
In the above example, n1 is local to main() and n2 is local to func().
This means you cannot access the n1 variable inside func() as it only exists
inside main(). Similarly, you cannot access the n2 variable inside main() as it only exists
inside func().
Page 10 of 15
Global Variable
Variables that are declared outside of all functions are known as external or global
variables. They are accessible from any function inside the program.
#include <stdio.h>
void display();
int n = 5; // global variable
int main()
{
++n;
display();
return 0;
}
void display()
{
++n;
printf("n = %d", n);
}
Static Variable
A static variable is declared by using the static keyword. For example; The value of a
static variable persists until the end of the program.
#include <stdio.h>
void display();
int main()
{
display();
display();
}
void display()
{
static int c = 1;
c += 5;
printf("%d ",c);
}
Page 11 of 15
Pointers
Pointers (pointer variables) are special variables that are used to store addresses rather
than values.
Here is how we can declare pointers.
int *p1;
int * p2;
Assigning addresses to Pointers
int* pc, c;
c = 5;
pc = &c;
Here, 5 is assigned to the c variable. And, the address of c is assigned to the pc pointer.
Get Value of Thing Pointed by Pointers
To get the value of the thing pointed by the pointers, we use the * operator. For
example:
int* pc, c;
c = 5;
pc = &c;
printf("%d", *pc);
Here, the address of c is assigned to the pc pointer. To get the value stored in that
address, we used *pc.
Changing Value Pointed by Pointers
int* pc, c;
c = 5;
pc = &c;
c = 1;
printf("%d", c); // Output: 1
printf("%d", *pc); // Ouptut: 1
Page 12 of 15
We have assigned the address of c to the pc pointer.
Then, we changed the value of c to 1. Since pc and the address of c is the same, *pc gives
us 1.
int* pc, c;
c = 5;
pc = &c;
*pc = 1;
printf("%d", *pc); // Ouptut: 1
printf("%d", c); // Output: 1
We have assigned the address of c to the pc pointer.
Then, we changed *pc to 1 using *pc = 1;. Since pc and the address of c is the same, c will
be equal to 1.
#include <stdio.h>
int main()
{
int* pc, c;
c = 22;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 22
pc = &c;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 22
c = 11;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 11
*pc = 2;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 2
return 0;
}
Page 13 of 15
Strings
a string is a sequence of characters terminated with a null character \0.
char c[] = "c string";
How to initialize strings?
You can initialize strings in a number of ways.
char c[] = "abcd";
char c[50] = "abcd";
char c[] = {'a', 'b', 'c', 'd', '\0'};
char c[5] = {'a', 'b', 'c', 'd', '\0'};
Read String from the user
You can use the scanf() function to read a string
The scanf() function reads the sequence of characters until it encounters whitespace
(space, newline, tab, etc.).
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
fgets() and puts()
#include <stdio.h>
int main()
{
Page 14 of 15
char name[30];
printf("Enter name: ");
fgets(name, sizeof(name), stdin); // read string
printf("Name: ");
puts(name); // display string
return 0;
}
Here, we have used fgets() function to read a string from the user.
fgets(name, sizeof(name), stdlin); // read string
The sizeof(name) results to 30. Hence, we can take a maximum of 30 characters as input
which is the size of the name string.
To print the string, we have used puts(name);.
Passing string to a Function
#include <stdio.h>
void displayString(char str[]);
int main()
{
char str[50];
printf("Enter string: ");
fgets(str, sizeof(str), stdin);
displayString(str); // Passing string to a function.
return 0;
}
void displayString(char str[])
{
printf("String Output: ");
puts(str);
}
Page 15 of 15