C local block

What is a local block?

  1. Statements which are enclosed in left brace ({) and the right brace (}) forms a local Block.
  2. Local Block can have any number of statements.
  3. Branching Statements or Conditional Statements, Loop Control Statements such as if,else,switch,for,while forms a local block.
  4. These Statements contain braces , so the portion of code between two braces would be considered a local block.
  5. Variables declared in a local block have local scope i.e they can be accessed within the block only.

Live Program : Local Scope :

#include<stdio.h>
int x = 40 ;         // Scope(Life) : Whole Program
int main()
{
int x = 10 ;         // Scope(Life) : In main
   {
   x = 30 ;
   printf("%d",x);
   }
printf("%d",x);
}

Output :

30 10

Explanation of Local Block :

  1. In the above example , we can see that variable ‘x’ is declared inside main function and also inside inner block.
  2. Inside inner block , local copy of variable ‘x’ is given higher priority than the outer copy of ‘x’.

Different Forms of Local Block :

Form 1 : Local Block Inside Control Statement

main()
{
if (var > 5)
    {
    printf("Inner Bock : If Statement");
    }
}

Form 2 : Local Block Inside Switch Case

switch(input) 
{
    case 1:            
         printf("Playing the game\n");
         break;
    case 2:          
        printf("Loading the game\n");
        break;
    case 3:         
        printf("Playing multiplayer\n");
        break;
    case 4:        
        printf( "Thanks for playing!\n" );
        break;
    default:            
        printf( "Bad input!\n" );
        break;
}

Similarly we can have local blocks in For Loop,While Loop and do-While Loop.

C Padding Zero using Printf

Padding Zero Using Format Specifier :

We can use printf statement for formatting Number as per our requirements. Some times we need to pad zeroes before the actual number in order to fill complete width. Format Specifier used in C Programming is efficient way to pad zero. Let’s look , how to pad zero using format specifier -

  1. To zero-pad a number, insert a number, preceded by a zero, after the % in the format specifier.
  2. If you fail to include the zero prefix on the number, it will be padded with spaces and not zeros.

Five-character integer, Padded with Zeros

printf("%05d",i);

Floating point, Padded with zero to left

printf("%07f",f);

Live Example : Padding Zero

#include<stdio.h>
int main()
{
   int i = 123;
   printf("%d\n",i);
   printf("%05d\n", i );
   printf("%07d\n", i );
   return( 0 );
}

Output :

123
00123
0000123

Live Example 2 :

#include <stdio.h>
int main(void) 
{
   float value = 1.0F;
   printf("value = %07.3f\n", value);
   return 0;
}

Output :

value = 001.000

pow() Function : C Reference

Calculating x^n Using Pow function :

#include<stdio.h>
#include<math.h>
int main()
{
    int num,power,result;
    printf("\nEnter the numaber and its Power : ");
    scanf("%d%d",&num,&power);
    result = pow(num,power);
    printf("\nResult : %d",result);
    return(0);
}

Output :

Enter the numaber and its Power : 6 2
Result : 36

Explanation of the Code :

  1. In a C Programming Language we can find the expression of type “x raise to y”.
  2. Power function is used to find the square , cube of number or number raise to any index.
  3. math.h header file contain the power function.

Syntax of the Pow Function :

pow(num1,num2);

represents num1 raise to num2.

Different Ways of Using Power Function :

Way 1 : Used to Find Cube

result = pow(num,3);

Way 2 : Used to Find Square

result = pow(num,2);

fcloseall() Function : C Reference

Closing all the Open Streams in C Programming :

Sometimes we open multiple files for processing then it is tedious task to close all the open streams one by one after usage. C provides powerful feature to close all the open streams using single method.

fcloseall() : Does not closed following Streams

1stdinStandard Input Stream
2stdoutStandard Output Stream
3stdprnStandard Printer Stream
4stderrStandard Error Stream
4stdaux

Declaration :

int fcloseall(void);

Remark : Explanation

Remark PointExplanation
Return Value on SuccessNo of Streams Closed by Function
Return Value on FailureEOF
UsageClosing all the open streams

Program : Live Example

#include<stdio.h>
{ 
int streams_closed;
fopen("ONE.txt","w");
fopen("TWO.txt","w");
streams_closed = fcloseall();
if (streams_closed == EOF)
    printf("Error");
else 
    printf("%d Streams Were Closed", streams_closed);
return 0;
}

Output :

2 Streams Were Closed

Explanation :

We have opened two files in write mode so that we have two streams open.

fopen("ONE.txt","w");
fopen("TWO.txt","w");

Now we are closing all the streams using single statement.Function will return no of streams closed by function

streams_closed = fcloseall();

Return value is compared with the EOF, If return value is not EOF then we can say that function has successfully closed open streams

if (streams_closed == EOF)
    printf("Error");
else
    printf("%d Streams Were Closed", streams_closed);

clearerr() Function : C Reference

Declaration :

void clearerr(FILE *stream);
  • Resets error indication
  • clearerr resets the named stream’s error and end-of-file indicators to 0.
  • Once the error indicator is set, stream operations continue to return error status until a call is made to clearerr or rewind.
  • The end-of-file indicator is reset with each input operation.
  • Return Value : None

Live Example :

#include<stdio.h>
int main(void)
{
   FILE *fp;
   char ch;
   fp = fopen("temp.txt", "w");
   ch = fgetc(fp);
   printf("%c",ch);
   if (ferror(fp))
   {
   printf("Error reading from temp.txt");
   clearerr(fp);
   }
   fclose(fp);
   return 0;
}

Explanation of Program :

fp = fopen("temp.txt", "w");
ch = fgetc(fp);
printf("%c",ch);

Intentionally we are reading from file which is opened in writing mode. If error is detected by following statement then it will reset the error code and will flush the error.

if (ferror(fp))
{
}
two_dimensional_arrays in c Programming

C Multidimensional Array

Multidimensional array

  1. Array having more than one subscript variable is called multidimensional array.
  2. Multidimensional array is also called as matrix.

Consider the Two dimensional array -

  1. Two Dimensional Array requires Two Subscript Variables
  2. Two Dimensional Array stores the values in the form of matrix.
  3. One Subscript Variable denotes the “Row” of a matrix.
  4. Another Subscript Variable denotes the “Column” of a matrix.

two_dimensional_arrays in c Programming

Declaration and Use of Two Dimensional Array :

int a[3][4];

Use :

for(i=0;i<row,i++)
   for(j=0;j<col,j++)
   {
   printf("%d",a[i][j]);
}

Meaning of Two Dimensional Array :

  1. Matrix is having 3 rows ( i takes value from 0 to 2 )
  2. Matrix is having 4 Columns ( j takes value from 0 to 3 )
  3. Above Matrix 3×4 matrix will have 12 blocks having 3 rows & 4 columns.
  4. Name of 2-D array is ‘a‘ and each block is identified by the row & column number.
  5. Row number and Column Number Starts from 0.
Cell LocationMeaning
a[0][0]0th Row and 0th Column
a[0][1]0th Row and 1st Column
a[0][2]0th Row and 2nd Column
a[0][3]0th Row and 3rd Column
a[1][0]1st Row and 0th Column
a[1][1]1st Row and 1st Column
a[1][2]1st Row and 2nd Column
a[1][3]1st Row and 3rd Column
a[2][0]2nd Row and 0th Column
a[2][1]2nd Row and 1st Column
a[2][2]2nd Row and 2nd Column
a[2][3]2nd Row and 3rd Column

Two-Dimensional Array : Summary with Sample Example

Summary PointExplanation
No of Subscript Variables Required2
Declarationa[3][4]
No of Rows3
No of Columns4
No of Cells12
No of for loops required to iterate2

Memory Representation

  1. 2-D arrays are Stored in contiguous memory location row wise.
  2. 3 X 3 Array is shown below in the first Diagram.
  3. Consider 3×3 Array is stored in Contiguous memory location which starts from 4000 .
  4. Array element a[0][0] will be stored at address 4000 again a[0][1] will be stored to next memory location i.e Elements stored row-wise
  5. After Elements of First Row are stored in appropriate memory location , elements of next row get their corresponding mem. locations.

Multi Dimensional Array in C Programming

  1. This is integer array so each element requires 2 bytes of memory.

Basic Memory Address Calculation :

a[0][1] = a[0][0] + Size of Data Type

ElementMemory Location
a[0][0]4000
a[0][1]4002
a[0][2]4004
a[1][0]4006
a[1][1]4008
a[1][2]4010
a[2][0]4012
a[2][1]4014
a[2][2]4016

Memory Address Location in Multi Dimensional Array in C Programming

C Initializing 1-D Array

Different Methods of Initializing 1-D Array

Whenever we declare an array, we initialize that array directly at compile time.

Initializing 1-D Array is called as compiler time initialization if and only if we assign certain set of values to array element before executing program. i.e at compilation time.

Initializing 1-D Array

Here we are learning the different ways of compile time initialization of an array.

Ways Of Array Initializing 1-D Array :

  1. Size is Specified Directly
  2. Size is Specified Indirectly

A. Method 1 : Array Size Specified Directly

In this method , we try to specify the Array Size directly.

int num[5] = {2,8,7,6,0};

In the above example we have specified the size of array as 5 directly in the initialization statement.Compiler will assign the set of values to particular element of the array.

num[0] = 2
num[1] = 8
num[2] = 7
num[3] = 6
num[4] = 0

As at the time of compilation all the elements are at Specified Position So This Initialization Scheme is Called as “Compile Time Initialization“.

Graphical Representation :

C Programming Array 1-D

B. Method 2 : Size Specified Indirectly

In this scheme of compile time Initialization, We does not provide size to an array but instead we provide set of values to the array.

int num[] = {2,8,7,6,0};

Explanation :

  1. Compiler Counts the Number Of Elements Written Inside Pair of Braces and Determines the Size of An Array.
  2. After counting the number of elements inside the braces, The size of array is considered as 5 during complete execution.
  3. This type of Initialization Scheme is also Called as “Compile Time Initialization

Sample Program

#include <stdio.h>
int main()
{
int num[] = {2,8,7,6,0};
int i;
for(i=0;i<5;i++) {
    printf("\nArray Element num[%d] : %d",i+1,num[i]);
}
return 0;
}

Output :

Array Element num[1] : 2
Array Element num[2] : 8
Array Element num[3] : 7
Array Element num[4] : 6
Array Element num[5] : 0

C Array Declaration

In this tutorial we will be learning the C Array Declaration. A programmer need to specify the type of the elements and the number of elements required by an array.

C Array Declaration

Array has to be declared before using it in C Program. Array is nothing but the collection of elements of similar data types.

Syntax

<data_type>  array_name  [size1][size2].....[sizen];
Syntax ParameterSignificance
data_typeData Type of Each Element of the array
Array_nameValid variable name
sizeDimensions of the Array

Array declaration requirement

RequirementExplanation
Data TypeData Type specifies the type of the array. We can compute the size required for storing the single cell of array.
Valid IdentifierValid identifier is any valid variable or name given to the array. Using this identifier name array can be accessed.
Size of ArrayIt is maximum size that array can have.

What does C Array Declaration tells to Compiler ?

  1. Type of the Array
  2. Name of the Array
  3. Number of Dimension
  4. Number of Elements in Each Dimension

Examples of C Array Declaration

Examples : Declaring 1D array

// Array of 10 integer roll numbers  
int roll[10]

In the above example we are declaring the integer array of size 10. Array is single dimensional and have

Examples : Declaring 2D array

// 2-D Array
char name[80][20];

In the above example we are declaring 2D array which has 2 dimensions. First dimension will refer the row and 2nd dimension will refer the column.

Examples : Declaring 3D array

// 3-D Array
char name[80][20][40];

Above declaration tells compiler following things -

ExampleTypeArray NameDimension No.No.of Elements in Each Dimension
1integerroll110
2charactername280 and 20
3charactername380 and 20 and 40
Different Types of the array in C Programming language

C Array Types

In this tutorial we will be learning C Array Types. In C Programming , We have learnt about Array and its advantages , disadvantages and different applications of an array. In this chapter we will study about different types of an array. Array Types are represented using following Tree chart.

C Array Types

Different Types of the array in C Programming language

1.Single Dimensional Array :

  1. Single or One Dimensional array is used to represent and store data in a linear form.
  2. Array having only one subscript variable is called One-Dimensional array
  3. It is also called as Single Dimensional Array or Linear Array

Syntax :

<data-type> <array_name> [size];

Example of Single Dimensional Array :

int iarr[3]   = {2, 3, 4};
char carr[20] = "c4learn" ;
float farr[3] = {12.5,13.5,14.5} ;

2. Multi Dimensional Array :

  1. Array having more than one subscript variable is called Multi-Dimensional array.
  2. Multi Dimensional Array is also called as Matrix.

Syntax :

<data-type> <array_name> [row_subscript][column-subscript];

Example : Two Dimensional Array

int a[3][3] = { 1,2,3
                5,6,7
                8,9,0 };

C Programming Function Calling Types

C Programming - Types of Function Calling

There are different types of function calling. Depending on the number of parameters it can accept , function can be classified into following 4 types -

Function TypeParameterReturn Value
Type 1Accepting ParameterReturning Value
Type 2Accepting ParameterNot Returning Value
Type 3Not Accepting ParameterReturning Value
Type 4Not Accepting ParameterNot Returning Value

Let us Consider all types of functions one by one -

Type 1 : Accepting Parameter and Returning Value

Above type of method is written like this -

int add(int i, int j)
{
  return i + j;
}

and Called like this -

int answer = sum(2,3);

We need to assign the function call to any of the variable since we need to capture returned value.

Type 2 : Accepting Parameter and Not Returning Value

Above type of method is written like this -

void add(int i, int j)
{
  printf("%d",i+j);
}

above method can be called using following syntax -

sum(2,3);

Type 3 : Not Accepting Parameter but Returning Value

Above type of method is written like this -

int add()
{
  int i, int j;
  i = 10;
  j = 20;
  return i + j;
}

called using following syntax -

result = add();

Type 4 : Not Accepting Parameter and Not Returning Value

Above type of method is written like this -

void add()
{
  int i, int j;
  i = 10;
  j = 20;
  printf("Result : %d",i+j);;
}

and called like this -

add();

Tutorials based on Types of function -

  1. No argument and no return value
  2. C Function Arguments & No Return Value
  3. C Function Arguments & Return Value