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

Basics of Arrays: C Program

Lets look at basics of arrays in C programming language. We’ve already covered a lot of stuffs about arrays in Introduction To Arrays: C Programming Language. In this video tutorial we’ll look at some specific things about arrays which we use often.

Related Read:
For Loop In C Programming Language
Sizeof Operator in C Programming Language

Declaring Array Variable

Syntax:

Data_type variable_name[array_size];

Ex: int a[5];

Here array variable is a, it can hold upto 5 integer values.

Index of array starts from zero, and it ends at N-1. N being the size of the array.

For Ex:
int a[N];
Here the first element of array a is at a[0] and the last element is at a[N-1].

Definition of Array

An array is a collection of data items, of same data type, accessed using a common name.

Video Tutorial: Basics of Arrays: C Program


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

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

Source Code: Basics of Arrays: C Program

Printing all the elements of an array

#include<stdio.h>

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

    printf("Array elements are: \n");
    for(i = 0; i < 5; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
Array elements are:
1
2
3
4
5

This prints all the elements of an array. In this program we’re declaring and initializing array variable simultaneously.

Empty curly braces for Array Variable

#include<stdio.h>

int main()
{
    int a[5] = {}, i;

    printf("Array elements are: \n");
    for(i = 0; i < 5; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
Array elements are:
0
0
0
0
0

Compiler will insert zero in all the empty spots.

Un-initialized Array Variable

#include<stdio.h>

int main()
{
    int a[5], i;

    printf("Array elements are: \n");
    for(i = 0; i < 5; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
Array elements are:
6356864
4200750
4200656
46
8

If array variable is left un-initialized it’ll have garbage values inside it.

Array Variable Not fully initialized Manually

#include<stdio.h>

int main()
{
    int a[5] = {3, 2}, i;

    printf("Array elements are: \n");
    for(i = 0; i < 5; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
Array elements are:
3
2
0
0
0

Whenever we assign less values than the array size, the remaining elements will get assigned to 0.

Expression As Array Size

#include<stdio.h>

int main()
{
    int a[2+3] = {3, 2, 1, 0, 5}, i;

    printf("Array elements are: \n");
    for(i = 0; i < 5; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
Array elements are:
3
2
1
0
5

Any valid expression which ultimately resolves to a positive integer is valid inside square brackets.

Negative Integer Number As Array Size

#include<stdio.h>

int main()
{
    int a[-5] = {3, 2, 1, 0, 5}, i;

    printf("Array elements are: \n");
    for(i = 0; i < 5; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
error: size of array ‘a’ is negative
warning: excess elements in array initializer

You can only have positive integer as size of an array and nothing else.

Trying To Assign More Values Than The Array Size

#include<stdio.h>

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

    printf("Array elements are: \n");
    for(i = 0; i < 5; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
warning: excess elements in array initializer

You can’t assign more values than the array size.

Overwrite values present at an index: Array

#include<stdio.h>

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

    a[3]  = 100;

    printf("Array elements are: \n");
    for(i = 0; i < 5; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
Array elements are:
1
2
3
100
5

Here the previous value present at index 3(which can be access using a[3]), is overwritten by value 100.

Garbage Values In Empty Spots: Array

#include<stdio.h>

int main()
{
    int a[5], i;

    a[3]  = 100;

    printf("Array elements are: \n");
    for(i = 0; i < 5; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
Array elements are:
6356864
4200766
4200672
100
8

As you can see, the element at index 3 has 100, and all other elements value is just garbage values.

Array Size In Memory

#include<stdio.h>

int main()
{
    int    a[5];
    float  b[5];
    char   c[5];
    double d[5];

    printf("Int    Array: %d\n", 5 * sizeof(int));
    printf("Float  Array: %d\n", 5 * sizeof(float));
    printf("Char   Array: %d\n", 5 * sizeof(char));
    printf("Double Array: %d\n", 5 * sizeof(double));

    return 0;
}

Output:
Int Array: 20
Float Array: 20
Char Array: 5
Double Array: 40

Each cell in array occupies memory space depending upon its data type. Int and float occupies 4 bytes. Char occupies 1 byte. Double occupies 8 bytes. Also remember, size of data type is machine dependent.

Initializing and Accessing Array Elements

#include<stdio.h>

int main()
{
    int a[5], i;

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

    printf("Array elements are: \n");
    for(i = 0; i < 5; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
Enter 5 integer numbers
1
2
3
4
5
Array elements are:
1
2
3
4
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

Basics of Jade – Template Engine: Node.js

Lets learn some of the basics of Jade Template Engine. Jade is the default template engine for Express Web Framework of Node.js Also note that, Jade and Express are open source product of the same company, so go very well with each other!

jade-template-engine-nodejs-express-web-framework

Using template engine might seem pointless in the beginning, but if you’re building a large-scale application, it’s a handy tool and you’ll feel good about your decision to use one for your project.

Make sure you’ve installed Express Web framework and Jade module locally for your application. You can find the procedure at Express Web Framework: Node.js

Configuration Section
app.js

1
app.set('view engine', 'jade');

This would let your application know that you’ll be using Jade as Template Engine. This way, you need not mention the Template Engines file extension each time.

Jade File: Indentation
index.jade

1
2
3
4
html
 head
  title Technotip
 body

Would output

1
2
3
4
5
<html>
 <head><title>Technotip</title></head>
 <body>
 </body>
</html>

Indentations in Jade decide which element(s) is/are a child off which element.

Jade File: Variable
index.jade

1
2
 - var name = "Love For Design"
 p= name

and

Jade File: String. Minus sign significance
index.jade

1
2
 - var name = "Love For Design"
 p #{name}

Out put Love For Design on the browser, inside a paragraph tag.

Jade File: Code Interpretation – REPL
index.jade

1
 p #{ 1 + 5 }

This outputs 6 on to the browser inside a paragraph tag.

Jade File: String Length Management
index.jade

1
2
3
4
5
6
7
 p
  | My Name is Satish
  | I Love web development
  | I love helping people
  | by teaching them whatever I know
  | I believe, this is a good cause of 
  | spreading knowledge.

This would treat the entire string as a single line text, and out put looks like:
My Name is Satish I Love web development I love helping people by teaching them whatever I know I believe, this is a good cause of spreading knowledge.

Jade File: Id’s and Classes
index.jade

1
2
div#wrapper
  p.highlight I Love Node.js

This would apply the id wrapper to div and highlight class to p tag.

Jade File: Multiple id and class
index.jade

1
2
div#wrapper.content.highlight
  p I Love Node.js

We could even assign multiple id’s and classes to a html element.

Jade File: Anchor Tag
index.jade

1
a(href="/about", rel="nofollow") Satish

This would wrap the word Satish with anchor tag and nofollow attribute.

Jade File: Anchor Tag and Image Tag
index.jade

1
2
a(href="/about", rel="nofollow") Satish
img(src="1.gif", alt="Child Eating KitKat")

This would output Satish with anchor tag and nofollow attribute. Also an image with alt attribute attached to it. Both these tags are siblings.

Jade File: Hyperlink the Image file – Hypermedia
index.jade

1
2
a(href="/about", rel="nofollow")
 img(src="1.gif", alt="Child Eating KitKat")

Indent img tag inside anchor tag and the image gets linked to by the anchor tag.

Jade File: Writing Function inside Jade file
index.jade

1
2
- var fn = function() { return "android KitKat"}
p #{fn()}

This outputs android KitKat to the browser.

Jade File: Accessing elements of Object
index.jade

1
2
3
4
- obj = { name: "Apple", product: "iPhone"}
ul
  li #{obj.name}
  li #{obj.product}

This would output

  • Apple
  • iPhone

Jade File: Accessing elements of an array
index.jade

1
2
3
4
- obj = [ "Nexus 5", "iPhone 5S"]
ul
  li #{obj[0]}
  li #{obj[1]}

This would output

  • Nexus 5
  • iPhone 5S

Jade File: Including another jade file
index.jade

1
2
p
 include show

This would include the contents of show.jade file inside index.jade file.

Basics of Jade – Template Engine: Node.js


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

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



Note:
sign tells jade that the code that follows should be executed.
= sign tells that the code should be evaluated, escaped and then output.

Stay subscribed: In next video we’ll show how to use bootstrap + Express + Jade + Node.js
Building a web form. Loops and Conditional statements present in Jade.

jQuery Basics: Replace Text/String Inside HTML Document

Today lets start with learning jQuery.

In this video we show you where to get the jQuery library file and the text editor we are using to write our jQuery programs.

Since we are on Windows 7, we choose pspad.

For all the links and installation procedures, please watch the short video below.

To start the day 1 of learning jQuery, let’s do a simple string replacement program.
We shall change the text inside p tag once the user clicks on the text inside p tag.

Complete Code
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<html>
 <head><title>jQuery Basics</title>
 
  <script src="script/jquery-1.8.1.min.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(document).ready( function() {
      $("p").click( function(){
 
          $("p").html("jQuery is awesome!");
 
      } );
    } 
    );
  </script>
 </head>
 <body>
                  <p>JavaScript</p>
 </body>
</html>

First include the jQuery library file..and in next script tag, start writing your jQuery code.
The code is triggered once the html document loads i.e., when it is ready.
Once the page loads, a anonymous function is being called and is ready to register the user events.

When a user clicks on the p tag or its content, the string content(which is a separate node in DOM), is changed to jQuery is awesome!

Video Tutorial: jQuery Basics: Replace Text/String Inside HTML Document


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

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



Write this program and setup your jQuery learning environment and be ready for the future video tutorials.

Try to change the tags, content and the code and also invoke the action for other user events other than just click.