Size of Array using Macro and Constant: C Program

In this video tutorial lets see how we can assign size of an array using macros and constants.

Related Read:
For Loop In C Programming Language
Introduction To Arrays: C Programming Language
Keywords, Constants, Variables: C

Disadvantage of Not Using Macro or Constant To Assign Array Size

If requirement of the program/software changes and you need to increase or decrease the array size, then you’ll have to be very careful and scan through the entire source code and make changes at multiple locations. Even if you skip changing the array size information at one place, you’ll start getting wrong results.

And if you have any business logic which makes use of array size, then you’ll have hard time rectifying and debugging the code. It’ll take unnecessary time and effort to make it work correctly once again.

By making use of Macros or constant variables you can handle this very efficiently. You can make the change at one place and it’ll take effect at all the places in your source code.

Watch the video below for demonstration of effectiveness of using macros and constants for assigning size of an array.

Video Tutorial: Assign Size of Array using Macro and Constant: C Program


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

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

Source Code: Size of Array using Macro and Constant: C Program

Without using Macros and/or constants

#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

Here we have a array variable with size 5. We enter 5 integer variables and we display those elements using for loop. In for loop condition we mention the number of times it has to iterate.

Now assume that the requirement changes and we need to increase the size of array from 5 to 7:

#include<stdio.h>

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

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

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

    return 0;
}

Output:
Enter 7 integer numbers
1
2
3
4
5
6
7
Array elements are:
1
2
3
4
5
6
7

As you can see we made edits at 4 places. Its a very simple program and even in that we had to make 4 edits. What if the program is huge and the requirement changes?

Macros

Assign Array size using Macros

#include<stdio.h>

#define N 5

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

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

    printf("Array elements are:\n");
    for(i = 0; i < N; 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

Observe the changes we’ve made in the source code. We’re defining a macro here. Macro template is N and macro expansion is 5. We replace the value 5 inside main method by macro name N.

#include<stdio.h>

#define N 7

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

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

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

    return 0;
}

Output:
Enter 7 integer numbers
1
2
3
4
5
6
7
Array elements are:
1
2
3
4
5
6
7

Assume that the requirement changes and the client wants a list size of 7. Now instead of editing at multiple places, we only change the macro expansion from 5 to 7, and it starts working as intended.

Constants

Assign Array size using Constants

#include<stdio.h>

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

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

    printf("Array elements are:\n");
    for(i = 0; i < N; 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

Observe the changes we’ve made in the source code. We’ve declared and initialized a constant variable N. Constant variable name is N and its value is 5. We replace the value 5 inside main method by constant variable N.

#include<stdio.h>

int main()
{
    const int N = 7;
    int a[N], i;

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

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

    return 0;
}

Output:
Enter 7 integer numbers
1
2
3
4
5
6
7
Array elements are:
1
2
3
4
5
6
7

Assume that the requirement changes and the client wants a list size of 7. Now instead of editing at multiple places, we only change the value of constant variable N from 5 to 7, and the program works as intended.

Note: It’s always considered best practice to either use macros or constant variables to assign array size. This practice will prove to be very advantageous while writing big programs.

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

Registration Form Validation: PHP + jQuery + AJAX (PART 2)

In this video tutorial we illustrate both client side as well as server side validation.

Client side validation using jQuery.
Server side validation using PHP.

To Solve:
Empty values shouldn’t be registered.
Duplicate usernames must not be allowed.
Display appropriate message, in case of duplicate username.

Explanation about HTML file (index.html), Database connection file(db.php):
Registration Form Using jQuery + PHP + AJAX (PART 1)

jQuery File: Client Side Validation
my_script.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
$("#submit").click( function() {
 
if( $("#username").val() == "" || $("#pass").val() == "" )
  $("#ack").html("Username/Password are mandatory fields -- Please Enter.");
else
  $.post( $("#myForm").attr("action"),
         $("#myForm :input").serializeArray(),
 function(info) {
 
   $("#ack").empty();
   $("#ack").html(info);
clear();
 });
 
$("#myForm").submit( function() {
   return false;
});
});
 
function clear() {
 
$("#myForm :input").each( function() {
      $(this).val("");
});
 
}

If the username and the password fields are empty, we display appropriate message and skip the execution of $.post() method.
This ensures that, we do not request data from the server when there is no need for it.

If the user has entered both username and password, then we execute $.post() method and pass the user entered data to process.php file.

PHP File: Server Side Validation
process.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
< ?php
      include_once('db.php');
 
  $username = mysql_real_escape_string( $_POST["username"] );
  $password = mysql_real_escape_string( md5($_POST["pass"]) );
  $fname = mysql_real_escape_string( $_POST["fname"] );
  $lname = mysql_real_escape_string( $_POST["lname"] );
 
 
  if( empty($username) || empty($password) )
  {
  echo "Username and Password are mandatory - from PHP!";
exit();
  }
 
 
 $res = mysql_query("SELECT username FROM users WHERE username='$username'");
  $row = mysql_fetch_row($res);
 
  if( $row > 0 )
    echo "Username $username has already been taken";
  else
  {
     $sql = "INSERT INTO users VALUES('',
                                           '$username', 
                                           '$password', 
                                           '$fname', 
                                           '$lname')";
    if( mysql_query($sql) )
     echo "Inserted Successfully";
   else
     echo "Insertion Failed";
}
?>

At the beginning we check if the username or the password is empty. If they are empty, we echo Username and Password are madatory – from PHP and then stop further execution of the script.

If the username and password are not empty, then we check the user entered username against the usernames present inside the database. If the username is already present inside the database, then we intimate it to the user with a customized message.

Registration Form Validation: PHP + jQuery + AJAX (PART 2)


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

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



Why Validate both client side as well as server side ?
What if javascript has been disabled on client machine i.e., the browser ?
In this situation, our client side validation completely fails. So, server side validation is also important.

Then Why client side validation when server side validation could serve our purpose ?
This is because, client side validation is faster. i.e., if user tries to register empty data, it needs to travel across, reach the server, execute the validation rules script and then travel back to report that the user had submitted empty data and is not acceptable!
Instead of this lengthy, time consuming and costly process, we could simply write a client side validation and it responds back instantly, saving time, bandwidth and hence the cost of processing the data.

Working With Images: Small jQuery Application

In this video tutorial, we shall test our skills in jQuery: bind, unbind, append and remove functions. Also we shall see the use of chain methods.

jQuery Event Handling: Binding and Unbinding
Animate Image with ‘this’ Selector: jQuery
Append/Add and Remove HTML/XML Elements: jQuery

Assume that a client has mailed her requirements to us:
She has 5 images in her html page.
Once the user clicks on a image, a message should popin beside the image.
Image should be clickable only once.
Once the user clicks on other images, the messages appended beside previously clicked image must be removed.

With these requirements in mind, we shall start developing our image based jQuery Application.

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<html>
 <head><title>Working With Images: Small jQuery Application</title>
 <style type="text/css">
 img{
  padding: 10px;
 }
 </style>
 </head>
 <body>
 
   <div> <img src="images/aperture.png" width="69" height="69" /> </div>
   <div> <img src="images/coda.png" width="69" height="69" /> </div>
   <div> <img src="images/finder.png" width="69" height="69" /> </div>
   <div> <img src="images/photoshop.png" width="69" height="69" /> </div>
   <div> <img src="images/safari.png" width="69" height="69" /> </div>
 
   <script type="text/javascript" src="script/jquery-1.8.1.min.js"></script>
   <script type="text/javascript" src="script/my_script.js"></script>
 </body>
</html>

Here we have included 5 images and have added 10px padding using CSS.
Each image is being placed inside a div tag.

Note:
So img is a child of div or div is the parent of img.

jQuery code
my_script.js

1
2
3
4
5
6
7
8
9
$(document).ready( function() {
 
  $("img").click( function() {
   $("b").remove();
   $(this).parent().append("<b>You clicked on Me!</b>");
   $(this).unbind();
 });
 
});

Once the document is ready and the user clicks on a image:
1. Any b tag present in the document is removed. Thus, the message associated with the image which was being clicked previously is removed.
2. The parent tag of the image being clicked: i.e., div tag is selected and a message with b tag is appended to it, which appears beside the image being clicked by the user.
3. The event associated with the image being clicked is removed.

Note:
Use of function().function() is called chain method.
Example:
parent().append();
next().parent().remove(); etc

Make sure to maintain the order of the code. If you replace or rearrange the code in a way other than above, you wouldn’t get expected result.
While practicing, change the order of the code and look for the output, that would help you understand the code and the flow / execution flow well.

Video Tutorial: Working With Images: Small jQuery Application


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

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



Keep testing your jQuery skills by doing some mini projects like this one.
Let it be small, so that it doesn’t take forever to test your skills.

You could even test and enhance your jQuery skills by helping people on our forum.