Java Programming – Shishir Kant Singh https://shishirkant.com Jada Sir जाड़ा सर :) Sun, 03 Sep 2023 04:10:37 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://shishirkant.com/wp-content/uploads/2020/05/cropped-shishir-32x32.jpg Java Programming – Shishir Kant Singh https://shishirkant.com 32 32 187312365 Nested While Loop in C https://shishirkant.com/nested-while-loop-in-c/?utm_source=rss&utm_medium=rss&utm_campaign=nested-while-loop-in-c Sun, 03 Sep 2023 04:10:33 +0000 https://shishirkant.com/?p=4077 Nested While Loop in C Programming Language:

Writing while loop inside another while loop is called nested while loop or you can say defining one while loop inside another while loop is called nested while loop. That is why nested loops are also called “loops inside the loop”. There can be any number of loops inside one another with any of the three combinations depending on the complexity of the given problem.

In implementation when we need to repeat the loop body itself n number of times then we need to go for nested loops. Nested loops can be designed for up to 255 blocks.

Nested While Loop Syntax in C Language:

Following is the syntax to use the nested while loop in C language.

Nested While Loop in C Programming Language

Note: In the nested while loop, the number of iterations will be equal to the number of iterations in the outer loop multiplied by the number of iterations in the inner loop which is almost the same as the nested for loop. Nested while loops are mostly used for making various pattern programs in C like number patterns or shape patterns.

Execution Flow of Nested While Loop in C Language:

The outer while loop executes based on the outer condition and the inner while loop executes based on the inner condition. Now let us understand how the nested while loop executes. First, it will check the outer loop condition and if the outer loop condition fails, then it will terminate the loop.

Suppose if the outer loop condition is true, then it will come inside, first, it will print the outer loop statements which are there before the inner loop. Then it will check the inner loop condition. If the inner while condition is true, then the control move inside and executes the inner while loop statements. After execution of inner while loop statements, again, it will check the inner while loop condition because it is a loop and as long as the condition is true, it will repeat this process. Once the inner while loop condition fails, then the control moves outside and executes the statements which are present after the inner while loop. Once it executes then, again it will go and check the outer while loop condition. And if it is true, then it will again execute the same process.

So, when the loop will terminate means when the outer while loop condition becomes false.

Flow Chart of Nested While Loop:

Please have a look at the following diagram, which represents the flow chart of the nested while loop.

Flow Chart of nested While Loop

The flow will start and first, it will check the outer while loop condition. And if the outer while loop condition failed, then it will come to end. Suppose, the outer loop condition is true, then it will first execute the outer while loop statements if any. After execution of Outer while loop statements, it will check the inner while loop condition. For the inner while loop condition, it will also check for true and false. Suppose, the inner while loop condition is true, then inner while loop statements are executed. After executing the inner while loop statements, again, it will check the inner while loop condition, and this inner loop execution process will repeat as long as the inner while loop condition is true. If the inner while loop condition is false, then the remaining outer loop statements are executed. Once, the outer loop statements are executed, then again, it will come and check the outer while condition. This is the flow of the nested while loop.

Example: WAP to print the following format.
Nested While Loop in C Programming Language with Examples
Program:
#include <stdio.h>
int main ()
{
    int i, n, in;
    printf ("ENTER A NUMBER ");
    scanf ("%d", &n);
    i = 1;
    while (i <= n)
    {
        printf ("\n");
        in = 1;
        while (in <= i)
       {
            printf ("%d ", in);
            in = in + 1;
       }
       i = i + 1;
   }
   return 0;
}

Example: WAP to print the following format:
Nested While Loop in C Language with Examples
Program:
#include <stdio.h>
int main()
{
    int i, n, dn;
    printf("ENTER A NUMBER ");
    scanf("%d", &n);
    i = n;
    while(i >= 1)
    {
        printf("\n");
        dn = i;
        while(dn >= 1)
       {
            printf("%d ", dn);
            dn = dn - 1;
       }
       i = i - 1;
    }
    return 0;
}

Example: WAP to print the following format:
Nested While Loop in C Programming Language
Program:
#include <stdio.h>
int main ()
{
    int a = 1, b = 1;
    while (a <= 5)
    {
        b = 1;
        while (b <= 5)
       {
             printf ("%d ", b);
             b++;
       }
       printf ("\n");
       a++;
    }
    return 0;
}

In the next article, I am going to discuss Do While Loop in C Language with Examples. Here, in this article, I try to explain the Nested While Loop in C Programming Langauge with Examples. I hope you enjoy this Nested While Loop in C Programming Langauge with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

]]>
4077
While Loop in C https://shishirkant.com/while-loop-in-c/?utm_source=rss&utm_medium=rss&utm_campaign=while-loop-in-c Sun, 03 Sep 2023 04:03:31 +0000 https://shishirkant.com/?p=4075 What is looping?

The process of repeatedly executing a statement or group of statements until the condition is satisfied is called looping. In this case, when the condition becomes false the execution of the loops terminates. The way it repeats the execution of the statements will form a circle that’s why iteration statements are called loops.

Why do we need looping?

The basic purpose of the loop is code repetition. In implementation whenever the repetitions are required, then in place of writing the statements, again and again, we need to go for looping.

Iteration or looping Statements:

Iteration statements create loops in the program. It repeats the same code fragment several times until a specified condition is satisfied is called iteration. Iteration statements execute the same set of instructions until a termination condition is met. C provides the following loop for iteration statements:

  1. while loop
  2. for loop
  3. do-while loop
What is While Loop in C Language:

A loop is nothing but executes a block of instructions repeatedly as long as the condition is true. How many times it will repeat means as long as the given condition is true. When the condition fails, it will terminate the loop execution.

A while loop is used for executing a statement repeatedly until a given condition returns false. Here, statements may be a single statement or a block of statements. The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true. If you see the syntax and flow chart parallelly, then you will get more clarity of the while loop.

While Loop Syntax in C Language:

Following is the syntax to use the while loop in C Programming Language.

What is While Loop in C Language

While we are working with a while loop first we need to check the condition, if the condition is true then the control will pass within the body if it is false the control pass outside the body.

When we are working with an iteration statement after execution of the body control will be passed back to the condition, and until the condition become false. If the condition is not false then we will get an infinite loop.

It is something similar to the if condition, just condition, and statements, but the flow is different from the if condition. How it is different lets us understand through the flow-chart.

Flow Chart of While Loop in C Language:

The following diagram shows the flow chart of the while loop.

Flow Chart of While Loop in C Language

The flow chart will start. The start is represented by the oval symbol. Then it will check the condition. As discussed earlier, every condition is having two outputs i.e. true and false. If it is true what will happen and it is false what will happen, we need to check.

Suppose, the condition is true, then what all statements defined inside the block (within the while loop block) will execute. After execution of statements, will it end? NO, it will not end. After execution of statements, once again it will go and check the condition. It will repeat the same process as long as the given condition is true. Suppose, the condition is false, then it will come to end. This is the execution flow of a while loop.

Program to understand While loop in C Language:
#include<stdio.h>
int main()
{
    int a=1;
    while(a<=4)
    {
        printf("%d", a);
        a++;
    }
    return 0;
}

Output: 1234

The variable a is initialized with value 1 and then it has been tested for the condition. If the condition returns true then the statements inside the body of the while loop are executed else control comes out of the loop. The value of a is incremented using the ++ operator then it has been tested again for the loop condition.

Example to Print no 1 to 5 using a while loop in C Language
#include <stdio.h>
int main()
{
    int i = 1;
    while(i <= 5)
    {
         printf("%d ", i);
         i = i + 1;
    }
    return 0;
}

Output: 1 2 3 4 5

Example: Print the nos 10, 9, 8…. 1 using while loop
#include <stdio.h>
int main()
{
    int i;
    i = 10;
    while(i >= 1)
    {
        printf("%d ", i);
        i = i - 1;
    }
    return 0;
}

Output: 10 9 8 7 6 5 4 3 2 1

Example: Print the numbers in the following format up to a given number and that number is entered from the keyboard.

2 4 6 8 …………………….. up to that given number

#include <stdio.h>
int main()
{
    int i, n;
    printf("Enter a Number : ");
    scanf("%d", &n);
    i = 2;
    while(i <= n)
    {
        printf("%d ", i);
        i = i + 2;
    }
    return 0;
}

Output:
While Loop in C Programming Language

Program to Enter a number and print the Fibonacci series up to that number using a while loop in C Language.
#include <stdio.h>
int main ()
{
    int i, n, j, k;
    printf ("Enter a Number : ");
    scanf ("%d", &n);
    i = 0;
    j = 1;
    printf ("%d %d ", i, j);
    k = i + j;
    while (k <= n)
    {
        printf (" %d", k);
        i = j;
        j = k;
        k = i + j;
    }
    return 0;
}

Output:
While Loop in C Language

Example: Enter a number from the keyboard and then calculate the no of digits and sum of digits of that number using a while loop.

#include <stdio.h>
int main()
{
    int no, nd, sd, rem;
    printf("Enter a Number : ");
    scanf("%d", &no);
    nd = 0;
    sd = 0;
    while (no > 0)
    { 
        rem = no % 10;
        nd = nd + 1;
        sd = sd + rem;
        no = no / 10;
    }
    printf("The number of digit is %d", nd);
    printf("\nThe sum of digit is %d", sd);
    return 0;
}

Output:
While Loop in C Language with Examples
What is the pre-checking process or entry controlled loop?

The pre-checking process means before the evaluation of the statement block conditional part will be executed. When we are working with a while loop always pre-checking process will occur. The loop in which before executing the body of the loop if the condition is tested first then it is called an entry controlled loop.

While loop is an example of entry controlled loop because in the while loop before executing the body first condition is evaluated if the condition is true then the body will be executed otherwise the body will be skipped.

]]>
4075
Switch Statements in C https://shishirkant.com/switch-statements-in-c/?utm_source=rss&utm_medium=rss&utm_campaign=switch-statements-in-c Sat, 02 Sep 2023 17:36:39 +0000 https://shishirkant.com/?p=4071 Switch Statements in C Language:

The switch is a keyword, by using the switch keyword we can create selection statements with multiple blocks. Multiple blocks can be constructed by using a “case” keyword.

Switch case statements are a substitute for long if statements that compare a variable to several integral values. The switch statement is a multi-way branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. The switch is a control statement that allows a value to change control of execution.

Rules for Switch statements in C Language:
  1. The expression provided in the switch should result in a constant value otherwise it would not be valid.
  2. Duplicate case values are not allowed.
  3. The default statement is optional. Even if the switch case statement does not have a default statement,
    it would run without any problem.
  4. The break statement is used inside the switch to terminate a statement sequence. When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
  5. The break statement is optional. If omitted, execution will continue on into the next case. The flow of control will fall through to subsequent cases until a break is reached.
  6. Nesting of switch statements is allowed, which means you can have switch statements inside another switch. However nested switch statements should be avoided as it makes the program more complex and less readable.

Switch Statements in C Language with Examples

Syntax of Switch Statements in C Language:

Syntax of Switch Statements in C Language

After the end of each block it is necessary to insert a break statement because if the programmers do not use the break statement, all consecutive blocks of codes will get executed from every case onwards after matching the case block.

When do we need to go for a switch statement?

When there are several options and we have to choose only one option from the available options depending on a single condition then we need to go for a switch statement. Depending on the selected option a particular task can be performed.

Example to understand Switch Statement in C Language:
#include <stdio.h>
int main()
{
   int x = 2;
   switch (x)
   {
      case 1: printf("Choice is 1");
      break;
      case 2: printf("Choice is 2");
      break;
      case 3: printf("Choice is 3");
      break;
      default: printf("Choice other than 1, 2 and 3");
      break;
   }
   return 0;
}

Output: Choice is 2

What is the difference between nested if-else and switch statements in C Language?

By using nested if-else also we can also create multiple blocks whenever required, but for creating “n” no of blocks we are required to create “n-1” conditions. In the switch statement, we can create multiple blocks under a single condition that reduces the coding part.

When we are working with nested if-else at even any point of time among those all blocks only one block gets executed. But in the switch statement, we can create more than one block depending on the requirement by removing the break statement between the blocks.

Some tricky questions related to Switch Statement in C.

Question1: What will be the output in the below program?
#include <stdio.h>
int main()
{
   int i;
   i = 3;
   switch(i)
   {
      case 1:
         printf("A");
         break;
      case 3:
         printf("C");
      case 2:
         printf("B");
         break;
      default:
         printf("D");
   }
   return 0;
}

Output: CB

This is because whenever we are working with switch statements randomly we can create the cases i.e. in any sequence it can be created. In order to execute the switch block, it can be executed all cases in sequence from the matching case onwards until it finds the break statement.

Question2: What will be the output in the below program?
#include <stdio.h>
int main()
{
   int i;
   i = 5;
   switch(i)
   {
      case 1:
         printf("A");
         break;
      default:
         printf("D");
      case 2:
         printf("B");
         break;
      case 3:
         printf("B");
   }
}

Output: DB

This is because when are working with the default it can be placed anywhere within the switch body i.e. top of the switch statement or middle of the switch statement or end of the switch statement but recommended to place at end of the switch body. Placing the default is always optional, it is required to place whenever we are not handling all statements of the switch body.

Question3: What will be the output in the below program?
#include <stdio.h>
int main()
{
   float i;
   i = 2; //i = 2.0
   switch(i)
   {
      case 1:
         printf("A");
         break;
      case 2:
         printf("B");
         break;
      case 3:
         printf("C");
         break;
      default:
         printf("D");
   }
   return 0;
}
Output:
Switch Statements in C

This is because whenever we are working with the switch statement it required condition and expression of type integer only i.e. float data we cannot pass within the switch.

Question4: What will be the output in the below program?
#include <stdio.h>
int main()
{
   int i;
   i = 2;
   switch(i)
   {
      case 1.0:
         printf("A");
         break;
      case 2.0:
         printf("B");
         break;
      case 3.0:
         printf("C");
         break;
      default:
         printf("D");
   }
   return 0;
}
Output:
Switch Statements in C Language in detail

This is because the case keyword required condition or expression of integer type value only i.e. we cannot pass float data as a case constant value.

Question5: What will be the output in the below program?
#include <stdio.h>
int main()
{
   int a = 1, b = 2, c = 3;
   int d = c-a;
   switch(d)
   {
      case a:
         printf("A1");
         break;
      case b:
         printf("B2");
         break;
      case c:
         printf("C3");
         break;
      default:
         printf("D4");
    }
   return 0;
}
Output:
C Switch Statements Examples
Question6: What will be the output in the below program?
#include <stdio.h>
int main()
{
   int i;
   i = 3-2;
   switch(i)
   {
	    case 2%2:
			printf("A");
			break;
	    case 5/2:
			printf("B");
			break;
	    case 3*2-3-2:
			printf("C");
			break;
	    default:
			printf("D");
    }
    return 0;
}

Output: C

This is because when we are passing expression format data then it works according to the return type of the expression.

Question7: What will be the output in the below program?
#include <stdio.h>
int main()
{
    int i;
    i = 5 < 8;
    switch(i)
    {
        case 2>5:
            printf("A");
            break;
        case !2 != 2:
            printf("B");
            break;
        case 8 < 5:
            printf("C");
            break;
        default:
            printf("D");
    }
    return 0;
}
Output:
C Switch Statements

This is because in switch statements we cannot create more than one case with the same constant value. If we are creating then the compiler will give an error called duplicate case.

Points Remember while working with Switch Statement in C Language:
  1. When we are working with the switch statement at the time of compilation switch condition/expression return value will match with the case constant value. At the time of execution if the matching case occurs then control will pass to the correspondent block, from the matching case up to the break everything will be executed, if the break does not occur then including default all cases will be executed.
  2. At the time of execution if the matching case does not occur then control will pass to the default block. Default is a special kind of case that will be executed automatically when the matching case does not occur. Using default is always optional, it is recommended to use when we are not handling all cases of the switch block.
  3. When we are working with the switch it required expression or condition as a type of integer only.
]]>
4071
Nested If-Else Statement in C  https://shishirkant.com/nested-if-else-statement-in-c/?utm_source=rss&utm_medium=rss&utm_campaign=nested-if-else-statement-in-c Sat, 02 Sep 2023 17:16:30 +0000 https://shishirkant.com/?p=4068 Nested if-else statements in C Language:

When an if-else statement is present inside the body of another “if” or “else” then this is called nested if-else. Nested ‘if’ statements are used when we want to check for a condition only when a previous dependent condition is true or false. C allows us to nested if statements within if statements, i.e. we can place an if statement inside another if statement.

What is the Nested If block?

Nested if block means defining if block inside another if block. We can also define the if block inside the else blocks. Depending on our logic requirements, we can use nested if block in n number of ways. You can define nested if block at many levels. First, we will see the syntax and example, and later part of this article, we will understand the flowchart by taking one example.

Nested If-Else Statement Syntax in C Language:

lease have a look at the below image which shows the different ways to use the nested if block in C Programming Language.

Nested If-Else Statement Syntax in C Language

Now, we will take one example and try to understand the flow chart. We are taking the following syntax. Here, we have an if-else block inside the if block, as well as, an if-else block inside the else block.

Nested If-Else Statement in C Language with Examples
How Nested IF ELSE work in C Language?

First, it will check the first if condition i.e. the outer if condition and if it is true, then the outer else block will be terminated. So, the control moves inside the first or the outer if block. Then again it checks the inner if condition and if the inner if condition is true, then the inner else block gets terminated. So, in this case, the outer if and inner if block statements get executed.

Now, if the outer if condition is true, but the inner if condition is false, then the inner if block gets terminated. So, in this case, the outer if and inner else block statements get executed.

Now, if the outer if condition is false, then the outer if block gets terminated and control moves to the outer else block. And inside the outer else block, again it checks the inner if condition, and if the inner if condition is true, then the inner else block gets terminated. So, in this case, the outer else and inner if block statements get executed.

Now, if the outer if condition is false as well as the if condition inside the outer else blocks also failed, then the if block gets terminated. And in this case, the outer else and inner else block statements get executed. This is how statements get executed in Nested if. Now we will see the flow chart of nested if blocks.

Flow chart of Nested If Block in C Programming Language:

First, have a look at the below diagram which shows the flow chart of the nested if-else statement.

Flow chart of Nested If Block in C Programming Language

First, it will check the outer if condition, and if the outer if condition is true, then the control comes inside and it will check the inner if condition, and if the inner if condition is true, then the outer if block statements and inner if block statements get executed. And after execution, it will come to end.

Suppose, the outer if condition is true but the inner if condition is failed, then the outer if block statements and the inner else block statement get executed. And once the statement gets executed, it will come to end.

Suppose, the outer if condition is failed, then the control directly comes to the else block and checks the inner if condition. And again, for the inner if condition two options are there. If the inner if condition is true, then it will execute the outer else block and inner if block statement, and if the inner if condition is false, then it will execute the outer else block and inner else block statements and then comes to end.

Program to understand Nested IF-ELSE statements in C Language:
#include <stdio.h>
int main()
{
int i = 10;
if (i == 10)
{
   if (i < 15) // First if statement
    printf("i is smaller than 15\n"); // Nested - if statement
    // Will only be executed if statement above is true.
      if (i < 12)
         printf("i is smaller than 12 too\n");
      else
         printf("i is greater than 15");
}
return 0;
}
Output:
Program to understand nested if else statements in C
Ladder if-else statements in C Language:

In Ladder if-else statements one of the statements will be executed depending upon the truth or falsity of the conditions. if the condition1 is true then Statement 1 will be executed and so on but if all conditions are false then Statement 3 will be executed. The C if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions are true, then the final else statement will be executed.

Ladder if-else statements in C Language
Syntax to use Ladder if-else statements in C Language:
Syntax to use Ladder if-else statements in C Language
Program to understand Ladder if-else statements in C Language:
#include <stdio.h>
int main()
{
  int i = 20;
  if (i == 10)
  {
    printf("i is 10");
  }
  else if (i == 15)
  {
    printf("i is 15");
  }
  else if (i == 20)
  {
    printf("i is 20");
  }
  else
  {
    printf("i is not present");
  }
}

Output: i is 20

]]>
4068
If Else Statements in C Language https://shishirkant.com/if-else-statements-in-c-language/?utm_source=rss&utm_medium=rss&utm_campaign=if-else-statements-in-c-language Sat, 02 Sep 2023 17:08:45 +0000 https://shishirkant.com/?p=4064 If Else statements in C Language with Examples

In this article, I am going to discuss If Else Statements in C Language with Examples i.e. how if and if-else block gets executed with the help of syntax, flow chart, and multiple examples. Please read our previous articles, where we discussed the basics of Control Statements in C. Before understanding if-else statements, let us first understand the Selection Statements in C Langauge.

What are Selection Statements in C?

Selection statements allow you to control the flow of program execution on the basis of the outcome of an expression or state of a variable known during run time. It executes different sections of code depending on a specific condition or the value of the variable. Selection statements can be divided into the following categories:

  • if-else statements (Will discuss in this article)
  • switch statements (Will discuss in the next article)
If Block in C Programming Language:

It executes a block of instructions (one or more instructions) when the condition in the if block is true and when the condition is false, it will skip the execution of the if block. Following is the syntax to use the if block.

If Block in C Programming Language
Flow Chart of If Block:

Let us see how we will represent the execution flow of the if block using a flow chart. The starting point is represented by the oval symbol. And the flow will be from the condition and the condition is represented by a diamond shape. Here, first, we need to check the condition. And for every condition, two options are there i.e. if conditions are successful (condition is true) and if conditions are failed (condition is false). That means two situations are there i.e. TRUE and FALSE. Suppose, the condition is TRUE, then what all statements are defined inside the if block gets executed. And the statements we are representing in a flow chart with the help of a parallelogram symbol. And after the execution of the statements, the control will come to end. Suppose, the condition is false, then without executing any statement, it will come to the end. For better understanding, please have a look at the below diagram which represents the flow chart of the if conditional statement.

Flow Chart of If Block

Note: Here, the block of statements executes only when the condition is true. And if the condition is false, then it will skip the execution of the statements.

Example: Program to check whether the number is greater than 10

Here, we will take the number from the user and then we will check whether that number is greater than 10 or not using If Statement in C Language. The following program exactly does the same.

#include<stdio.h>
int main()
{
int number;
printf("Enter a Number : ");
scanf("%d", &number);
if(number > 10)
{
  printf("%d is greater than 10 \n", number);
  printf("End of if block \n");
}
printf("End of Main Method");
return 0;
}

In the above program, inside the main method, we are declaring one integer variable i.e. number, and then we are taking the input from the user by using the scanf function and storing it in the number variable.

After reading the input we are checking whether the given number is greater than 10. If the number > 10, then if the condition is true and, in that case, we are executing the two statements that are present inside the block else if the condition is false, then the if block statements will be skipped and the last printf statement gets executed.

For example,

  1. We take 15 as an input, 15 > 10 means the condition is true, then the if block statement gets executed.
  2. We take 5 as an input, 5 > 10 means the condition is false, then the if block statements will be skipped

For a better understand, please have a look at the below image.

WAP to check whether the number is greater than 10
If Statement without Curly Braces in C Language

In the declaration of if block if we do not specify statements using blocks ({}) nothing but braces, then only the first statement will be considered as the if block statement. To understand this point please have a look at the below example.

#include<stdio.h>
int main()
{
int number;
printf("Enter a Number : ");
scanf("%d", &number);
if(number > 10)
    printf("%d is greater than 10 \n", number);
printf("End of Main Method");
return 0;
}

As you can see, in the above example, we have not specified the curly braces to define the if block. In this case, only the first statement will be considered as the if block statement. The second statement will not be a part of the if block. For a better understanding, please have a look at the below image. The statement which is in red color will belong to the if block and the statement which is in the black color do not belong to the if block.

If Statement without Curly Braces in C Language

So, when you execute the above program, irrespective of the condition, the black statement is always going to be executed as it is not part of the if block. The red statement is only executed when if the condition is true. For a better understand, please have a look at the below image.

If Statement without Curly Braces in C Language with Examples
If Else Block in Programming Language:

The If-Else block is used to provide some optional information whenever the given condition is FALSE in the if block. That means if the condition is true, then the if block statements will execute, and if the condition is false, then the else block statement will execute. Following is the syntax to use IF ELSE block in most of the programming languages.

If Else Block in Programming Language

Note: The point that you need to remember is, only one block of statement i.e. either if block or else block is going to be executed at a time. So, if the condition is TRUE if block statements get executed and if the condition is FALSE, else block statements get executed.

Is it mandatory to use else block?

No, it is not mandatory to use else block. It is an optional block. You can use only if block also. If you want to provide any information when the condition is failed, then you need to use this optional else block.

Flow Chart of If-Else Block:

The flow chart of the if-else block is almost similar to the if block. In this case, when the condition is true, the if block statements get executed and when the condition is false, the else block statements get executed. For better understanding, please have a look at the below image which shows the flow chart of the if-else block.

Flow Chart of If-Else Block
Points to Remember:

The ‘if’ control statement allows you to check the validity of a certain condition and perform required operations depending on the condition. If the condition followed by the ‘if’ keyword holds True, the code is written inside the braces of the ‘if’ statement will be executed, otherwise the program control will skip the loop execution and continue with the remaining program. ‘if’ statement is generally accompanied by the ‘else’ block which lets the compiler know about actions to be performed if the condition following the ‘if’ statement is False.

Note: In C Programming Langauge, if and else are reserved words. The expressions or conditions specified in the if block can be a Relational or Boolean expression or condition that evaluates to a TRUE(1) or FALSE(0). 

Now let us see some examples to understand the if-else conditional statements.

Example: Program to check whether a number is even or odd.

Here we will take the input number from the user and then we will check whether that number is even or odd using the if-else statement in C Language. The following program exactly does the same.

#include<stdio.h>
int main()
{
int number;
printf("Enter a Number : ");
scanf("%d", &number);
if(number % 2 == 0)
{
    printf("%d is an Even Number", number);
}
else
{
    printf("%d is an Odd Number", number);
}
return 0;
}

In the above program, inside the main method, we are declaring one integer variable i.e. number and then we are reading input from the user using the scanf function and storing the value in the address of the number variable. After reading the input we are checking whether the given number is even or odd. An Even number is a number that is divisible by 2.

If number % 2 equals 0, then the if condition is true and, in that case, we are printing a message that it is an even number and if the condition is false then we are printing a message that it is an odd number.

For example,

  1. We take 16 as an input, 16%2 == 0 means the condition is true, then the if block statement gets executed. And the output will be 16 is an Even Number.
  2. We take 13 as an input, 13%2 == 0 means condition is false, then the else block statements get executed. And the output will be 13 is an Odd Number.

For a better understand, please have a look at the below image.

Write a Program to check whether a number is even or odd
If and Else Block without Curly Braces in C Programming Language

In the declaration of if block or else block if we do not specify statements using blocks ({}) nothing but braces, then only the first statement will be considered as the if block or else block statement. Let us understand this point with some examples. Please have a look at the below example.

#include<stdio.h>
int main()
{
 if(1 == 1)
    printf("Hi\n");
 else
    printf("Hello\n");
printf("Bye\n");
return 0;
}

As you can see, in the above example, while creating the if and else block we have not specified the curly braces. So, in this case, the first printf statement will belong to the if block. After the else statement, we have two printf statements. Here, the printf statement which printing the Hello message will belongs to the else block only. The next printf statement which printing the message bye will not belong to else block. Now, if you execute the above program then you will get the following output.

If and Else Block without Curly Braces in C Programming Language

Now, if we replace the Hello statement in the if block, then an ERROR message will be displayed. The reason is, not more than one statement gets executed without braces. One statement will execute inside the if block. If we want to execute more than one statement then you should use braces and all the statements will be inside the braces. For better understanding, please have a look at the below example.

#include<stdio.h>
int main()
{
if(1 == 1)
    printf("Hi\n");
    printf("Hello\n");
else
    printf("Bye\n");
return 0;
}

Now, while compiling the code, you will get the following error.

If and Else Statement without Curly Braces in C Programming Language

Note: For every if condition statement else block is optional. But for every else block if block is compulsory. The purpose of the ‘if’ statement in a program is to allow multiple execution paths for varying user inputs, making it more interactive!

]]>
4064
Control Statements in C https://shishirkant.com/control-statements-in-c/?utm_source=rss&utm_medium=rss&utm_campaign=control-statements-in-c Sat, 02 Sep 2023 05:12:54 +0000 https://shishirkant.com/?p=4058 Control Statements in C:

Control Statements are the statements that alter the flow of execution and provide better control to the programmer on the flow of execution. They are useful to write better and more complex programs. A program executes from top to bottom except when we use control statements, we can control the order of execution of the program, based on logic and values.

In C, control statements can be divided into the following three categories:

  • Selection Statements or Branching statements (ex: if-else, switch case, nested if-else, if-else ladder)
  • Iteration Statements or looping statements (ex: while loop, do-while loop, for-loop)
  • Jump Statements (ex: break, continue, return, goto)
Control Statements in C Language

C Control Statements are used to write powerful programs by repeating important sections of the program and selecting between optional sections of a program.

In the next article, I am going to discuss If else Selection Statements in C with examples. Here, in this article, I try to explain what is Control Statements in C, and their type. I hope you enjoy this Control Statements in C Language article. I would like to have your feedback. Please post your feedback, question, or comments about this Control Statements in the C Language article.

]]>
4058
Type Casting in C Programming https://shishirkant.com/type-casting-in-c-programming/?utm_source=rss&utm_medium=rss&utm_campaign=type-casting-in-c-programming Sat, 05 Aug 2023 18:19:57 +0000 https://shishirkant.com/?p=4049 Type Casting in C Language

In this article, I am going to discuss Type Casting in C Language with examples. Please read our previous article, where we discussed the Data Types in C Language. As part of this article, you will learn what is Type Casting in C, and why do we need Typecasting in C Language with examples.

Why do we need Type Casting in C?

If both data types are the same type then the return value will be the same. If both data types are different then among those two bigger ones will be the return type. When we are working with integral value with the combination of float then always return value will be float type. Let us understand this with an example.

#include <stdio.h>
int main()
{
   int i = 10000;
   long int l;
   float f;
   i = 32767 + 1;
   l = 32767 + 1;
   f = 32767.0f + 1;
   printf("%d %ld %f", i, l, f );
   return 0;
}

Output: 32768 32768 32768.000000

But what if you want to store a bigger value like a float in a smaller variable like int. Then in such cases, we need typecasting.

What is Type Casting in C Language?

It is a concept of converting one data type values into another data type. Typecasting is performing by using the cast operator. The compiler will automatically change one type of data into another if it makes sense. For instance, if you assign an integer value to a floating-point variable, the compiler will convert the int to float. Casting allows you to make this type of conversion explicit, or to force it when it wouldn’t normally happen.

Type conversion in c can be classified into the following two types:

  • Implicit Type Conversion
  • Explicit Type Conversion
Syntax:
What is Type Casting in C Language
Example to Understand Type Casting in C Language:
#include <stdio.h>
int main ()
{
   float f = 10.25;
   int i; 
   i = (int) f;
   printf ("%d %f", i, f);
   return 0;
}
Output:

In the above C program, we are trying to store the floating value in an integer variable. So, we typecast it before storing it into the integer variable.

Note: It is best practice to convert lower data types to higher data types to avoid data loss. Data will be truncated when a higher data type is converted to lower. For example, if the float is converted to int, data that is present after the decimal point will be lost.

What is the cast operator in C?

Cast operator is a data type present in between parenthesis after the equal (=) operator and before the source variable.

Implicit Type Conversion or Implicit Type Casting in C:

When the type of conversion is performed automatically by the compiler without the programmer’s intervention, such type of conversion is known as implicit type conversion or type promotion.

It is the concept of converting lower data type values into higher data types. Implicit type casting is under the control of the compiler. So a programmer no needs to be considered the implicit type casting process. Let us see an example for a better understanding.

#include <stdio.h>
int main ()
{
   int i = 12345;
   long int l;
   l = (long)i; // Implicit casting from int to long int
   printf("%d %d", i,l);
   return 0;
}

Output: 12345 12345

Explicit Type Conversion or Explicit Type Casting in C:

The type conversion performed by the programmer by posing the data type of the expression of a specific type is known as explicit type conversion. The explicit type conversion is also known as typecasting.

It is a process of converting a higher data type value into a lower data type. Whenever the explicit type casting has occurred mandatory handling or else data overflow will occur. The typecasting in c is done in the following form:

(data_type) expression; where, data_type is any valid c data type, and expression may be constant, variable, or expression. Let us see a program for understanding this concept

#include <stdio.h>
int main ()
{
   double d = 12345.6789;
   int l;
   l = (int)d; //Explicit casting from double to int
   printf("%d %lf", l, d);
   return 0;
}

Output: 12345 12345.678900

Rules for Type Casting in C:

The following rules have to be followed while converting the expression from one type to another to avoid the loss of information:

  1. All integer types are to be converted to float.
  2. All float types are to be converted to double.
  3. All character types are to be converted to an integer.
Rules for Type Casting in C

Example:
int x=7, y=5;
float z;
z=x/y; /*Here the value of z is 1*/ 

If we want to get the exact value of 7/5 then we need explicit casting from int to float:

Example:
int x=7, y=5;
float z;
z = (float)x/(float)y; /*Here the value of z is 1.4*/

Inbuilt TypeCast Functions in C Language

There are many inbuilt typecasting functions available in C language which performs data type conversion from one type to another.

  • atof() Converts a string to float
  • atoi() Converts a string to int
  • atol() Converts a string to long
  • itoa() Converts int to string
  • ltoa() Converts long to string
atof() function in C:

The atof() function in the C language converts string data type to float data type. The “stdlib.h” header file supports all the typecasting functions in the C language.
Syntax: double atof (const char* string);

Example to understand the atof() function in C:
#include <stdio.h>
#include <stdlib.h>
int main()
{
   char a[10] = "3.14";
   float pi = atof(a);
   printf("Value of pi = %f\n", pi);
   return 0;
}

Output: Value of pi = 3.140000

atoi() function in C:

The atoi() function in C language converts string data type to int data type.
Syntax: int atoi (const char * str);

Example to understand the C atoi() function:
#include <stdio.h>
#include <stdlib.h>
int main()
{
   char a[10] = "100";
   int value = atoi(a);
   printf("Value = %d\n", value);
   return 0;
}

Output: Value = 100

atol() function in C:

The atol() function in C language converts string data type to long data type.
Syntax: long int atol ( const char * str );

Example to understand atol function in C:
#include <stdio.h>
#include <stdlib.h>
int main()
{
   char a[20] = "100000000000";
   long value = atol(a);
   printf("Value = %ld\n", value);
   return 0;
}

Output: Value = 1215752192

itoa() function in C:

The itoa () function in the C language converts int data type to string data type.
Syntax: char *  itoa ( int value, char * str, int base );

Example to understand itoa function in C:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
   int a=54325;
   char buffer[20];
   itoa(a,buffer,2); // here 2 means binary
   printf("Binary value = %s\n", buffer);
   itoa(a,buffer,10); // here 10 means decimal 
   printf("Decimal value = %s\n", buffer);
   itoa(a,buffer,16); // here 16 means Hexadecimal
   printf("Hexadecimal value = %s\n", buffer);
   return 0;
}
Output:
Example to understand itoa function in C

Note: “stdlib.h” header file supports all the typecasting functions in C language. But, it is a nonstandard function.

ltoa() function in C:

The ltoa() function in the C language converts long data type to string data type.
Syntax: char *ltoa(long N, char *str, int base);

Example to understand C ltoa function:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
   long a=10000000;
   char buffer[50];
   ltoa(a,buffer,2); // here 2 means binary
   printf("Binary value = %s\n", buffer);
   ltoa(a,buffer,10); // here 10 means decimal
   printf("Decimal value = %s\n", buffer);
   ltoa(a,buffer,16); // here 16 means Hexadecimal
   printf("Hexadecimal value = %s\n", buffer);
   return 0;
}
Output:
Example to understand C ltoa function
]]>
4049
Sizeof and Limits of Data Type in C Programming https://shishirkant.com/sizeof-and-limits-of-data-type-in-c-programming/?utm_source=rss&utm_medium=rss&utm_campaign=sizeof-and-limits-of-data-type-in-c-programming Sat, 05 Aug 2023 18:10:46 +0000 https://shishirkant.com/?p=4045 Sizeof and Limits of Data Type in C Language

In this article, I am going to discuss Sizeof and Limits of Data Types in C Language with Examples. In our last article, we discussed Character Data Type in C Language briefly. In this article, we are going to discuss two more concepts related to data type. The first one is the sizeof method or we can also call it sizeof operator and the second one is the limits of each data type.

Sizeof() Fucntion in C Language

The sizeof function is a predefined function just like the printf and scanf() functions.

What is the use of sizeof function in C?

The sizeof function in C Language is used to return the size of different things. So, what are the different things? The sizeof function returns the size of the following four things.

  1. Size of a variable.
  2. Size of a data type
  3. Size of an expression
  4. Size of a pointer

So, we can pass either variable, data type, expression, or pointer as an argument to the sizeof function. The sizeof function is a predefined function and that will return the size of different types of things. So, if you want to find out the size of any data type, we can go for a sizeof function. For better understanding, please have a look at the following diagram.

Sizeof and Limits of Data Type in C Language
Predefined sizeof function example in c language:

Please have a look at the following example which uses the predefined sizeof function.

#include<stdio.h>
#include<conio.h>
int main()
{
   char C;
   short S;
   printf("size of char : %d bytes(s)\n", sizeof(C));
   printf("size of short : %d bytes(s)\n", sizeof(S));
   printf("size of float : %d bytes(s)\n", sizeof(float));
   return 0;
}

In the above program, first, I am declaring two variables. One is of type character i.e. C and the second one is of type short i.e. s. Then I print the size of these two variables using the sizeof function.

What is the size? The size representation is always in the form of integers. So always use %d format specifier to show the size. Here, we are passing the variable names to the sizeof function. When we pass C variable name to the sizeof function, then it will return the size of the character. The size of the character is one byte. so it will print that value one.

Next, it will send the control to the next line. In the next line, we are printing the size of short, it is also %d because size is always in integers. And we know the size of the short is 2 bytes, so it will print 2 and send the control to the next line.

Whenever we are the calling sizeof function, we can pass either variable name, data type name, expression or pointer. In the next line, we are passing the data type float to the sizeof function. The size of the float is 4 bytes. So here it will print the value as 4 bytes.

So, when you run the above program, you will get the following output.

Predefined sizeof function example in c language

In our upcoming articles, we discuss how to pass expression and pointer to the sizeof function in C Language.

Limits of data type in C Language

Now we will understand the limits of a data type. What are the limits of a data type means we have one header file i.e. limits.h. The Limits.h header file contains n number of predefined variables and all these predefined variables are global variables. Global variable means we can access these variables from anywhere in any c application. These variables are also called constant variables. Constant variable means we cannot modify the values of these variables. We cannot modify limits.h header file. For better understanding, please have a look at the following diagram.

Limits of data type in C Language

Now we will see some programs on how to use a sizeof function and then we will see how to work with the limits.h variables.

Example to understand limits of data type in C Language:

Now, we will see how to print the limits of each data type. The Limits.h header file contain so many predefined constant variables i.e global variables. The limits.h header contains many predefined variables as shown in the below image,

Example to understand limits of data type in C Language

In any programming language, if you want to represent a constant variable. Then mostly, we are using capital letters only. All these variables are belonging to signed type and unsigned type.

The minimum range of every unsigned datatype starts with a zero. That is why they didn’t provide that info. All these variables are available in a limits.h, and all these are global variables. you can access anywhere in a C application and all these are constants.

Example:

Please have a look at the below program.

#include<stdio.h>
#include<limits.h>
int main()
{
   printf("Signed short MIN Value %d\n", SHRT_MIN);
   printf("Signed short Max Value %d\n", SHRT_MAX);
   printf("Unsigned short Max Value %d\n", USHRT_MAX)
   printf("Signed char MIN Value %d\n", SCHAR_MIN);
   printf("Signed char Max Value %d\n", SCHAR_MAX);
   printf("Unsigned char Max Value %d\n", UCHAR_MAX);
   return 0;
}

In the above program, we include the limits.h header file. This is because we are using some of the variables which are related to limits.h header file. Or else you will get an error message. When you run the above program, you will get the following output.

Sizeof and Limits of Data Type in C Language
]]>
4045
Character Data Types in C Programming https://shishirkant.com/character-data-types-in-c-programming/?utm_source=rss&utm_medium=rss&utm_campaign=character-data-types-in-c-programming Sat, 05 Aug 2023 18:07:38 +0000 https://shishirkant.com/?p=4041 Character Data Types in C Language with Examples

In this article, I am going to discuss Character Data Types in C Language with Examples. Please read our previous article where we discussed Integer Data Types in C Language. At the end of this article, you will understand everything about character data type in c language.

Character Data Types in C Language

The character data type is divided into two types one is signed data type and the second one is unsigned data type.

Character Data Types in C Language

Both Signed data type and unsigned data type occupy only one byte of memory. Unsigned means it will accept only positive values and the signed means it will accept both positive as well as negative values. Whatever the type either signed or unsigned, the character occupies only one byte.

Using 1 byte of memory what is the minimum and maximum value we can store?

To understand this, look at the memory allocation process. Here I am taking 1 byte of memory. 1 byte equals 8 bits. And it takes only binary values i.e. 0 and 1. Now, if we place zeros in all 8 places then the value will be zero which is the minimum we can store in a 1-byte memory location as shown in the below image.

Using 1 byte of memory what is the minimum and maximum value we can store?

If we place all ones in all the 8 bits, the value is 255. So, the maximum integer value we can store in 1 byte is 255 as shown in the below image.

Using 1 byte of memory what is the minimum and maximum value we can store?

So, using 1 byte of memory, the minimum integer value we can store is 0 and the maximum integer value we can store is 255.

Unsigned Character Range in C Language:

As we already discussed unsigned means it will accept only positive values. And the range 2equals 256. As positive value starts with 0, so, the unsigned character data type range is from 0 to 255.

Signed Character Range in C Language:

Now let us understand the range of Signed character data types. The signed data type accepts both positive as well as negative values. So, we need to divide 28 = 256 by 2. 256/2 the value is 128. So negative values start with -1, -2, and up to -128 and the positive values start from 0 up to 127.

We are using character data type to store symbols like a, b, A, B, or some special symbols. Then how can we represent such symbols in integers? Why character data type representation in integer. So, while working with Character Data Types in C Language, we need to understand the following four questions.

  1. Why does character limits representation in integers?
  2. How can we store symbols into one-byte memory nothing but why character occupies one-byte memory?
  3. What is a character system?
  4. What is ASCII?

Consider the below diagram. It is a simple program and we name this program as Program.c, and inside the main method, we are declaring one integer local variable and assigned with a value of 10 and the remaining instructions are also there as it is. We can call it source code.

Character Data Types in C Language with Examples

In our previous article, we already discussed that whatever program we have written using any high-level programming language that the system cannot understand. This is because the system can understand only binary language. But you have written an English statement. We should convert all these high-level instructions into low-level. Who will convert? The Answer is the compiler.

The compiler is a predefined program. We need to pass the source code to the compiler and the compiler will then generate the binary instructions code which is in the form of zeros and ones. So, the compiler needs to convert all these high-level instructions into machine level. Consider 10, it will convert into binary i.e. 1010 and this is possible by using the number system. So, using the number system concept we can convert the decimal value to binary value.

But here the problem is how it is converted #, <, >, a, I, A, etc. symbols into binary. If the decimal value is there, we can use a number system to convert it into binary. But how we can convert characters (a, b, A, B) and special symbols (#, <. >, etc.) into binary? The answer is the character system. Only for computer programming languages, the character system was introduced.

What is a character system?

Using a character system, we can represent one entire language into integer constants. For example, the English language contains capital letters, small letters, digits special symbols, etc., and using a character system we can represent all the above characters and symbols into integer constants. This is called a character system.

How many character systems are available?

A list will come if you search on google. A number of character systems are available. The first computer was introduced into the market by IBM. IBM is having its own character system. Now, the famous one is the ASCII character system, and every programming language follows the ASCII character system only. Let us see how using the ASCII character system, we can represent one particular language.

What is ASCII? What it stands for?

Now let us understand the English language ASCII Code. ASCII stands for Americans Standard Code for Information Interchange. A standard code means it is a fixed code, no one can change the value and no one can modify the value. It is used to interchange the information from high-level language to low-level language.

How ASCII represents?

To understand how ASCII represents the English language, please have a look at the below diagram,

What is ASCII? What it stands for?

As you can see in the above image, capital A is represented by a constant integer value 65 and this is the fixed value and no one can change this value. The next one is for capital B and is 66 and for capital C it is 67, so on and for capital Z it is 90. The value of small a is 97 and small B is 98 and so on up to small z whose value is 122.

For digit 0, the ASCII value is 48, for 1 the value is 49 and for 9, the ASCII value is 57. Using the digits 0 to 1, you can construct any number, so they have given ASCII for 0 to 9 only.

For special characters, if it is a space the value is 32, for #, the value is 35, and so on for every symbol. So, every character, digit, special symbol, is represented by a constant integer value in the character system. Not only in the ASCII character system but in any character system which is available in the market.

So, for every language like English, Hindi, Odia, there is a character system. Here, the above diagram representing the English language using the ASCII character system, and these are the standard values.

How can we store a symbol into one-byte memory?
How can we store a symbol into one-byte memory?

Just count all the values, so total will 26 capital alphabets we have in English and 26 small letters and next 10 numbers and not more than 150 special symbols. So here if you add all these, then this is less than 256. Any language you can take in this world, it is at most having 256 symbols. So, ASCII decided that if we assign the values for these symbols from 0 to 255, so you can represent any character in the language using one byte of memory.

How can we say that one-byte memory?

256 is nothing but a 2 power 8 value. 2 power 8 is nothing but a one-byte memory. This is the only reason every character we can represent using one byte of memory in a programming language.

Character Data Types Examples in C Language

Now we will see some of the examples on the character data type. First, let us understand the unsigned character and signed character in the form of circles.

Understanding signed char data type circle in c Language.

If it is a signed character the limits are from -128 to +127. Let us write all these limits in the form of a circle and based on these circles only we will see how programs will execute.

Either positive value or negative value always the counting starts with 0. Positive value counting starts from 0, 1, 2, and so on up to 127 in a clockwise direction, and here the maximum positive value is 127. Negative values counting starts from -1, -2, -3, and so in up to -128 in an anti-clockwise direction as shown in the below image.

Understanding signed char data type circle in c Language.

Note: In the declaration of variable if you are not specifying whether the variable is a signed variable or unsigned variable by default it is a signed variable and can accept both positive and negative values.

Understanding unsigned char data type circle in c Language.

If it is an unsigned character the limits are from 0 to 255 and the unsigned char data type accepts only positive values. In the case of unsigned char, the circle starts from 0, 1, 2, so on and ends with 255 i.e. the maximum positive value is 255 as shown in the below image.

Understanding unsigned char data type circle in c Language
Example to understand character data type in c language:

Following is a simple example of a c program using char data type. Here, inside the main function, we are declaring one character variable with the name CH (you can give any name as per your choice) and assigning this variable with the value A. In the C programming language, we are representing characters by using single quotes. Then we are printing the character in the console. To print the character in the console we need to use the format specifier as %c. %c is the format specifier for character and it will print the value A in the console. Next, we have also written the %d format specifier for the character variable CH. In this case what it will print? Here, it will print the corresponding ASCII value of character A which is nothing but 65.

#include <stdio.h>
int main()
{
  char CH = 'A';
  printf("%c", CH);
  printf(" %d", CH);
  return 0;
}

Output: A 65

Now we will see some tricky questions on character data type which are mostly asked in interviews.

#include <stdio.h>
int main()
{
   char CH = 258;
   printf("%c", CH);
   printf(" %d", CH);
   return 0;
}

In the above example, we have initialized the character variable CH with a value of 258. Yes, we can store integers on the character data type. The above CH variable is by default a signed character. So, to understand what value it will store we need to understand the signed char circle and see the actual value of 258. As 258 is a positive value, so the count will start from 0, 1, and so on in a clockwise direction. In the circle when it reached 127, the next value is -128 (in count it will be 128), the next is -127 (in count it will be 129), and in the same way, -1 will be for 255, the next value in the circle is 0 which is 256, 1 for 257, and 2 for 258. So, in the variable instead of 258, it will store.

Example to understand character data type in c language

So, in the output for %d format specifier, it will print 2 and for character specifier, it will print some unknown value i.e. 2 corresponding unknown characters it will print from the ASCII character system and when you run the above code, you will get the following output.

Example to understand character data type in c language

Now, we will see how to write a program in which we will input one character and it has to print that corresponding ASCII value. In this program, we are going to work with the scanner function. Using the scanf function, we are taking input from the end-user in the C programming language.

What is a console?

The console is where you can see the output and where we can give the input.

Write a program to display ASCII value of character input by end-user.

We want to read information from the end-user while the application is executing is our concept. We are reading information from end-user i.e. we are taking input from the end-user. Please have a look at the below program. Here, I am declaring one character variable with the name CH i.e. char CH; here, the variable CH gets memory allocation.

On the console first, we print a message and asking the end-user to enter a character. We are reading the end-user input using the scanner function. The scanner function is available in stdio.h header file.

What end-user want to do they cannot understand that, so that is the reason we need to provide some information. Best example atm application, whenever you enter into an atm center clear information it will show please choose one language, insert your atm card, insert your pin number and how much amount you want to withdraw. Information is very important, how good you are writing the logic is not at all matters. First, we are asking the message very clearly i.e. enter one character. Whatever the message you have written in the printf function, that will be written on the console. It will print that message enter a character.

Whenever the end-user will enter one character, for example, the end-user entered a character h. Then automatically system will print the ASCII value of h. h should be stored in some memory location. So here we need to provide a memory address. How to provide a memory address, who will provide a memory address? So, for the first time, we are using scanf function in C programming.

If you want to read only one character, so write one time %c format specifier. If you want to read ten characters then you have to write %c 10 times. But here it is only one character, so here we are specifying the character address by using the & address operator. It will return the address of the memory location of the CH variable. Whatever character we have given in the console will be stored in that location. h corresponding ASCII value will be converted into binary and then the binary value will go and store in that memory location. Now we want to print the ASCII value just printf “ASCII Value is %d” and output will be generated. Whatever we discussed above is given in the below example.

#include <stdio.h>
int main()
{
   char CH;
   printf("Enter a Character : ");
   scanf("%c", &CH);
   printf("ASCII Value is %d", CH);
   return 0;
}
Output:
Write a program to display ASCII value of character input by end-user.
]]>
4041
Integer Data Types in C Programming https://shishirkant.com/integer-data-types-in-c-programming/?utm_source=rss&utm_medium=rss&utm_campaign=integer-data-types-in-c-programming Sat, 05 Aug 2023 18:01:02 +0000 https://shishirkant.com/?p=4038 Integer Data Types in C Language with Examples

In this article, I am going to discuss Integer Data Types in C Language with examples. Please read our previous article where we discussed the basics of Data Types in C. We already discussed in our previous article that the Integer data type is divided into six classifications as shown in the below image.

Integer Data Types in C Language with Examples

The first classification is short type. Short again divided into two sub-classifications, it is signed short and unsigned short. Either it is a signed short or is unsigned short, it occupies two bytes of memory.

What is a signed data type?

Using signed data type both positive and negative values we can store.

What is the unsigned data type?

Using unsigned data types, we can store only positive values.

Using 2 bytes of memory what is the minimum and maximum value we can store?

To understand this, look at the memory allocation process. Here I am taking two bytes of memory. 1 byte equals 8 bits, so 2 bytes equals 16 bits. And it takes only binary values i.e. 0 and 1. Now, if we place zeros in all the 16 places then the value will be zero which is the minimum we can store in 2 bytes memory location as shown in the below image.

Using 2 bytes of memory what is the minimum and maximum value we can store?

If we place all ones in all 16 bits, the value is 65535. So, the maximum integer value we can store in 2 bytes is 65535 as shown in the below image.

Using 2 bytes of memory what is the minimum and maximum value we can store?

So, using 2 bytes of memory, the minimum integer value we can store is 0 and the maximum integer value we can store is 65535. Now, let us come to the signed and unsigned data type. 1 byte is 8 bits and 2 bytes is 16 bits. The unsigned short data type can store only positive integer values ranges from 0 to 65535 as shown in the below image.

Integer Data Types in C Language

The signed short data type can store both positive and negative values. So, here just divide the value by 2 i.e. 65536/2 which will result in 32768. The negative or minus value always starts from -1, -2, up to -32768. And the positive value starts from 0, 1, and up to 32767 for signed short as shown in the below image.

Integer Data Types in C Language
Declaration of signed short Data Type in C Language:

If you do not specify whether the variable is a signed variable or an unsigned variable, by default that is a signed variable and can accept both positive and negative values. Following are the examples of declaring signed short variables in c language

short a;
short int a;
signed short a;
signed short int a;

For All the above four signed declarations, the format specifier is %d. In these many ways, we can declare a signed variable in our C program.

Declaration of unsigned short Data Type in C Language:

In unsigned declarations, we must specify explicitly that these are unsigned declarations. Following are the two ways to declare unsigned short data type in c language.

unsigned short a;
unsigned short int a;

For these two unsigned declarations, the format specifier is %u. So, these are the total of six declarations about a short data type. First, four comes under the signed short declarations and the last two comes under the unsigned declarations. For better understanding, please have a look at the below image.

Declaration short Data Type in C Language
The next important thing is what is format specifier?

If you want to read the information or if you want to display the information, formatting is very important. In which format do you have to read information and in which format do you have to print the information. That you have to specify to the computer using a format specifier.

Example:

Now we will see some programs. I just want to print a small value on the console. We are writing the program and the execution starts from the main method. I am declaring one variable; it is a short variable and then prints it on the console.

#include <stdio.h>
#include <stdlib.h>
int main()
{
   short a = 10;
   system("cls");
   printf("%d", a);
   return 0;
}

Output: 10

In the above example, short a = 10; declaring a variable of type short and assigned with value 10. We want to print the value of the variable on the console, so here, we are using printf function which belongs stdio.h header file. Inside the double quotes, we have to write the format specifier. As variable a is a signed variable, so the format specifier is %d and we want to print the value of a. Value of a is 10, so program output will be 10.

Note: To clear the screen in the Linux system use system(“clear”) function which is included in stdlib.h, and if you use this in the window use the system(“cls”).

This is a very simple program and here, format specifier is very, very important. With the help of a format specifier only we are reading the elements and printing the elements.

Complex Examples using short Data Type in C Language:

Next, we will see some complex programs. Consider the limits of signed short data type in the form of a circle. The range of minimum and maximum values of signed short data type is -32768 to +32767 as shown in the below image.

Any value you want to count, whether +VE values and -VE values, the count is always going to start from 0. Positive values are going to be count in a clockwise direction and the maximum value is 32767. The negative values count is going to be the anti-clockwise direction and it will start from 0, -1, -2, up to -32768. For better understanding please have a look at the below diagram.

Complex Examples using short Data Type in C Language

Based on the above diagram we will see one program. I just want to print a big value on the console. We are writing the program and execution starts from the main method. I am declaring one short variable.

#include <stdio.h>
int main()
{
   short a = 32769;
   printf("%d", a);
   return 0;
}

Output: -32767

Why we are getting -32767, not 32769. As the value is a positive number so the count will start clockwise from 0 and reach the maximum value of 32767. Now, please observe, what is the next value of 32767 in clockwise direction, it is -32768 (32767+1 = 32768) and what the next value, it is -32767 (32768+1 = 32769) and that is printed on the console. So, in this case, when the value exceeds, it will print a garbage value. In this case, it is not giving any error instead it prints a garbage value.

Unsigned short Integer Data Type Example in C Language:

Now we will see one more program. Please have a look at the below example. Here, we are declaring a variable of unsigned short type but assigning a negative value i.e. -5. We know, unsigned short only take positive values. Let us first execute the program and see the output.

#include <stdio.h>
int main()
{
   unsigned short a = -5;
   printf("%d", a);
   return 0;
}

Output: 65531

To understand why we are getting 65531 in the output, we need to understand the unsigned short data type in the form of a circle. The range of minimum and the maximum values is 0 to 65535 for unsigned short and it moves in a clockwise direction for +VE values and anti-clockwise direction for -VE values as shown in the below image.

Unsigned short Integer Data Type Example in C Language

Now, as we are assigning -5 to the unsigned variable, so it will start counting in an anti-clockwise direction. So, it will start from 0, then 65535 for -1, 65534 for -2, 65533 for -3, 65532 for -4, and 65531 for -5 and it will store 65531 in the memory location, and that is what you can see in the memory output.

As we are using the %u format specifier, it will look into an unsigned circle diagram for the value of a. In the memory location, the value of a will be stored as 65531. Because -5 is not in the range of unsigned short variable, so it will look in an anti-clockwise direction.

Example: unsigned short Integer in C Language

Now we will see one more program. In the below program, we declare an unsigned variable and assigned it a value 65538.

#include <stdio.h>
int main()
{
   unsigned short a = 65538;
   printf("%u", a);
   printf(" %d", a);
   return 0;
 }

Output: 2 2

Let us understand why we are getting 2 as the output. To understand this, first, we need to understand what value is going to be stored in the memory location for the variable a. So, here, the variable a data type is unsigned, so it will check the unsigned circle which is start from 0 and ends with 65535 and counts the numbers in a clockwise direction. So, it will start from 0, and goes up to 65535 in the circle. What is the next value in the clockwise direction of 65535, it is 0. So, 0 for 65536, 1 for 65537, and 2 for 65538. So, in the memory location, it will store the value 2.

Now, in the first printf statement, we have used the %u format specifier, so it will check the unsigned short circle and found value 2 is therein and hence it will print that value. In the second printf statement, we have used %d format specifier, so it will check the signed short circle and found value 2 is therein and hence it will also print that value in the console.

Now we will see one more program. In the below program, we declare one unsigned short variable and assigned it with a value -32772.

#include <stdio.h>
int main()
{
   unsigned short a = -32772;
   printf("%u", a);
   printf(" %d", a);
   return 0;
}

Output: 32764 32764

]]>
4038