Protec Computer Academy (An ISO 9001:2015 Certified Institute, Powered by E-Max Education, Branch Code EMAX/EK-80503, Registered by government of India.) is a best IT training center in Siwan with 100% Job placement assistance. Where you can learn Programming, WebDesigning, Hardware|Networking, Blogging, WordPress, Digitial marketing, English Speaking, And many more...| All certificates are valid in Government Jobs as well as in Private Companies. *** At Tara Market, Beside Vishal Mega Mart - Siwan*** +917541905230, Email- ahmad.irshad781@gmail.com *** Follow us on | | @welcome2protec

Sunday, November 29, 2020

What is address of operator and it's need?

Ahmad Irshad
Address of Operator | welcome2protec.com

Address of operator (&) is used to access the address of any variable by prepending the ampersand sign (&) with a variable name. You can see at below example to understand it better. 


What is address or memory location of a variable?

In C language, every variable gets a memory location (Address of variable) somewhere in the RAM when it is declared, which help us to access the value of that variable. This memory location has a unique address in hexadecimal format something like 0xbffd8b3c. Simply you can say, A memory location where data is stored is called address of variables.

Address of variable | welcome2protec.com
Address or memory location of variables | welcome2protec.com

Let’s consider a scenario: In a computer network every computer has a unique IP address if you need data from that computer we need to access that computer by using IP address. The same way if we need to access the value of variable ‘x’ we need to access memory location of that variable by using address of (&) Operator with format specifier either %p, %x or %u.


How to access address or memory location of a variable?

Address of  operator (&) is used to specifying the address location of the Variable in C Language.

For Example:

/*while Taking The Input form user */
scanf("%d", &x); 
/*Here address of operator (&) Points to the Memory Location of variable x */

Let's say the address assign to variable x is 0xbffd8b3c, which means whatever value will be assigned to x should be stored at the location 0xbffd8b3c. As you can see in the above diagram 

As I mentioned at the beginning of this tutorial, Address of operator (&) is used to access the address of any variable by prepending the ampersand sign (&) with a variable name. Now let's see the below example how to access the address of x?

/*Program to print both value and address of variable x */.
int main()
{
 int x = 10;
 /*Printing the value of variable x*/
 printf("Value of x = %d\n" , x);
 
 /*Printing the address of variable x */
 printf("Address of x = %u" , &x);
 return 0;
}
/* Here address of x will be displayed on the screen.*/ 

Output:

When the above code is compiled and executed, it produces the following result −

Value of x = 10  
Address of x = 0xbffd8b3c

Address of (&) operator also used in passing the reference in the function arguments.

//Pass By Reference  
void check(int * ,int *); //Function Declaration 
// Check is a function taking 2 Arguments pointer to integer. 
 
check(&a,&b); // Function Call 
 //Here The Passing The Address of a and b to the Function Call.

Points to remember:

  • '&' is known as Address of operator or ampersand.
  • It is an unary operator.
  • '&' is also known as referencing operator.
  • Operand must be the name of variable.
  • '&' Address of operator returns address of a variable.

Infinite loop in C

Ahmad Irshad
Infinite loop in C | welcome2protec.com

Infinite for loop:

An infinite for loop is the one which goes on repeatedly for infinite times. This can happen in two cases:

1) When the loop has no expressions.

for(;;)
{
 printf("Welcome2Protec");
}

The above code runs infinite times because there is no test expression to terminate the loop. Hence, Welcome2Protec gets printed infinite times.

2) When the test condition never becomes false.

for(i=1;i<=5;)
{
 printf("Welcome2Protec");
}

In the above case, the statement Welcom2Protec gets printed infinite times because the test condition never becomes false. The value of i remains the same because it is never updated and thus the value of i remains smaller than 5 for each iteration.


Empty for loop

An empty for loop is the one which has got no body. In simple words, it contains no statements or expressions in its body. It can be used for time-consuming purposes. Each iteration takes its own time for compilation and execution. Usually, it is too small to be of any significant importance. Here’s the syntax of an empty for loop:

for(i=1;i<=5;i++)
{}


More on this to be updated soon...



Thursday, November 26, 2020

Nested for loop in C

Ahmad Irshad
Nested for loop in C | welcome2protec.com

Nested For Loop:

In the previous tutorial of if-else, control statements we saw what nested if is. Nested for loop refers to the process of having one loop inside another loop. We can have multiple loops inside one another. The body of one ‘for’ loop contains the other and so on. The syntax of a nested for loop is as follows (using two for loops): Let's have a look at the below example:



Syntax:

for(initialization; test; update) 
{
  for(initialization; test; update) //using another variable
  {
    //body of the inner loop
  }
 //body of outer loop(might or might not be present)
} 

Example 1: Nested For Loop

/*Program to prints a triangular pattern numbers*/
#include <stdio.h> 
int main()
{
 int i,j;
 for(i=1; i<=5; i++)
 {
  for(j=1; j<=i; j++)
   printf("%d", j);
  
   printf("\n");
 }
 return 0;
 }

Output

1 
12 
123 
1234 
12345 

Explanation:

Above program prints a triangular pattern. Now, the outer loop starts with i=1 and checks the condition whether i<= 5 is true or not which is true so the control goes on the body which contains another loop. This loop starts with the initial value as j=1 and checks if j<=i which is true and hence prints the value of j.

In the next iteration, the condition of the inner loop becomes false and the control exits the inner loop and changes the line. Now it goes for the next iteration of the outer loop and the process goes on. unless the condition becomes false and the loop terminates and the program ends.


Example 2: Nested For Loop

// Example of nested for loop:
#include <stdio.h>
int main()
{
    for(i=0; i<2; i++)
    {
        for(j=0; j<=3; j++)
        {
           printf("%d, %d\n", i, j); 
        {
        sum += count;
    }
    return 0;
 }

Output

0, 0
0, 1
0, 2
0, 3
1, 0
1, 1   
1, 2  
1, 3







Wednesday, November 25, 2020

Difference between while & do while loop in C

Ahmad Irshad
Difference between while & do while loop in C


do...wile loop is similar to while loop, however is a difference between them: In while loop, condition is evaluated first and the statements inside loop body gets executed, on the other hand in do...while loop, statements inside do...while gets executed first and then condition is evaluated.

A simple example of while loop:

#include <stdio.h>
#include <conio.h>	
void main()
{	
 int i = 1;					
 while(i < 5){
  printf("protec");
  i++;
 }
 getch();
} 

Same example using do...while loop:

#include <stdio.h>					
#include <conio.h>						
void main()					
{
 int i = 1;
 do{
  printf("protec");			
  i++;
 }while(i < 5);			  
 getch();	   
}

Output:

Protec
Protec
Protec
Protec
Protec

Conclusion:

If you try and compare both the set of codes above, you will notice that there is not much difference between while and do while loop.

The major difference is that the while loop has the condition at the starting point whereas the do...while loop has the condition at the end of the loop.

Also, if you notice a minor fact here, there is a semicolon at the end of the do...while looping condition whereas it does not exists in case of the while loop.

The statements within the while loop will never execute if the while condition is false however in case of a do...while loop the block statements are going to be executed at least once.


while loop:

  1. Entry conditioned loop
  2. Condition is checked before loop execution
  3. Never execute loop if condition is false
  4. There is no semicolon at the end of while statement
  5. Lower execution time and speed
  6. No fixed number of iterations

do...while loop:

  1. Exit conditioned loop
  2. Condition is checked at the end of loop
  3. executes false condition at least once since condition is checked later
  4. There is semicolon at the end of while statement
  5. Higher execution time and speed
  6. Minimum one number of iterations

Tuesday, November 24, 2020

For loop in C

Ahmad Irshad
Loop in C | welcome2protec.com


A loop is used for executing a block of statements repeatedly until a given condition returns false.

There are three types of loop in C programming.

  1. for loop
  2. while loop
  3. do....while loop

In this tutorial, We will learn about for loop. Rest two loops(while and do...while loop) will learn in the next tutorial.



For loop in C:

For loop is the most commonly used looping technique. The reason why it is so popular is because it has all the three parts of the loop: initialization, test expression, and update expression in the same line.

Syntax

for (initializationStatement; testExpression; updateStatement)
{
    // statements to be executed repeatedly.
}

How does a for loop work in C?

Step 1: First initialization happens and the counter variable gets initialized.

Step 2: In the second step the test expression (condition) is checked, where the counter variable is tested for the given condition, if the condition returns true then the C statements inside the body of for loop gets executed.

Step 3: If the condition returns false then the for loop gets terminated and the control comes out of the loop.

Step 4: After successful execution of statements inside the body of loop, the counter variable is incremented or decremented, depending on the operation (++ or –). And again the test expression(condition) is checked.

This process is goes until the test expression(condition) is false. And when the condition is false, the loop will be terminated. Lets understand with a simple example at below.

To learn more about test expression or condition visit relational and logical operators.


Flow chart of for loop in C:

For loop | welcome2protec.com
For loop | welcome2protec.com

Example 1: Program to print number using for loop

// Print numbers from 1 to 10
#include <stdio.h>

int main() {
  int i;

  for (i = 1; i <= 10; ++i)
  {
    printf("%d ", i);
  }
  return 0;
}

Output

1 2 3 4 5 6 7 8 9 10

Explanation:

Here we have given the initial value of i as 1 (initialization). The test condition is i<=10 and the update expression is i++.

Let’s understand how this works. In the beginning, the control goes to the initial condition and assigns the value 1 to i. Now it checks whether 1<=10 which is true. Since the condition is true the control flows to the body of the loop and prints 1.

the control flows back to for again. Now, it updates the value of i (i=2) and checks the condition again whether 2<=10 which stand true again. So the control again flows to the body of the loop and prints 2 again. (Note that the control does not go back to the initialization expression in the next iteration).

Similarly, the process continues for values of i =3, 4,5,6,7,8,9, and 10. When i becomes equal to 11, the condition i<=10 becomes false and the loop terminates and the program ends.


Example 2: Program to calculate the sum of first n natural numbers using for loop

/* Program to calculate the sum of first n natural numbers.
* Positive integers 1,2,3...n are known as natural numbers. */

#include <stdio.h>
int main()
{
    int num, count, sum = 0;
    printf("Enter a positive integer: ");
    scanf("%d", &num);

    // for loop terminates when num is less than count
    for(count = 1; count <= num; ++count)
    {
        sum += count;
    }
    printf("Sum = %d", sum);
    return 0;
}

Output

Enter a positive integer: 10
Sum = 55

Different types of for loop in C:

I am using variable num as the counter variable in all the following examples.

1) Here instead of num++, I’m using num=num+1 which is same as num++.

Example 1: num++ (or num = num + 1)

/* Here instead of num++, I’m using num=num+1 which is same as num++. */
 for(num = 20; num <= 20; num=num+1)
 
 /* num++ or ++num can be written as num = num + 1 
  * num += count can be written as num = count + 1 */

2) Initialization part can be skipped as you can see at below example, since you can initialized it before the loop. But don't forget to write Semicolon (;) before condition else you will get compilation error.

Example 2: Initialization part can be skipped

/*Initialization part has been skipped and initialized it before the loop.*/
 num = 20;
for(; num<=20; mum++)
 

3) Like initialization, you can also skip the increment part as you can see at below example. In this case semicolon (;) is must after condition (test expression). In this case the increment or decrement part is written inside the loop.

Example 3: Like initialization, increment part can be skipped too

for(num=10; num<=10;)
{
    //statements
    num++;
}

4) This is also possible. The counter variable is initialized before the loop and incremented inside the loop.

Example 4:

int num=10;
for(; num <= 10;)
{
  //statements
   num++;
}

5) In C, multiple variables can be initialized in the for loop. Let's take a simple example to understand it

Example: Multiple variables can be initialized

/*Multiple variable initialization*/
for(i = 0, j = 1; i <= 5 && j <=5; i++, j++;)









Monday, November 23, 2020

switch case statement in C

Ahmad Irshad
switch-case statement | welcome2protec.com

The switch case statement is used when we have multiple options (choice) and we need to perform a different task for each option. You can do the same thing with the If...else...if ladder.


Syntax:

switch(expression){    
 case constant1
  //code to be executed;    
 break;  //optional  
 case constant2
  //code to be executed;    
 break;  //optional  
 ......    
    
 default:     
  code to be executed if all cases are not matched;    
}    

How does the switch statesmen work?

The expression is evaluated once and compared with the values of each case label.

  • If there is a match, the corresponding statements after the matching label are executed. For example, if the value of the expression is equal to constant 2, statements after case constant 2 are executed until break is encountered.
  • If there is no match, the default statements are executed.

Flow Chart of switch...case statement:

switch-case statement | welcome2protec.com
switch-case statement | welcome2protec.com

Lets take a simple example to understand the working of switch...case statement in c.

Example 1: switch...case in C:

#include <sdtio.h> 
int main(){    
  int number=0;     
  printf("enter a number:");    
  scanf("%d", &number);    
  switch(number){    
   	 case 10:    
 		printf("number is equals to 10");    
 		break;    
 	 case 20:    
 		printf("number is equal to 20");    
 		break;    
   	 case 30:    
  		printf("number is equal to 30");    
 	 	break;    
 	 default:    
 		printf("number is not equal to 10, 20 or 30");    
    }    
    return 0;  
 }

Output

Output 1:
 enter a number:4
 number is not equal to 10, 20 or 30

Output 2:
 enter a number: 20
 number is equal to 20

There is a default statement in switch...case which is optional. If switch expression does not match with any case, default statement are executed by the program. As you can see in output 1.


Example 2: Switch...case

#include <stdio.h>   
int main () { 
 
   /* local variable definition */ 
   char grade = 'B'; 
 
   switch(grade) { 
      case 'A' : 
         printf("Excellent!\n" ); 
         break; 
      case 'B' : 
      case 'C' : 
         printf("Well done\n" ); 
         break; 
      case 'D' : 
         printf("You passed\n" ); 
         break; 
       
      default : 
         printf("Invalid grade\n" ); 
   } 
   printf("Your grade is  %c\n", grade ); 
   return 0; 
} 

When the above code is complied and executed, it produces the following result.

Output

Well done
You grade is B

You can use the break statement to end processing of a particular case within the switch statement and to branch to the end of the switch statement. Without break, the program continues to the next case, executing the statements until a break or the end of the statement is reached. In some situations, this continuation may be desirable.

The default statement is executed if no case is equal to the value of switch ( expression ). If the default statement is omitted, and no case match is found, none of the statements in the switch body are executed. There can be at most one default statement. The default statement need not come at the end; it can appear anywhere in the body of the switch statement. A case or default label can only appear inside a switch statement.


Example 3: Switch case

In absence of break, all cases below the intended case gets executed one-by-one. Lets take an example to understand it better.

#include <stdio.h>
int main()
{
  int x = 0;
  switch(x) 
  { 
	case 0 : printf("\n Its a zero"); 
 
	case 1 : printf("\n Its a one"); 
 
	default : printf("\n Its something else"); 
  }
  return 0;
}

Output

INPUT : x = 0 
	Its a zero 
	Its a one 
	Its something else

In above code, if I didn’t use the break statements, then all the cases below the correct case ( case 0) are executed unintentionally. To prevent this ‘break statements’ are used. See below example.


Example 4: Switch case

#include <stdio.h>
int main()
{
  int x = 0;  
  switch(key) 
  { 
	case 0 : printf("\n Its a zero"); 
			 break; 
 
	case 1 : printf("\n Its a one"); 
			 break; 
 
	default : printf("\n Its something else"); 
			  break; 
  }
  return 0;
}

Output

INPUT : x = 0  
It's a zero 






Sunday, November 22, 2020

if-else and ladder if-else in C

Ahmad Irshad
if...else and ladder if...else | welcome2protec


If statement have an optional else block. Here, we must noticed that, if and else block cannot be executed simultaneously. See the below syntax of if...else statement.



Syntax:

if (Condition) {
  // statements to be executed if the condition is true
}
else {
  // statements to be executed if the condition is false
}

How if...else statement works?

  • If condition returns true then the statements inside the body of  “if” are executed and the statements inside body of “else” are skipped.
  • If condition returns false then the statements inside the body of  “if” are skipped and the statements in “else” are executed.

Flow chart of if...else statement:

Flow chart of if...else | welcome2protec
Flow chart of if...else statement in C

Example 1: If...else Statement

Let's understand with a simple example to check whether a number is even or odd using if-else statement.

/* Program to check whether a number is even or odd using if-else */
#include <stdio.h>   
int main(){    

int number=0;    
printf("enter a number:");    
scanf("%d",&number);     

if(number%2==0){    
 printf("%d is even number",number);    
}    

else{    
 printf("%d is odd number", number);    
}     
return 0;  
}

Output:

Enter a number:14
14 is even number

In above, when the user enter number 14 the condition (number % 2 == 0) is returns true. Hence, the statement inside the body of "if" is executed.

Remember: In C, Zero (0) is used to represent false, and one (1) is used to represent true

Note: If there is only one statement is present in the “if” or “else” body then you do not need to use the braces (parenthesis). Have a look at the below example.


The above program can also be written like this 👇👇:

#include <stdio.h>   
 int main(){    
 
 int number=0;    
 printf("enter a number:");    
 scanf("%d", &number);     
 
 if(number%2==0)    
   printf("%d is even number", number);     
 
 else    
   printf("%d is odd number", number);      
 
 return 0;  
}

Ladder if...else...if statement:

It is used in the scenario where there are multiple cases to be performed for different conditions. In if-else-if ladder statement, if a condition is true then the statements defined in the if block will be executed, otherwise if some other condition is true then the statements defined in the else-if block will be executed, at the last if none of the condition is true then the statements defined in the else block will be executed. There are multiple else-if blocks possible. It is similar to the switch case statement where the default is executed instead of else block if none of the cases is matched.

Syntax:

if(condition1){  
  //code to be executed if condition1 is true  
}else if(condition2){  
  //code to be executed if condition2 is true  
}  
else if(condition3){  
  //code to be executed if condition3 is true  
}  
...  
else{  
  //code to be executed if all the conditions are false  
}  

Example 2: Ladder if...else...if statement

#include <stdio.h>   
int main(){    
 int number=0;    
 printf("enter a number:");    
 scanf("%d", &number);     
  if(number==10){    
    printf("number is equals to 10");    
  }    
  else if(number==50){    
    printf("number is equal to 50");    
  }    
  else if(number==100){    
    printf("number is equal to 100");    
  }    
  else{    
    printf("number is not equal to 10, 50 or 100");    
  }    
  return 0;  
}    

Output

Enter a numbr:12
Number is not equal to 10, 50 or 100
Enter a number:50
Number is equal to 50









Friday, November 20, 2020

Control statements in C

Ahmad Irshad
Control statements | welcome2protec.com


What is control statements in C?

Control statements are used in C or other programming language to regulate the flow of program execution, i.e., whether or not a set of statements will be executed based on certain conditions or how many times a certain block of cedes is to be executed, again based on condition.

For Example:

/*Control statements in C*/
int x = 2;
int y = 3;

/*If condition is true, this code block will be executed*/
if((x + y) % 5 == 0){
 // Do whatever
}

/*if condition is false, this code block will be executed*/
else{
 //Do something else 
}
-------------------OR----------------------------
int i;
for(i = 0; i < 10; i++){
 /* Do anything that you want. This code block will be 
  * executed until i becomes > or = to 10 */
}

There are three type of control statements in C

Decision making statement:

It is used to decide whether a certain statement or block of statements will be executed or not i.e. If a certain condition is true then a block of statement is executed otherwise not.

Types of decision making statement:

  1. Simple if statement
  2. if...else & ladder if...else statement
  3. nested if...else statement
  4. Switch...case statement

Iterative statements:

Iterative statements create loops in the program. It is the process where a set of instructions or statements is executed repeatedly for a specified numbers of time or until a condition is satisfied.

Type of iteration statement in C:

  1. do...while loop
  2. While loop
  3. For loop
  4. Nested for loop

Jumping statement in C:

Jump statement are used to transfer control from one point to another point in the program. It allows to exit loop, start the next iteration of a loop and explicitly transfer program control to a specified location in you program.

Type of jumping statement:

  1. Break statement
  2. goto statement
  3. Continue statement













Wednesday, November 18, 2020

C Interview questions and answers-5

Ahmad Irshad
C Interview questions and answers | welcome2protec


What is control statements in C?

Control statements are used in C or other programming language to regulate the flow of program execution, i.e. whether or not a set of statements will be executed based on certain conditions or how many times a certain block of cedes is to be executed, again based on condition.

For Example:

/*Control statements in C*/
int x = 2;
int y = 3;

/*If condition is true, this code block will be executed*/
if((x + y) % 5 == 0){
 // Do whatever
}

/*if condition is false, this code block will be executed*/
else{
 //Do something else 
}
-------------------OR----------------------------
int i;
for(i = 0; i < 10; i++){
 /* Do anything that you want. This code block will be 
  * executed until i becomes > or = to 10 */
}

What is if---else statements in C?

The if---else statement in C is used to perform the operation based on some specific condition. The if statement is executed if the statement inside the condition evaluates to true, otherwise the statement inside the else block is executed.

/*Syntax of if---else statement.*/
if(Condition){
 // Block-1 statement
}

/*if condition is false, this code block will be executed*/
else{
 //Blcok-2 statement 
}

What is nested if...else in C?

Nested if...else: Having more than one if...else statement inside the body of another if...else statement is called nested if...else statement.

Syntax | More details.

if(condition) {
    //Nested if else inside the body of "if"
    if(condition2) {
       //Statements inside the body of nested "if"
    }
    else {
       //Statements inside the body of nested "else"
    }
}
   else {
    //Statements inside the body of "else"
   }


Waht is if...else...if ladder statement in C?

It is used in the scenario where there are multiple cases to be performed for different conditions. In if-else-if ladder statement, if a condition is true then the statements defined in the if block will be executed, otherwise if some other condition is true then the statements defined in the else-if block will be executed, at the last if none of the condition is true then the statements defined in the else block will be executed. There are multiple else-if blocks possible. It is similar to the switch case statement where the default is executed instead of else block if none of the cases is matched.

Syntax

if(condition1){  
//code to be executed if condition1 is true  
}else if(condition2){  
//code to be executed if condition2 is true  
}  
else if(condition3){  
//code to be executed if condition3 is true  
}  
...  
else{  
//code to be executed if all the conditions are false  
}  



To be updated soon...

--

--



Sunday, November 15, 2020

2D array in C

Ahmad Irshad
2D array in C | welcome2protec


2D array: simply can be defined as an array of arrays (In other words you can say collection of several one dimensional arrays is called 2D array).

/* Here, you can see four arrays inside one array. That's how 
 * you can say "an array of arrays" in known as 2D array. */
 
   int arr[4][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}};


1D array can be seen as data elements organized in a row. And 2D array is similar to 1D array but, it can be visualized as a grid (or table) with rows and columns as you can see below example.

/* Here, 2D array is organized in one row similar to 1D array */
  
   int arr[4][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}};
  
/* But, it can be visualized as a grid (or table)
   with rows and columns as you can see below. */
   
    col-1   col-2    col-3
     
    {1,         2,       3}     // Row-1
    {4,         5,       6}     // Row-2
    {7,         8,       9}     // Row-3
    {10,       11,      12}     // Row-4
  

In above, arr[4][3] first arr[4] represent number of rows, and 2nd arr[3] represent number of columns. Let's understand with a simple example at given below.

Note: 2D array is organized as matrices which can be represented as the collection of rows and columns as you can see above. However 2D arrays are used to create database in data structure.


Example 1: A simple example of 2D array

/* A simple example of 2D array */

#include <stdio.h>
#include <conio.h>

int main()
{
 /* 2D array declaration with initialization*/
 int arr[4][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}}; 
 int i, j;
 clrscr();

 /* Traversing 2D array by using nested for loop */
 printf("Elements of 2D array:\n");
 for(i=0; i<=3; i++)
 {  
    for(j=0; j<=2; j++)
    { 
      printf("%d    ",arr[i][j]);
	if(j==2)
	 printf("\n");
    }
  }
  getch();
 }    

Output

Elements of 2D array:
  
  1    2    3
  4    5    6
  7    8    9
  10  11   12 
  

How to take input data from user in 2D array? See below example2


Declaration of 2D array:

The basic syntax of declaring a 2D array is given below:

/* Syntax for declaring a 2D array */
  
  Data_Type Array_Name[Row_Size][Column_Size];
  
/* For Example: An int array of 12 elements (row * column i.e 4*3), 
 * where arr is the name of 2D array, [4] represent number of rows, 
 * and [3] represent number of columns */
 
  int arr[4][3]
  

Initialization of 2D array:

A 2D array can be initialized by three ways

// First method
  int arr[4][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};

Since the above array have 4 rows and 3 columns. Therefore, the elements will store in array in the order like 1st three elements will be stored in first row, next three elements in 2nd row, and similarly last three elements will be stored in 4th row.


This type of initialization use of nested braces. Each set of inner braces represent one row. since this declaration have total 4 rows so there are 4 sets of inner braces.

// second method
  int arr[4][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}};

A 2D array can also be declared as below. In this declaration you must always specify the second dimension even if you are specifying elements during declaration.

/* Third method */
  int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9};

As you can see the second declaration is better and more readable than the 1st and 3rd one. I recommend you to use the 2nd method as it is more readable and in this method you can visualize the rows and columns of 2D array.


Let’s see the below initialization of 2D array to understand it better:

Int arr[2][3] = {2,4,5,8,9,10}      /*Valid declaration*/
Int arr[ ][3] = {2,4,5,8,9,10}      /*Valid declaration*/

Int arr[ ][ ] = {2,4,5,8,9,10}      /*Invalid declaration*/
Int arr[2][ ] = {2,4,5,8,9,10}      /*Invalid declaration*/

Example 2: Taking inputs from user in 2D array

/* Program to take data as input form user */

#include <stdio.h> 
#include <conio.h>

int main()
{
 /* Declaration of 2D array*/
 int arr[3][4];
 /* Counter variables for the loop */
 int i, j;
 clrscr();

 /* Taking input from user */
 for(i=0; i<=2; i++)
 {
    for(j=0; j<=3; j++)
    {
       printf("Enter vlaue for arr[%d][%d]:");
       scanf("%d", &arr[i][j]);
    }
 }
 /* Displaying array elements */
 printf("Elements of 2D array:\n");
 for(i=0; i<=2; i++)
 {
    for(j=0; j<=3; j++)
    {
      printf("%d ", arr[i][j]);
      if(j==3)
      printf("\n");
    }
 }
  getch();
 }

Output

  Enter value for arr[0][0]: 1
  Enter value for arr[0][1]: 2
  Enter value for arr[0][2]: 3
  Enter value for arr[0][3]: 4
  
  Enter value for arr[1][0]: 5
  Enter value for arr[1][1]: 6
  Enter value for arr[1][2]: 7
  Enter value for arr[1][3]: 8
  
  Enter value for arr[2][0]: 9
  Enter value for arr[2][1]: 10
  Enter value for arr[2][2]: 11
  Enter value for arr[2][3]: 12
  
  Elements of 2D array:
  
  1    2    3    4
  5    6    7    8
  9   10   11   12
  

Memory representation of 2D array:

2D array can be visualized as a grid (or table) with rows and columns with x rows and y columns where row number ranges from 0 to (x-1) and columns number ranges from 0 to (y-1). For example: A 2d array arr[4][3] with 4 rows and 3 columns. As you can see at below diagram

Conceptual representation of 2D array | welcome2protec

Every elements in a 2D array is identified by an element name which is in the form of arr[i][j], where 'arr' is the name of an array, and 'i' represent the row index and 'j' represent the column index. that uniquely identify each element in a 2D array as you can see at above diagram.


However, the actual representation of this array in memory would be something like below diagram.

Actual memory representation of 2D array | welcome2protec

Since, this array is of integer type so each elements would use 4 bytes of memory that's the reason there is a difference of 4 in element's addresses.

Note: The address are generally in hexadecimal. In above diagram showing these addresses in integer just because to show you that the elements are stored in contiguous locations.













Saturday, November 14, 2020

Array in C | part-2

Ahmad Irshad
Array in C - part-2 | welcome2protec


Memory representation of an array:

All the array elements in C occupy sequential block of memory spaces and each memory block is of same size. For example, int num[6]; /* An integer array of 6 elements*/ it's length is 6, so this array will get 6 sequential memory block in the RAM and each memory block has a unique address in byte. 



There is a difference of 4 among the address of subsequent neighbors, since an integer type array holds 4 bytes of memory, therefor each block will occupy memory of 4 bytes. For example, address of 1st block is 1000, so 2nd block will be 1004, 3rd block 1008, 4rth block 10012, 5th block 1016, and last block will be 1020 as you can see in below diagram. 

Memory representation of array | welcome2protec
Memory representation of array

Array Indexing:

The location of an elements in an array is represented by numerical value which is called array index. In programming languages, the indexes always start with 0, meaning that the first elements has index 0, and second has index 1, third has index 2, similarly it continue through the natural numbers until the last index (N-1). Where N represents the length of an array. Let's have a look at the below example:

Array Indexing | welcome2protec.com

Note: The elements of an array share the same variable name but each element has its own unique index number (also known as a subscript) see the above diagram.


Accessing elements of an array:

you can use index number (subscript) to access any elements stored in array. Since we know that, The elements of an array share the same variable name but each element has its own unique index number (also known as a subscript) see array indexing. This is how you can access the array elements.

/* Array Declaration with initialization */
int num[] = {2, 4, 6, 8, 10, 12};

num[0] = 2;  // 1st element of array, since num[0] represent 1st index
num[3] = 8;  // 4th element of array, since num[3] represent 4th index

/* Last element of array, since num[5] represent 6th index i.e last index of array.*/
num[5] = 12;

Let's understand with below example


Example of Array: Program to find average of  4 numbers.

#include <stdio.h> 
int main()
{
    int avg = 0;
    int sum =0;
    int x=0;

    /* Array- declaration – length 4 */
    int num[4];

    /* We are using a for loop to traverse through the array
     * while storing the entered values in the array
     */
    for (x=0; x<4; x++)
    {
      printf("Enter number %d \n", (x+1));
      scanf("%d", &num[x]);
    }
    
    /* Displaying elements of array */
    for (x=0; x<4; x++)
    {
        sum = sum+num[x];
    }

    avg = sum/4;
    printf("Average of entered number is: %d", avg);
    return 0;
}

Output

Enter number 1 
10
Enter number 2 
10
Enter number 3 
20
Enter number 4 
40
Average of entered number is: 20

How to store elements in array?

Here, we are traversing the array from 0 to 9 since length of array is 10. Inside the loop we are taking input form user of any 10 numbers. All the input numbers will be stored in corresponding array using scnaf() function. Look at the below statements taken from the above example.

/* We are using a for loop to traverse through the array
 * while storing the entered values in the array */
for (x=0; x<4; x++)
{
  printf("Enter number %d \n", (x+1));
  scanf("%d", &num[x]);
}

How to display elements from an array?

Again you need to run a for loop to display the stored elements of an array. Look at the below statements taken from the above example.

/* Displaying elements of array */
for (x=0; x<4; x++)
{
  sum = sum + num[x];
}

How to calculate the size of an array?

You can calculate the size of an array in bytes by using sizeof operator.

Example: Size of array in bytes using sizeof() operator

/* Calculating size of an int array using sizeof operator */
#include <stdio.h> 
int main()
{
  int arr[6] = {2, 4, 6, 8, 10, 12};
  printf("size of arr = %d bytes", sizeof(arr));
  return 0;
}
  

Output

Size of arr = 24 bytes

How to calculate the length of an array?

There are various technique to find length of array in C, by using sizeof() operator and without using sizeof() operator. Let's see the both technique.

Length of array = sizeof (arr) / sizeof (arr[0])

Example 1: Length of an array using sizeof operator

/* Calculating the length of int array using sizeof operator */
  #include <stdio.h>
  int main()
  {
    int arr[6] = {2, 4, 6, 8, 10, 12};
    printf("Length of arr = %d", sizeof(arr) / sizeof(arr[0]));
return 0; }

Output

Length of arr = 6 

Example 2: Length of an array without sizeof() operator

/* Calculating the length of int array without sizeof() operator */
  #include <stdio.h>
  int main()
  {
    int arr[6] = {2, 4, 6, 8, 10, 12};
    int i = 0;
    while(arr[i] !=12)
    {
      i++;
    }
    printf("Length of arr = %d",i+1);
    return 0;
  }
  

Output

Length of arr = 6 









Friday, November 13, 2020

Array in C | Part-1

Ahmad Irshad
Array in C | welcome2protec


Array is a collection of elements of similar data type stored at contiguous memory location. An array can be of any type for example: int, char, float, double etc. like int array holds the elements of int types while the float array holds the elements of float types.



OR simply you can say, Array is a group of variables of same data type stored at contiguous memory location.

It also has the capability to store the collection of derived data type such as pointers, structure etc. Elements can be accessed randomly using indexes of an array (index is also known as subscript).

Array in C | welcome2protec.com

Note: Each values stored in array is called an elements of the array. The elements of the array share the same variable name but each elements has its own unique index number. As you can see in above diagram.


Why do we use an array?

Consider a scenario where you need to find out the average of 100 integer numbers entered by user. In C, you have two ways to do this: first: you need to define 100 variables with int data type and then perform 100 scanf() operations to store the entered values in the variables and then at last calculate the average of them. Second: you need to declare a single integer array to store the values, loop the array to store all the entered values in array and later calculate the average.

which solution is better according to you?

Obviously the second one is better, it is convenient to store same data types in one single variable and later access them using array index. i will discuss about array index later.


Declaration of Array:

In order to declare an array you need to specify as follow:

  • The data type of an array elements. It could be int, char, float, double etc.
  • The name of an array.
  • A fixed number of elements that array may contain. The number of elements is placed inside the square brackets followed by the array name.

Syntax

DataType ArrayName [ArraySize];

For Example: Array declaration by specifying size

/*Array declaration by specifying it's size*/
float marks[5]; 
int num[6];

/* An array can also be declared by user specified size */
int x = 6;
int num[x];

There are many ways to declare an array see at below declaration with initialization

Similarly an array can be of any data type such as int, char, float, double etc.

In above declaration, marks is a name of an array of float type, and five in the square bracket [5] represent the length of the array. Similarly in the 2nd declaration, num is a name of an array of int type, and six inside the square bracket [6] represent the length of an array. 


Declaration with initialization:

Array initialization is the process of assigning elements to an array. The initialization can be done in a single statement or one by one.

1) Arrays may be initialized when they are declared, just as any other variables. Place the initialization data in curly {} braces followed by the equal (=) sign. Let's see the below example.

/* An array can be initialized when they are declared, 
 *just as any other variables. */
int num[6] = {2, 4, 6, 8, 10, 12};

For Example: Declaration of array

Declaration of array | welcome2protec

In above, int num[6]; is a declaration statements of an array, and number inside the curly braces {2, 4, 6, 8, 10, 12}; are initialized values, these values will store in array at contiguous memory location. As you can see in above diagram.

Note: The first element in an array is stored at index [0], while the last element is stored at index [n-1], where n is the total number of elements in the array.


2) An array can also be initialized by providing fewer data elements than the size of the array. And the remaining array will be automatically initialized to zero. Have a look at the below example.

/* An array can also be initialized by providing fewer data elements than 
 * it's size. And the remaining array will be initialized 
 * to zero. Have a look at below example. */
int num[6] = {2, 4, 6};

See the above diagram to understand it better.


3) If an array is to be completely initialized, then the dimension of the array is not required. The compiler will automatically size the array to fit the initialized data.

For Example: If the number of initialized values are nine {2, 4, 6, 8, 10, 12, 14, 16, 18}; then the compiler will fits it's size to 9 automatically, and if the number of initialized values are six then fits it's size to 6See the above diagram to understand it better.

/* Dimension is not required, If an array is to be completely initialized.*/
int num[] = {2, 4, 6, 8, 10, 12, 14};

Note: You can initialized any number of elements when the array size is not specified.


4) Array can be initialized individually too.

/* Declaration of an array */
int num[3];

/* Individually initialization */
num[0] = 10;
num[1] = 20;
num[2] = 30;   

5) An array cannot be initialized with more elements than it's size. If you do like this you get a compilation error "too many initialization"See the above diagram to understand it better.

/* An array cannot be initialized with more elements than it's size. 
 * If you do, you get a compilation error "too many initialization".*/
int num[5] = {2, 4, 6, 8, 10, 12, 14};

What if, an array is not initialized?

If array is declared in a function, then the values is undefined(garbage value). If the array is declared as a global one or as static in a function, then all elements are initialized to zero if they are not initialized already.


Advantage of array:

  • Array elements can be access randomly using array index
  • Use less line of codes it creates a singal array of multiple elements.
  • Easy access to all elements.
  • Traversal through the becomes easy using a singal loop.
  • Sorting becomes easy as it can be accomplished by writing less line of code.

Disadvantage of array:

  • An array in C is not dynamic, as it allows fixed number of elements to be entered which is decided at the time of declaration.
  • Insertion and deletion of elements can be costly since elements are needed to be managed in accordance with the new memory allocation.









Wednesday, November 11, 2020

Library Function in C

Ahmad Irshad
Library function | welcome2protec

Library function in C language are built-in function which are grouped together and placed in a common place called library function. Each library function in C performs specific operation. In order to use these library functions you need to import appropriate header files at the beginning of a program. Library function is also known as predefined function.

Note: All the library functions are declared in header files and its definition is stored in library file. Therefore, In order to use these library functions you need to include appropriate header files before writing the any program.



For Example:

If you want to use printf() and scanf() functions, the header file #include <stdio.h>  should be include in our program.

 #include <stdio.h> 
 int main()
 {
     int a,b;
     printf("Enter two numbers:");
     scanf("%d,%d", &a, &b);
     prinf("You have entered numbers %d and %d", a, b);
 }
 

Output

 Enter two numbers: 10 20
 You have entered numbers 10 and 20
    

Note: If you try to use printf() and scanf() functions without including the header file #include <stdio.h> you will get an error.


Advantage of using C library functions:

  • Simple and easy to use: These functions has gone through multiple rigorous testing and are easy to work.
  • The functions are optimized for performance: Since these functions are standard library functions, a dedicated group of developers constantly work on it and make them better. In the process, the are able to create the most efficient code optimized for maximum performance.
  • It saves considerable development time: Since the general functions like printing to a screen, calculating the square root, and many more are already written. You shouldn't worry about creating them. whenever you need these function you can call and use them in your program.
  • The functions are portable: Whenever changing real-world needs, your application is expected to work every time, everywhere. And, these library function help you in that they do the same thing on every computer.

Example: Square root using sqrt() function

Suppose, you want to find the square root of a number, so you can use the sqrt() library function to compute the square root of a number. To use this function you need to include <math.h> header file at the beginning of a program. Since sqrt() function is declared in #include <math.h>  header file.

 
 #include <stdio.h> //declaration of printf() and scanf() 
 #include <conio.h> //declaration of getch()
 #include <math.h>  //declaration of sqrt()
 void main()
 {
     float num, root;
     clrscr();
     printf("Enter a umber: ");
     scanf("%f", &num);
   
     /* Calculate the square root  of given number and stores in root */
     root = sqrt(num);    
     printf("square root of %.2f = %.2f", num, root);
     getch();
 }
  

Output

 Enter a number: 12
 square root of 12.00 = 3.46
  

Note: As you can see, clrscr(), printf(), scanf(), sqrt(), and getch() these all are the example of library functions which are used in the program by calling it directly.


Library Functions in Different Header Files:

A header file is a file with extension .h which contains C function declarations and macro definitions to be shared between several source files. You need to include appropriate header file at the beginning of a program to supply the declarations you need to invoke

List of header file in C language.

Header file Description
<assert.h> Program assertion functions
<conio.h> console Input/output functions
<ctype.h> Character type functions
<locale.h> Localization functions
<math.h> Mathematics functions
<setjmp.h> Jump functions
<signal.h> Signal handling functions
<stdarg.h> Variable arguments handling functions
<stdio.h> Standard Input/output functions
<stdlib.h> Standard Utility functions
<string.h> String handling functions
<time.h> Date time functions










Protec Computer Academy (An ISO 9001:2015 Certified Institute, Powered by E-Max Education, Branch Code EMAX/EK-80503, Registered by government of India.) is a best IT training center in Siwan with 100% Job placement assistance. Where you can learn Programming, WebDesigning, Hardware|Networking, Blogging, WordPress, Digitial marketing, English Speaking, And many more...| All certificates are valid in Government Jobs as well as in Private Companies. *** At Tara Market, Beside Vishal Mega Mart - Siwan*** +966532621401, Email- ahmad.irshad781@gmail.com *** Follow us on | | @welcome2protec
Protec Protec Protec Protec Protec Protec Protec Protec Protec Protec Protec Protec Protec Protec Protec Protec
Contact Us