C Programming: Arrays, Pointers and Functions

In today’s video tutorial lets learn more about arrays and pointers, and how we can use them with functions.

Note:
This video tutorial is very important, so please make sure to watch the video till the end and make some notes. These are the basic concepts of arrays, pointers and functions. If you miss this, you’ll find other programs complicated. If you learn these basic concepts thoroughly all the programs related to using points and arrays with function will feel more straightforward. So please watch the video till the end and make note of important things I’m teaching in it. Happy Learning!

Related Read:
Basics of Pointers In C Programming Language
Introduction To Arrays: C Programming Language
Basics of Arrays: C Program
Function / Methods In C Programming Language

Important Topic
Please watch this short video without fail: C Program To Display Elements of Array In Reverse Order using Pointers

Visual Representation

arrays pointers and functions in C

Video Tutorial: C Programming: Arrays, Pointers & Functions


[youtube https://www.youtube.com/watch?v=2wdjJNfP7Hw]

YouTube Link: https://www.youtube.com/watch?v=2wdjJNfP7Hw [Watch the Video In Full Screen.]

Source Code: Simple Pointer Example

#include<stdio.h>
int main()
{
    int num = 5, *ptr;

    ptr = &num;

    printf("Value present at address %d is %d\n", ptr, *ptr);

    return 0;
}

Output:
Value present at address 6356728 is 5

Here we are assigning address of variable num to pointer variable ptr. Using ptr we display the address of num and the value present at that address.

Source Code: Simple Pointer and Array Example

#include<stdio.h>

int main()
{
    int num[5] = {1, 2, 3, 4, 5}, *ptr1, *ptr2;

    ptr1 = &num[0];
    ptr2 = num;

    printf("Base Address using &num[0]: %d\n", ptr1);
    printf("Base Address using num: %d\n", ptr2);

    printf("\n");

    printf("Value at num[0]: %d\n", *ptr1);
    printf("Value at *num: %d\n", *ptr2);
    printf("Value at *(num + 0): %d\n", *(ptr2 + 0));
    printf("Value at index 1: %d\n", *(ptr2 + 1));
    printf("Value at index 2: %d\n", *(ptr2 + 2));

    printf("\n");

    return 0;
}

Output:
Base Address using &num[0]: 6356708
Base Address using num: 6356708

Value at num[0]: 1
Value at *num: 1
Value at *(num + 0): 1
Value at index 1: 2
Value at index 2: 3

Above program proves that both &num[0] and num(array variable name) hold base address of the array. And if you add 1 to base address or any address, it’ll point to the immediately next address of its own type. Since num is of type integer all the addresses will have 4 bytes gap between them – as each address is allocated with 4 bytes of data space.

Important Note

1. Array elements are always stored in contiguous memory location.
2. A pointer when incremented always points to an immediately next location of its own type.
3. Whenever compiler finds num[i] it’ll convert it into *(num + i). Because it’s faster to work with addresses than with variables.

Source Code: Arrays and For Loop

#include<stdio.h>

int main()
{
    int num[5] = {1, 2, 3, 4, 5}, i;

    for(i = 0; i < 5; i++)
        printf("%d\n", num[i]);

    printf("\n");

    return 0;
}

Output:
1
2
3
4
5

This is how we access and print array elements – i.e., by using its index as subscript to array name.

Source Code: Address of Array Elements

#include<stdio.h>

int main()
{
    int num[5] = {1, 2, 3, 4, 5}, i;

    for(i = 0; i < 5; i++)
        printf("%d\n", num + i); // OR printf("%d\n", &num[i]);

    printf("\n");

    return 0;
}

Output:
6356712
6356716
6356720
6356724
6356728

Since array variable name num holds base address – if we add index value to it, it’ll fetch all the consecutive addresses.

Source Code: Values Associated with Address of Array Elements

#include<stdio.h>

int main()
{
    int num[5] = {1, 2, 3, 4, 5}, i;

    for(i = 0; i < 5; i++)
        printf("%d\n", *(num + i));

    printf("\n");

    return 0;
}

Output:
1
2
3
4
5

If we append * infront of a pointer variable it’ll print the value present at that address or memory location.

Note:
If we know the data type of the array and the base address of the array, we can fetch all the remaining addresses and values associated with those addresses.

Source Code: Using num[i] and [i]num Interchangeably

#include<stdio.h>

int main()
{
    int num[5] = {1, 2, 3, 4, 5}, i;

    for(i = 0; i < 5; i++)
        printf("%d\n", i[num]);

    printf("\n");

    return 0;
}

Output:
1
2
3
4
5

We can access array elements by adding index value to the base address and appending * to it. i.e., *(num + i). We can write the same thing like this *(i + num) as well. Similarly, we can write num[i] as i[num] too and it outputs the same results.

Source Code: Print Array Elements Using Pointer Variable

#include<stdio.h>
int main()
{
    int num[5] = {1, 2, 3, 4, 5}, i, *ptr;

    ptr = num; // OR ptr = &num[0];

    for(i = 0; i < 5; i++)
        printf("%d\n", *ptr++);

    printf("\n");

    return 0;
}

Output:
1
2
3
4
5

Here we’ve assigned base address to pointer variable ptr. Inside for loop, we print the value present at the current address of ptr and then increment the address by 1 – doing which it points to the next address in the array.

Source Code: Print Array Elements In Reverse Order Using Pointer Variable

#include<stdio.h>

#define N 5

int main()
{
    int num[N] = {1, 2, 3, 4, 5}, i, *ptr;

    ptr = &num[N - 1]; // OR ptr = num;

    for(i = 0; i < N; i++)
        printf("%d\n", *ptr--);

    printf("\n");

    return 0;
}

Output:
5
4
3
2
1

Here we are assigning last index elements address to the pointer variable. Inside for loop we print the value present at address ptr and then decrement the value of ptr by 1 for each iteration of for loop – doing which it points to the previous address in the array.

Source Code: Arrays, Pointers & Functions: Call By Value

#include<stdio.h>

#define N 5

void display(int x)
{
    printf("%d\n", x);
}

int main()
{
    int num[N] = {1, 2, 3, 4, 5}, i;

    for(i = 0; i < N; i++)
       display(num[i]);

    return 0;
}

Output:
1
2
3
4
5

Inside for loop we are passing value/element of array to display() method one by one for each iteration. And inside display() method we’re printing the values. This is called Call by value method.

Source Code: Arrays, Pointers & Functions: Call By Reference

#include<stdio.h>

#define N 5

void display(int *x)
{
    printf("%d\n", *x);
}

int main()
{
    int num[N] = {1, 2, 3, 4, 5}, i;

    for(i = 0; i < N; i++)
       display(&num[i]);

    return 0;
}

Output:
1
2
3
4
5

Inside for loop we are passing address of each element of array to display() method one by one for each iteration. Since we are passing address to display method, we need to have a pointer variable to receive it. Inside display() method we display the value present at the address being passed.

Source Code: Arrays, Pointers & Functions: Printing address of array elements

#include<stdio.h>

#define N 5

void display(int *x)
{
    printf("%d\n", x);
}

int main()
{
    int num[N] = {1, 2, 3, 4, 5}, i;

    for(i = 0; i < N; i++)
       display(&num[i]);

    return 0;
}

Output:
6356712
6356716
6356720
6356724
6356728

Inside display() method we’re accepting address using pointer variable, and then printing the addresses to the console window. If we want to print the elements present at the address, we need to append * in front of the pointer variable i.e., *x

Source Code: Add 1 to all the elements of array, using pointers and function

#include<stdio.h>

#define N 5

void oneplus(int *x)
{
    *x = *x + 1;
}

int main()
{
    int num[N] = {1, 2, 3, 4, 5}, i;

    for(i = 0; i < N; i++)
       oneplus(&num[i]);

    printf("\nArray elements after Oneplus operation!\n");
    for(i = 0; i < N; i++)
       printf("%d\n", num[i]);

    return 0;
}

Output:
Array elements after Oneplus operation!
2
3
4
5
6

Here we are passing address of each element to oneplus() method and inside oneplus() method we’re adding 1 to the value present at the address. We’re printing modified array element values inside main() method.

Source Code: Square all the elements of array – use pointers and function

#include<stdio.h>

#define N 5

void oneplus(int *x)
{
    *x = (*x) * (*x);
}

int main()
{
    int num[N] = {1, 2, 3, 4, 5}, i;

    for(i = 0; i < N; i++)
       oneplus(&num[i]);

    printf("\nArray elements after Oneplus operation!\n");
    for(i = 0; i < N; i++)
       printf("%d\n", num[i]);

    return 0;
}

Output:
Array elements after Oneplus operation!
1
4
9
16
25

Here we are passing address of each element to oneplus() method and inside oneplus() method we square the value present at the address. We’re printing modified array element values inside main() method.

Source Code: Arrays are pointers in disguise!

#include<stdio.h>

#define N 5

void oneplus5(int x[], int n)
{
    int i;

    for(i = 0 ; i < n; i++)
        x[i] = x[i] + 5;

}

int main()
{
    int num[N] = {1, 2, 3, 4, 5}, i;

    oneplus5(num, N);

    printf("\nArray elements after oneplus5 operation!\n");
    for(i = 0; i < N; i++)
       printf("%d\n", num[i]);

    return 0;
}

Output:
Array elements after oneplus5 operation!
6
7
8
9
10

Here we are passing base address and the size of array to oneplus5() method. Inside oneplus5() method, we are adding 5 to each element of the array. Once the execution of oneplus5() method completes, control comes back to main() method and here we print all the elements of the array. And the modifications made inside oneplus5() method reflects in main() method when we print the elements of array. Internally, x[i] will be converted into *(x + i) and hence the operation takes place at address level. So the manipulation reflects everywhere in the program.

void oneplus5(int x[], int n)
{
    int i;

    for(i = 0 ; i < n; i++)
        x[i] = x[i] + 5;
}

will be converted to

void oneplus5(int x[], int n)
{
    int i;

    for(i = 0 ; i < n; i++)
        *(x + i) = *(x + i) + 5;
}

Word of Caution!

Whenever you pass base address to a function and operate on the value present at that address, the array element/value gets altered. If you want to avoid it, make sure to pass a duplicate copy of the array to the function and not the base address of the original array.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Display Elements of Array In Reverse Order using Pointers

Write a c program to display/print elements of an array in reverse order, using pointers.

Pointer Variable: Pointer variable is a variable which holds the address of another variable of same type.

Related Read:
C Program To Print Elements of Array In Reverse Order
Basics of Pointers In C Programming Language

Important Topic
Please watch this important video without fail: C Programming: Arrays, Pointers and Functions

Example: Expected Output

Enter 5 integer numbers
1
2
3
4
5

Elements of array in reverse order …
5
4
3
2
1

Visual Representation

print array elements in reverse order using pointers

Video Tutorial: C Program To Display Elements of Array In Reverse Order using Pointers


[youtube https://www.youtube.com/watch?v=CYf-rVrKNTI]

YouTube Link: https://www.youtube.com/watch?v=CYf-rVrKNTI [Watch the Video In Full Screen.]

Source Code: C Program To Display Elements of Array In Reverse Order using Pointers

#include<stdio.h>

#define N 5

int main()
{
    int a[N], i, *ptr;

    printf("Enter %d integer numbers\n", N);
    for(i = 0; i < N; i++)
        scanf("%d", &a[i]);

    ptr = &a[N - 1];

    printf("\nElements of array in reverse order ...\n");
    for(i = 0; i < N; i++)
        printf("%d\n", *ptr--);

    return 0;
}

Output 1:
Enter 5 integer numbers
1
2
3
4
5

Elements of array in reverse order …
5
4
3
2
1
Output 2:
Enter 5 integer numbers
10
9
8
7
6

Elements of array in reverse order …
6
7
8
9
10

Logic To Display Elements of Array In Reverse Order using Pointers

We ask the user to input N integer numbers and store it inside array variable a[N]. We assign address of (N – 1)th element(last element of any array) to pointer variable ptr.

Inside for loop
We iterate through the for loop and for each iteration we print the value present at the address ptr. And for each iteration we decrement the value of ptr by 1.

This prints the array elements in reverse order.

Important Things To Note

1. Array elements are always stored in contiguous memory location.
2. A pointer when incremented always points to an immediately next location of its own type.

Explanation With Example

int a[5] = {5, 2, 6, 4, 3};
ptr = &a[4];

iptr*ptr–
010173
110134
210096
310052
410015

Output
3
4
6
2
5

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Find Largest Difference Between Two Elements of Array

Write a C program to find largest / maximum difference between two elements of an array, such that larger element or number appears after the smaller number in the array.

Note: I’m not considering time complexity in this video tutorial intentionally. We’ll have a completely dedicated video teaching about time complexity from basic. My intention in this video is to make the logic as simple and understandable as possible.

Related Read:
C Program To Find Biggest Element of An Array
C Program To Find Smallest Element In An Array

Example: Expected Output

Enter 6 integer numbers
7
9
5
6
13
2
The largest difference is 8, and its between 13 and 5.

Visual Representation

Largest Difference Between Two Elements of Array

Video Tutorial: C Program To Find Largest Difference Between Two Elements of Array


[youtube https://www.youtube.com/watch?v=XLHcpajCZyQ]

YouTube Link: https://www.youtube.com/watch?v=XLHcpajCZyQ [Watch the Video In Full Screen.]

Source Code: C Program To Find Largest Difference Between Two Elements of Array

#include<stdio.h>

#define N 6

int main()
{
    int num[N], i, big, small;

    printf("Enter %d integer numbers\n", N);
    for(i = 0; i < N; i++)
        scanf("%d", &num[i]);

    big = small = num[0];

    for(i = 1; i < N; i++)
    {
        if(num[i] > big)
            big = num[i];

        if(num[i] < small)
            small = num[i];
    }

    printf("The largest difference is %d, ", (big - small));
    printf("and its between %d and %d.\n", big, small);

    return 0;
}

Output:
Enter 6 integer numbers
7
9
5
6
13
2
The largest difference is 11, and its between 13 and 2.

Here we find biggest element in the array and smallest element in the array. Next we subtract smallest element from biggest element to get the largest different between two array elements.

Find Largest Difference, where Largest Element Appears After Smallest Number in Array

#include<stdio.h>

#define N 6

int main()
{
    int num[N], i, big, small, pos = 0;

    printf("Enter %d integer numbers\n", N);
    for(i = 0; i < N; i++)
        scanf("%d", &num[i]);

    big = small = num[0];

    for(i = 1; i < N; i++)
    {
        if(num[i] > big)
        {
            big = num[i];
            pos = i;
        }
    }

    for(i = 1; i < pos; i++)
    {
        if(num[i] < small)
            small = num[i];
    }

    printf("The largest difference is %d, ", (big - small));
    printf("and its between %d and %d.\n", big, small);

    return 0;
}

Output:
Enter 6 integer numbers
7
9
5
6
13
2
The largest difference is 8, and its between 13 and 5.

Logic To Find Largest Difference b/w Two Elements of Array, where biggest number appears after the smallest number

As per the problem statement, the smallest number in the array must be chosen from index 0 to the position where the biggest number of the array is present.

For Example: Assume that we’ve an array {1, 2, 5, 3, 0}. Here biggest element in the array is 5 and its position in the array is 2. Now we need to select smallest number in the array between the index range 0 to 2. So the smallest number will be 1.

Step 1: First we iterate through the array using a for loop and find the biggest element in the array and we also determine the index position at which this biggest number is present.

Step 2: We write another for loop and iterate from index 1 to the position where the biggest number is present. And inside for loop we select the smallest element between the range.

Step 3: Now we subtract the smallest element from step 2 with the biggest element from step 1, and we get the largest difference between two elements of an array, where biggest number appears after the smaller number in the array.

Note:
1. We initialize variables big and small to the first element of the array, because we need to have some value to compare it with other elements of the array.
2. In both the for loops we initialize i to 1, as both variables big and small is assigned with value present at index 0. So there is no point in comparing with itself, so we start the comparison from index 1. That’s the reason we initialize i to 1 in both the for loops.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Search A Number And Count Its Occurrence In An Array

Twenty-five numbers are entered from the keyboard into an array. The number to be searched is entered through the keyboard by the user. Write a C program to find if the number to be searched is present in the array and if it is present, display the number of times it appears in the array.

Example: Expected Output

Enter 5 integer numbers
1
5
6
3
5
Enter the number to be searched …
5

5 has appeared at position 2 in the array.
5 has appeared at position 5 in the array.

Final Result: 5 has appeared 2 times in the array.

Visual Representation

search key in array

Video Tutorial: C Program To Search A Number And Count Its Occurrence In An Array


[youtube https://www.youtube.com/watch?v=qLrIu_epQYU]

YouTube Link: https://www.youtube.com/watch?v=qLrIu_epQYU [Watch the Video In Full Screen.]

Source Code: C Program To Search A Number And Count Its Occurrence In An Array

#include<stdio.h>

#define N 5

int main()
{
    int a[N], i, key, count = 0;

    printf("Enter %d integer numbers\n", N);
    for(i = 0; i < N; i++)
        scanf("%d", &a[i]);

    printf("Enter the number to be searched ...\n");
    scanf("%d", &key);

    printf("\n");

    for(i = 0; i < N; i++)
    {
        if(a[i] == key)
        {
          printf("%d has appeared at position %d in the array.\n", key, i + 1);
          count++;
        }
    }

  printf("\nFinal Result: %d has appeared %d times in the array.\n", key, count);

    printf("\n");

    return 0;
}

Output 1:
Enter 5 integer numbers
1
5
9
6
4
Enter the number to be searched …
4

4 has appeared at position 5 in the array.
Final Result: 4 has appeared 1 times in the array.

Output 2:
Enter 5 integer numbers
1
2
3
4
5
Enter the number to be searched …
6

Final Result: 6 has appeared 0 times in the array.

Output 3:
Enter 5 integer numbers
1
5
4
5
2
Enter the number to be searched …
5

5 has appeared at position 2 in the array.
5 has appeared at position 4 in the array.

Final Result: 5 has appeared 2 times in the array.

Logic To Search A Number And Count Its Occurrence In An Array

We ask the user to enter N integer numbers(25 integer numbers according to the problem statement) and store it inside array a[N]. Next we ask the user to input the number to be searched – we store the user input inside variable key.

Inside for loop
We make use of for loop to iterate through entire array. For each iteration we check if the value present at a[i] is equal to value present in key. If it’s true, then we display the position(index value + 1) at which “key” appears and also increment the value of variable count by 1.

After all the iterations of for loop, we display the number of occurrences of key inside the array – value of which is present in variable count.

Explanation With Example

If int a[5] = {1, 5, 6, 3, 5};
key = 5;

ia[i]a[i] == keycount
01FALSE0
15TRUE1
26FALSE1
33FALSE1
45TRUE2

5 has appeared at position 2 in the array.
5 has appeared at position 5 in the array.

Final Result: 5 has appeared 2 times in the array.

Note: We increment the position of key in the array by 1, as users are not used to counting from 0. (Array index starts from 0.)

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Segregate 0s and 1s In An Array using Swapping Method

Write a C program to segregate 0’s to the left and 1’s to the right of an array using Swapping method.

Related Read:
C Program To Segregate 0s and 1s In An Array using Counting Method

Example: Expected Input/Output

Enter 10 elements(0 or 1)
1
0
1
0
1
0
1
0
1
0

Array after sorting 0’s to left and 1’s to right
0
0
0
0
0
1
1
1
1
1

Visual Representation

Segregate 0s and 1s In An Array

Video Tutorial: C Program To Segregate 0’s and 1’s In An Array using Swapping Method


[youtube https://www.youtube.com/watch?v=AqJM2WtkeEU]

YouTube Link: https://www.youtube.com/watch?v=AqJM2WtkeEU [Watch the Video In Full Screen.]

Source Code: C Program To Segregate 0’s and 1’s In An Array using Swapping Method

#include<stdio.h>

#define N 5

int main()
{
    int a[N], i, left = 0, right = N - 1;

    printf("Enter %d elements(0 or 1)\n", N);
    for(i = 0; i < N; i++)
    {
        scanf("%d", &a[i]);

        if(a[i] != 0 && a[i] != 1)
        {
            printf("Please enter only 0 and 1 as input\n");
            i--;
        }
    }

    while(left < right)
    {
        while(a[left]   == 0)
            left++;

        while(a[right] == 1)
            right--;

        if(left < right)
        {
            a[left++] = 0;
            a[right--] = 1;
        }
    }

    printf("\nArray after sorting 0's to left and 1's to right\n");
    for(i = 0; i < N; i++)
        printf("%d\n", a[i]);

    printf("\n");

    return 0;
}

Output 1:
Enter 5 elements(0 or 1)
1
0
0
1
0

Array after sorting 0’s to left and 1’s to right
0
0
0
1
1

Output 2:
Enter 5 elements(0 or 1)
2
Please enter only 0’s and 1’s as input
10
Please enter only 0’s and 1’s as input
1
0
2
Please enter only 0’s and 1’s as input
1
1
0

Array after segregating o’s to left and 1’s to right
0
0
1
1
1

Logic To Segregate 0’s and 1’s In An Array using Swapping Method

We ask the user to input N integer numbers and store it inside a[N]. We assign 0(the first index of any array) to variable left and N – 1(the last index of any array) to variable right.

The outer while loop executes until left < right. Inside we write another while loop to check from left, if a[left] is 0. If its already 0, then its already in sorted order, so we don’t swap it. We simply increment the value of left by one position. Control exits this first inner while loop when a[left] is not equal to 0.

Similarly, we check if a[right] is 1. If its 1, we decrement the value of right by 1. When a[right] is not equal to 1, the control exits.

Now variable “left” will have the index position from left where there is number 1. And variable “right” will have the index position from right where there is number 0. Now we need to swap it.

We check if value of left is still less than the value of right. If true, we store 0 at a[left] and 1 at a[right].

Explanation With Example

If a[5] = {0, 1, 1, 0, 1};

lefta[left]righta[right]Swap
0041NO
1130YES
2121NO

a[5] after sorting 0’s to left and 1’s to right:
a[5] = {0, 0, 1, 1, 1};

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert