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 Find GCD using Pointers and Functions

Write a function to compute the greatest common divisor given by Euclid’s algorithm, exemplified for J = 1980, K = 1617 as follows:

1980 / 1617 = 11980 – 1 * 1617 = 363
1617 / 363 = 41617 – 4 * 363 = 165
363 / 165 = 2363 – 2 * 165 = 33
5 / 33 = 5165 – 5 * 33 = 0

Thus, the greatest common divisor is 33.

Analyze Above Problem Statement

1. We need to find Greatest Common Divisor(GCD) of 2 numbers entered by the user, using Euclid’s Algorithm.

2. If J = 1980 and K = 1617, GCD should be 33.

3. Make sure to use the calculation part as shown in problem statement.

4. We observe the calculation part in problem statement and formulate some formulas to figure out the result i.e., GCD of 2 numbers input by the user.

Related Read:
C Program To Find GCD and LCM of Two Numbers using Euclidean algorithm

Video Tutorial: C Program To Find GCD using Pointers and Functions, using Euclid’s Algorithm


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

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


Source Code: C Program To Find GCD using Pointers and Functions, using Euclid’s Algorithm

#include<stdio.h>

void calc_gcd(int, int, int*);

int main()
{
    int j, k, gcd;

    printf("Enter 2 integer numbers\n");
    scanf("%d%d", &j, &k);

    calc_gcd(j, k, &gcd);

    printf("\nGreatest Common Divisor of %d and %d is %d.\n", j, k, gcd);

    return 0;
}

void calc_gcd(int numerator, int denominator, int *gcd)
{
    int temp, num;

    if(denominator == 0)
    {
        *gcd = numerator;
    }
    else if(numerator == 0)
    {
        *gcd = denominator;
    }
    else
    {
        num  = numerator / denominator;
        temp = numerator - num * denominator;

        while(temp)
        {
            numerator   = denominator;
            denominator = temp;
            num  = numerator / denominator;
            temp = numerator - num * denominator;
        }

        *gcd = denominator;
    }
}

Output 1:
Enter 2 integer numbers
1980
1617

Greatest Common Divisor of 1980 and 1617 is 33.

Output 2:
Enter 2 integer numbers
1617
1980

Greatest Common Divisor of 1617 and 1980 is 33.

Output 3:
Enter 2 integer numbers
15
20

Greatest Common Divisor of 15 and 20 is 5.

Output 4:
Enter 2 integer numbers
20
15

Greatest Common Divisor of 20 and 15 is 5.

Logic To Find GCD using Pointers and Functions, using Euclid’s Algorithm

We ask the user to input integer values for variables j and k. We pass values of j and k and address of variable gcd to a function called calc_gcd().

Inside calc_gcd() function
Inside calc_gcd() function we use the following calculations:

Note: We copy the value of j, k and &gcd passed by main method into local variables of calc_gcd() i.e., numerator, denominator and *gcd.

Step 1: We check if denominator is 0. In that case the value present in numerator itself is the GCD. So we copy value present in variable numerator to *gcd.

Step 2: If denominator is not zero. Then, we divide numerator with denominator value and store the result into a variable called num.

num = numerator / denominator;

If j = 1980 and k = 1617, then numerator = 1980 and denominator = 1617.

num = numerator / denominator;
num = 1980/ 1617;
num = 1;

According to problem statement:

1980 / 1617 = 11980 – 1 * 1617 = 363

We’ve formulated the equation for the first part i.e., 1980 / 1617 = 1
Now lets formulate an equation for the second part i.e., 1980 – 1 * 1617 = 363

If you look at 1980 – 1 * 1617 = 363 closely and substitute the values with corresponding variables then you’ll come up with below formula:

temp = numerator – num * denominator;

Look at Step 1 for values of numerator, denominator and num.

Now lets look at the equations given in the problem statement:

1980 / 1617 = 11980 – 1 * 1617 = 363
1617 / 363 = 41617 – 4 * 363 = 165

In this look at 1617 / 363 = 4. Here the value of denominator has been shifted to numerators place, and the value of temp has been copied to denominator. So lets write the code:

numerator = denominator;
denominator = temp;

Step 3: Now lets use these formulate in co-ordination to finish writing our function code.

We need to repeat the code in order to get the results according to the columns present in the problem statement equations:

Here are our formulas:

   
        num         = numerator / denominator;
        temp        = numerator - num * denominator;     
        numerator   = denominator;
        denominator = temp;

Here are the steps in problem statement to calculate the GCD:

1980 / 1617 = 11980 – 1 * 1617 = 363
1617 / 363 = 41617 – 4 * 363 = 165
363 / 165 = 2363 – 2 * 165 = 33
5 / 33 = 5165 – 5 * 33 = 0

We need to repeat execution of our code to get above result:

num  = numerator / denominator;
temp = numerator - num * denominator;

     while(temp)
     {
        numerator   = denominator;
        denominator = temp;
        num  = numerator / denominator;
        temp = numerator - num * denominator;
      }

      *gcd = denominator;

We need to put our code inside a looping construct to repeat the code. Here we are using while loop. So while loop iterates until temp value is positive. Once value of temp is 0, the control exits the while loop.

We have written 2 lines of code before the while loop:

num  = numerator / denominator;
temp = numerator - num * denominator;

that is because we need to have some value inside variable temp before using it as condition for while loop.

Once the value of temp is 0, control exits while loop. Outside while loop we transfer the value present inside denominator to *gcd.

So *gcd will have the Greatest Common Divisor for values input by the user(j = 1980 and k = 1617).

Observe this table from problem statement

1980 / 1617 = 11980 – 1 * 1617 = 363
1617 / 363 = 41617 – 4 * 363 = 165
363 / 165 = 2363 – 2 * 165 = 33
5 / 33 = 5165 – 5 * 33 = 0

When temp value is 0, value of denominator is 33 – which is the Greatest Common Divisor of numbers 1980 and 1617.

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 Add Two Numbers using Pointers

Lets write a C program to add 2 numbers using pointer and function.

In this video tutorial we will show both ways of adding 2 numbers using pointers: 1. Using function 2. Without using function.

Related Read:
Basics of Pointers In C Programming Language
Function / Methods In C Programming Language

Video Tutorial: C Program To Add Two Numbers using Pointers


[youtube https://www.youtube.com/watch?v=0wBPwxsr6-U]

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


Source Code: C Program To Add Two Numbers using Pointers and Without using Function

#include<stdio.h>

int main()
{
    int a, b, c, *ptr1, *ptr2;

    ptr1 = &a;
    ptr2 = &b;

    printf("Enter 2 numbers\n");
    scanf("%d%d", &a, &b);

    c = *ptr1 + *ptr2;

    printf("Using *ptr1 + *ptr2 : %d + %d = %d\n", a, b, c);

    c = *(&a) + *(&b);

    printf("Using  *(&a) + *(&b) : %d + %d = %d\n", a, b, c);

    return 0;
}

Output:
Enter 2 numbers
25
25
Using *ptr1 + *ptr2 : 25 + 25 = 50
Using (&a) + *(&b) : 25 + 25 = 50

Logic To Add Two Numbers using Pointers

Here we are storing the address of variable a in pointer variable ptr1 and address of variable b in pointer variable ptr2.

We know that any address preceded by * would fetch the value present at that address. So we use following code to get the addition of 2 numbers result using pointers.

c = *ptr1 + *ptr2;

Source Code: C Program To Add Two Numbers using Pointer and Function

#include<stdio.h>

void addition(int, int, int*);

int main()
{
    int a, b, c;

    printf("Enter 2 numbers\n");
    scanf("%d%d", &a, &b);

    addition(a, b, &c);

    printf("%d + %d = %d\n", a, b, c);

    return 0;
}

void addition(int x, int y, int *z)
{
    *z = x + y;
}

Output:
Enter 2 numbers
10
40
10 + 40 = 50

Logic To Add Two Numbers using Pointers and Function

We ask the user to enter 2 numbers and store it inside address of variables a and b. Next we pass the values of a and b and address of variable c to a function called addition(). And then print the result in main method itself.

The motive is to change the value present at address of variable c. That way we can print the result directly inside main method itself, without our function addition() returning any value back to calling function(main()).

Inside addition() method, we add the values passed in first 2 arguments and then store the result back in the address location sent to addition() function as third argument. Function addition() doesn’t return any value, so it has void as its return type.

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

Custom Functions: jQuery

Video tutorial illustrates writing custom functions in jQuery.

Following topics are covered in the video:
Function Declaration.
Function Expression.
Passing parameters.
Returning value.
Returning nothing, etc ..

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
11
12
<html>
<head><title>Functions in jQuery!</title></head>
<body>
 
<span></span>
<button id="name">Software</button>
 
 
<script src="script/jquery-1.8.1.min.js" type="text/javascript"></script>
<script src="script/my_script.js" type="text/javascript"></script>
</body>
</html>

Here we have 1 span tag for display purpose and a button with an id name.

jQuery code: Passing Parameter To Function
my_script.js

1
2
3
4
5
6
7
8
9
$(document).ready( function() {
 fun1("Oracle");
});
 
 
function fun1(text){
  $("span").append(text);
  return false;
}

function is a keyword, fun1 is a function name we have given.
Once the webpage is loaded, fun1 function will be called, and Oracle is passed to it as parameter.
Inside fun1(), the span tag is selected and the passed parameter is appended to the span tag.
Since the function doesn’t return any value back, we have written return false.

jQuery code: Passing Parameter To Function And Returning Value
my_script.js

1
2
3
4
5
6
7
8
9
10
$(document).ready( function() {
 
 var d = fun1(10, 20);
 $("span").append(d);
 
});
 
function fun1(a, b){
     return(a+b);
}

Once the webpage is loaded, fun1 function will be called, and 10, 20 is passed to it as parameters.
Inside fun1(), 10 and 20 are added and the resulting value is returned back to the calling function, where in it is stored in a variable called d, where we append it to the span tag.

jQuery code: Function Expression
my_script.js

1
2
3
4
5
6
7
8
$(document).ready( function() {
  $("#name").click(software);
});
 
var software = function() {
 $("span").append("<h1>Microsoft ltd</h1>");
 return false;
}

Here, once the user clicks on the button(with an id name), the custom function software gets invoked.
Since the function here doesn’t return any value, we have written return false;

jQuery code: Function Expression with Event Binding
my_script.js

1
2
3
4
5
6
7
8
$(document).ready( function() {
  $("#name").bind('click', software);
});
 
var software = function() {
 $("span").append("<h1>Microsoft ltd</h1>");
 return false;
}

Here we bind the event click to the button and then invoke the function software.

Video Tutorial: Custom Functions: jQuery


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

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



Main Purposes of writing a function:
Re-usability of code.
Reduce the number of lines of code.
Cleaner looking code.
We could easily trace, modify and maintain the code.

Helps in Object Oriented Programming, as the data is bind to methods.
We could write the code in such a way that, we could pass different parameters to the same function and get desired results. Hence reducing a lot of code overhead and cost of writing extra useless codes!

Biggest of 2 Numbers Using Function: C++

Find the biggest of two numbers using function and ternary operator.

Basics of functions:

A function is a sub program to perform a specific task.
OR
a group of instructions to perform specific task.

Along with main() it is possible to define our own functions by following these steps:
1. Function prototype or Function declaration.
2. Function call.
3. Function definition.

Function Prototype:

Giving information about the function such as return type, function name and arguments type to the compiler is known as function prototype; It is written at the declaration section.
Syntax:

< return_type > < function_name >( arguments_type );

Example:
int findsum(int a, int b);
float findsum(int a, int b);
void findsum(int a, int b);
int findsum(int a[], int size);
int findsum(int, int);

Function Definition:
Writing the actual code of the function in a block. It is at this stage the task of the function is defined. It is written after the main function.
Syntax:

< return_type >< function_name >(parameters)
{
 
}

Example:

int findsum(int a, int b)
{
 int sum;
 
 sum = a + b;
 return(sum);
}

Function Call:
It is a technique used to invoke a function.
Syntax:

[variable] < function_name >([arguments]);

Example:
res = findsum(10, 20);
res = findsum(x, y);
res = findsum();

Full Source Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include< iostream.h >
#include< conio.h >
 
void main()
{
  int Big(int x,int y);  // Prototype
 
  int a, b;
  clrscr();
 
  cout< <"Enter 2 numbers\n";
  cin>>a>>b;
 
  int res = Big(a, b);   // Function call
 
  cout< <"Biggest = "<<res;
  getch();
}
 
int Big(int x, int y)   // Function Definition
{
  return( x>y?x:y );
}

You must also watch these videos, before continuing with this program:
Find Biggest of 2 Numbers: C++
Biggest of Two Numbers Using Ternary Operator: C++

Video Tutorial: Biggest of 2 Numbers Using Function


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

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



Output:
Enter 2 numbers
420
305
Biggest = 420