Introduction To Arrays: C Programming Language

Arrays is one of the most important topics in C programming language. In this video tutorial I’ll give you a brief introduction to Arrays.

Declaring Normal/regular Variable

Syntax:

Data_type variable_name;

Ex: int a;

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.

Definition of Array

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

Important Notes About Arrays In C

1. All the elements inside an array MUST be of same data type.
2. If you try to enter more elements than the size allocated to the array, it’ll start throwing error.
3. If you input less number of elements than the size of array, then remaining memory blocks will be filled with zeros.
4. Array variable name(without index) holds the base address or the address of first element of the array.
5. Previous address plus the size of the data type of the array gives the address of next element in the array.

Related Read:
For Loop In C Programming Language
Basics of Pointers In C Programming Language

Types of Array

There are two types of arrays in c programming:
1. One-dimensional array.
2. Multi-dimensional array.

In today’s tutorial we’ll be learning basics of one-dimensional array.

Since one-dimensional array contains some linear type of data, its also called as list or vector.

Two-dimensional arrays are often referred to as Tables or Matrix.

Video Tutorial: Introduction To Arrays: C Programming Language



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

Source Code: Introduction To Arrays: C Programming Language

Array Read Write: integer type array

#include<stdio.h>

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

    printf("Enter 5 integers\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 integers
6
8
5
9
2
Array elements are:
6
8
5
9
2

Declaring and Initializing: integer type array

#include<stdio.h>

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

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

    return 0;
}

Output:
Array elements are:
4
5
1
9
2

Since a[5] is of type integer, all the array elements must be integers too. we must enclose all the elements inside curly braces and each element must be separated by a comma.

Trying to insert more values than array size

#include<stdio.h>

int main()
{
    int a[5] = { 4, 5, 1, 9, 2, 6 }, 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.

In above source code we are trying to insert 6 integer values inside a[5], which can hold only 5 integer numbers. Hence compiler throws error and stops further compilation.

Inserting less elements/values than array size

#include<stdio.h>

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

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

    return 0;
}

Output:
Array elements are:
4
5
1
0
0

Here array size is 5, but we’re only initializing 3 integer values. So rest of it will be filled with zeros.

To avoid conflict between number of elements and array size

#include<stdio.h>

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

    printf("Array elements are:\n");

    for(i = 0; i < 8; i++)
    {
        printf("%d\n", a[i]);
    }

    return 0;
}

Output:
Array elements are:
4
5
2
6
1
2
4
5

Here we’re not specifying the size of array variable a. Compiler dynamically allocates size to it based on the number of integer numbers assigned to it.

Another method of assigning values to array variable

#include<stdio.h>


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

    a[0] = 4;
    a[1] = 5;
    a[2] = 9;

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

    return 0;
}

Output:
Array elements are:
4
5
9

We could use the index and insert the value at specified position inside an array.

Note: Indexing starts from 0 in C programming language. For example, if you have an array a[5], then the elements are accessed one by one like this: a[0], a[1], a[2], a[3], a[4].

Overwriting value of elements in an array

#include<stdio.h>

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

    a[5] = 100;

    printf("Array elements are:\n");

    for(i = 0; i < 8; i++)
    {
        printf("%d\n", a[i]);
    }

    return 0;
}

Output:
Array elements are:
4
5
2
6
1
100
4
5

Here previous value of a[5], which is 2 will be replaced by 100.

Pointers and Arrays

#include<stdio.h>

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

    printf("%d\n", a);
    printf("%d\n", &a[0]);

    return 0;
}

Output:
6356716
6356716

Here variable a will have base address or the address of first array element. In above program we’re printing the value of a and also the address where the first element of the array is stored. Both display the same address, meaning: a has base address or the address of first element in the array.

Pointers and Arrays

#include<stdio.h>

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

    printf("%d\n", &a[0]);
    printf("%d\n", &a[1]);
    printf("%d\n", &a[3]);
    printf("%d\n", &a[4]);

    return 0;
}

Output:
6356716
6356720
6356728
6356732

If you observe above addresses, there is a difference of 4 between each address. That’s because each memory cell stores integer type data(in above program), which is allocated with 4 bytes of memory(it is machine dependent).

Characters and Arrays

#include<stdio.h>

int main()
{
    char ch[5] = { 'A', 'P', 'P', 'L', 'E' };
    int i;

    for(i = 0; i < 5; i++)
        printf("%c", ch[i]);

    return 0;
}

Output:
APPLE

String and Arrays

#include<stdio.h>

int main()
{
    char ch[5] = { 'A', 'P', 'P', 'L', 'E' };

    printf("%s", ch);

    return 0;
}

Output:
APPLE&

Array of characters is called as string. Observe the output of above program. It has ampersand symbol at the end. To remove this kind of random symbols we need to let the program know the end of a string.

#include<stdio.h>

int main()
{
    char ch[6] = { 'A', 'P', 'P', 'L', 'E', '\0' };

    printf("%s", ch);

    return 0;
}

Output:
APPLE

Look at the last element in the array. Its forward slash followed by zero. That indicates end of string.

#include<stdio.h>

int main()
{
    char ch[] = { 'I', 'B', 'M', '\0' };

    printf("%s", ch);

    return 0;
}

Output:
IBM

#include<stdio.h>

int main()
{
    char ch[] = { 'I', 'B', 'M', '\0' };

    printf("%d\n", &ch[0]);
    printf("%d\n", &ch[1]);
    printf("%d\n", &ch[2]);

    return 0;
}

Output:
6356732
6356733
6356734

Character type data has 1 byte of allocated memory. Since this array stores characters in each cell, the address of consecutive element is 1 byte apart.

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

Structure of a basic C Program

Lets write our first C program – the typical “Hello World!” program.

In this video tutorial lets learn the structure of a basic C program:
1. Preprocessors – include directive.
2. Main method/function.
3. printf method/function.
4. Semicolon syntax.
5. Indentation for readability of code.

Source Code: A Simple C Program

#include<stdio.h>

int main()
{
    printf("Microsoft\n Apple\n Oracle\n Google\n Yahoo\n");
    return 0;
}

Output:
Microsoft
Apple
Oracle
Google
Yahoo

Structure of a basic C Program



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


Preprocessor statement

The “include” directive which we see in the first line is a preprocessor directive. Here we are including a standard library file which has some set of useful functions in it, which we are using in our “Hello World” C Program.

stdio stands for “Standard Input Output”. As the name suggests this library file has functions to read and write data to console window, along with other many useful functions. For example, printf() is a function present in stdio.h library file. We simply use it in our program to print data on to the console window. We need not know the implementation details of printf method/function.

main() method

Main method or function is part of all ‘C’ programs. It’s entry point of any C program execution. Function is a way of grouping some code together. We can write any logic/statements inside a function.

It’s a standard that main always returns a integer value. Thus main is preceded by a keyword called int, which means integer. It’s a keyword or reserve word. We’ll know more about keywords(or reserve words) in a separate video tutorial. Since main method needs to return a integer value, we explicitly return 0 at the end.

Readability of code

It’s very important that we write code which is readable. It helps in maintaining the code. Large programs get too clumsy very easily and reading and understanding code often becomes difficult. So we need to indent the code and make sure its readable as far as possible.

Note:
Main method/function doesn’t take any argument.

Getting Started With HTML5 Game Development: Phaser

From today lets learn HTML5 browser game development – applies both to desktop as well as mobile browsers. You’ll be able to build mobile game apps and launch it to play store or app store.

phaser logo

Phaser is an open source HTML5 game framework created by Photon Storm. It’s designed to create games that will run on desktop and mobile web browsers. A lot of focus was given to performance inside of mobile web browsers, a growing and important area of web gaming.

Video Tutorial List At One Place:
Phaser Video Tutorial List: Game Framework

In this introductory video you’ll be learning:
1. How to get started with Phaser.
2. Download the library and incorporate it into your new game project.
3. Running the game inside the server – in our case, we’re making use of Node server.
4. Quick starter guide to initiate and run the game project.
5. Placing the image in cache – using preload method.
6. Placing the cached/preloaded image(sprite) on to the game stage/container – using create method.
7. Setting the game stage / container background color.
8. Resizing the stage/container and trick to make use of entire device screen for our game.

Phaser Version: 2.4.9 (immediately 2.5.0 was released, so from tomorrows video we’ll be using 2.5.0)
OS used for Demo: Windows 10
Server used: Node Server



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



Node Server
1. Node.js Video Tutorial List
2. Express Web Framework: Node.js

HTML File – index.html

< !DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="javascripts/library/phaser.js"></script>
</head>
<body>
     <div id="gameContainer"></div>
</body>
</html>

Start with the HTML5 doc type as the first line, as Phaser is a HTML5 Game framework. Then you need to download the phaser library, and include it inside your project. If you’re using Node server, then place the library file and all the files inside the public directory. Use phaser.js file (the unminified version) for development and phaser.min.js file (the minified version) while pushing the code to production server.

You can optionally place a div container to render the game or the game engine will consider entire html body as game stage or container. In our case, for demonstration we’ve placed a div with id gameContainer and we’ll make phaser to use this to render the game objects.

JavaScript Code – Game Code

    var game = new Phaser.Game(window.innerWidth, window.innerHeight, 
                               Phaser.AUTO, 'gameContainer', {
                   preload: preload, create: create
               });
    function preload(){
        game.load.image('logo', '/images/logo.png');  
    }
    function create(){
        game.add.sprite(10, 100, 'logo');  
        game.stage.backgroundColor = '#e7e7e7';
    }

Create a game object with the help of Phaser.Game class. You need to pass the game stage width and height, then we can let Phaser decide whether to user WebGL or canvas to render the game – using Phaser.AUTO property. Phaser gives priority to WebGL, if it’s not present then it’ll make use of Canvas. Next we can optionally specify the game container id, and then the game code.

In this example I simply wrote the code and directly passed it as an argument. This works. And this is ok, if the game code is small. But in big game projects we need to follow modularity – which I’ll teach in my next video tutorial.

A valid Phaser state must have atleast one of these methods – preload, create, update.

preload method: is used to load all the game assets. Once loaded, these assets are stored in cache.
create method: here we make use of cached assets and present them on our game stage or container. We also create other objects needed for our game.
update method: this method is repeatedly called and our game objects are constantly updated to create movements or update the game objects or objectives!

In above code, inside preload method, we are using game object and loading a image and giving it a name called logo, by making use of game.load.image() method. First parameter is a name we give it to the image or sprite as we’ll start calling it from now. The second parameter is the path of the actual image – this can even be a remote server URL. Next we place this image on our game stage using game.add.sprite() method, by using create method. I’ve also shown you how to change the background color of the stage by using game.stage.backgroundColor property.

Full Screen Game
Often time when we’re developing game for mobile device(android or iOS game app), we would want to use full screen of the device – we can achieve this by passing window.innerWidth and window.innerHeight parameter while creating game object – as shown in the code – var game = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.AUTO);

Full source code

< !DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="javascripts/library/phaser.js"></script>
</head>
<body>
<div id="gameContainer"></div>
 
<script type="text/javascript">
    var game = new Phaser.Game(window.innerWidth, window.innerHeight, 
                               Phaser.AUTO, 'gameContainer', {
                    preload: preload, create: create
                });
    function preload(){
        game.load.image('logo', '/images/logo.png');  
    }
    function create(){
        game.add.sprite(10, 100, 'logo');  
        game.stage.backgroundColor = '#e7e7e7';
    }
</script>
</body>
</html>

In my next video tutorial I’ll show how to write modular code to handle big game projects – I’ll show it by using same code we used today, so that you’ll feel somewhat familiar.

Please make sure you download the phaser library and try it yourself – this looks like a small example, but worth trying, if you’re a beginner. Stay subscribed, more Phaser video tutorials are on the way.

Basic Routing Using Express: Node.js

Today let us learn a very important lesson in any web application development i.e., setting up the routes.

basic route using Express Node.js

Express is an excellent web framework for Node.js

Basic Routing with Express
app.js

1
2
3
app.get('/', function(req, res){
    res.send("Hello World!"); 
});

This would output Hello World when users access the index or home page.

Basic Routing with Express
app.js

1
2
3
app.get('/myPhone', function(req, res){
    res.send("Sony Xperia!"); 
});

This would output Sony Xperia! when users access the /myPhone route.

Dynamic Routing with Express
app.js

1
2
3
app.get('/user/:username', function(req, res){
    res.send(" "+req.params.username+"'s profile!"); 
});

When we request information of particular user by using his username in the URL, it fetches the username using request object and displays appropriate message.
Example: If the user requests /user/Satish it’ll output Satish’s profile!

Public Folder

If we put some files inside our public directory, it would be convenient if some middlewares fetch the files directly upon user request, instead of writing routes for all those files. Connect module which is a dependency of Express web framework takes care of this.

Middleware for public folder files
app.js

1
2
3
4
5
6
var express = require('express');
var path = require('path');
 
var app = express();
 
 app.use(express.static(path.join(__dirname, 'public')));

This would set the public directory.

Middleware for public folder files
app.js

1
2
 app.use(app.router);
 app.use(express.static(path.join(__dirname, 'public')));

If you want your custom routes to be checked before the public folder, then you could specify it using another middleware, i.e., app.router

Note that, the ordering of Middleware is significant.

Sending HTML in Routs: Express
app.js

1
2
3
4
5
6
7
8
9
10
app.get('/', function(req, res){
    var msg = [
               "<h1>I love Google..</h1>",
               "<p>Because they make awesome products",
               "<br />like my Nexus 7 Tablet",
               "which is so amazing!"
    ].join("\n");
    res.send(msg); 
});
</p>

This would out put with all HTML semantics on the browser.

Get, Post, Put, Delete Requests
Web browsers by default support only get and post requests. But we can override methods and make sure our Node.js application supports even the Put and Delete requests.

Post Request
HTML Form
index.html present in public directory

1
2
3
4
5
6
7
8
9
10
11
12
13
< !DOCTYPE html>
<html>
<head>
<title>Enter your name</title>
</head>
<body>
<form action="/user" method="POST">
<label for="name">Name: </label>
 <input type="text" name="name"/>
 <input type="submit"/>
</form>
</body>
</html>

Here we have a form with post method and also take note of action field value.

POST Route
app.js

1
2
3
4
5
app.use(express.bodyParser());
 
app.post('/user', function(req, res){
    res.send("Submitted user's name is: "+req.body.name);  
});

Inorder to parse the HTML page, you’ll need bodyParser middleware. Once you have it in place you can get form field entries and use it to insert the data into database or simply display as in our case with this example.

We could similarly write code for PUT and DELETE requests.
PUT & DELETE Routes
app.js

1
2
3
4
5
6
7
8
9
10
app.use(express.bodyParser());
app.use(express.methodOverride());
 
app.put('/user/:userId', function(req, res){
    res.send("Editing user with userid: "+req.params.userId);  
});
 
app.delete('/user/:userId', function(req, res){
    res.send("Editing user with userid: "+req.params.userId);  
});

By getting the unique userId of the user, you could fetch the data from database and make changes and update the information using Put request. Similarly, using the unique userId of the user, you could select and delete the information about the user!

Basic Routing Using Express: Node.js



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



Separating Route Files
As your application grows, its hard to keep the code cleaner and maintainable, so it’s always a good idea to separate these kind of information from the main application file. So we create a file called routes and include it as a local module in our main application file.

External Route File
/routes/index.js

1
2
3
4
5
6
7
/*
 * GET home page.
 */ 
exports.index = function(req, res){
  res.send('Google Nexus 5 To Be Release Shortly ..');
};

exports is a global provided by node.js
index is a name given by us; it’s a property name and we assign a function to it.

Accessing External Route File
app.js

1
2
3
var routes = require('./routes');
 
app.get('/', routes.index);

This would output: Google Nexus 5 To Be Release Shortly ..

Object Oriented Programming Basic: PHP

Video tutorial illustrates basics of OOP in PHP.

Things covered:
Defining class.
Creating Objects.
Public and Private access of Properties/Data.
Separating Class file and the application file.

What is a Class ?
A class is simply a representation of a type of object. It is the blueprint/ plan/ template that describe the details of an object. A class is the blueprint from which the individual objects are created. Class is composed of three things: a name, attributes, and operations.

Class Add
add.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
< ?php
class Add
{
private $a;
private $b;
 
function setValues($v1, $v2)
{
   $this->a = $v1;
   $this->b = $v2;
}
 
function add()
{
return( $this->a + $this->b );
}
}
?>

class is a keyword. Add is the name of the class we’ve assigned.
$a and $b are two variables of class Add. These have private access specifier, meaning, they’re not accessible directly from outside the class.
Public access specifier indicates that they can be accessed even outside the scope of a class. Private variables are treated as safe, so we prefer that.

Since private variables are accessed inside the class, we declared two methods inside the class Add. i.e., setValues() and add()
setValues() has two parameters which are then assigned to the local variables $a and $b using the $this pointer.

$this pointer references to the object which is currently pointing to it.

add() method adds the user passed values and returns the result.

Application File
index.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
?php
 include_once('add.php');
 
$add = new Add();
 
$add->setValues(50, 100);
echo $add->add();
 
$add->setValues(150, 100);
echo '<br />'.$add->add();
 
$add2 = new Add();
 
$add2->setValues(500, 1000);
echo '<br />'.$add2->add();
 
?>

Here we include the add.php file and create an object of (class)type Add.
Using this object we pass values to setValues(), and then call add() method, which returns the added value of the passed numbers. which is then output to the browser.

We could create as many objects as we wish and then pass and output as many results as required, without altering the class file what so ever, once finalized.

So this is the power of Object Oriented Programming.
This way we could manage complex applications easily or in an organized/standard way.
Increase code re-usability.
Also reduce maintenance cost etc..

Object Oriented Programming Basic: PHP



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



Why OOP in PHP ?
Most web projects still use procedural i.e., function based software development approach. And honestly, it has no issue, because most web projects are so small scale and straight forward that they don’t require OOP in most cases.

But for complex application development, you need OOP for effectiveness.
Like, if you want to build a home, you need a lot of planning, preparation and some standard approach to build it.