Tuesday, November 5, 2019

C-switch-statement

'switch' statement in C


Consider a situation in which we have many options out of which we need to select only one option that is to be executed. Such kind of problems can be solved using nested if statement. But as the number of options increases, the complexity of the program also gets increased. This type of problem can be solved very easily using a switch statement. Using the switch statement, one can select only one option from more number of options very easily. In the switch statement, we provide a value that is to be compared with a value associated with each option. Whenever the given value matches the value associated with an option, the execution starts from that option. In the switch statement, every option is defined as a case.
The switch statement has the following syntax and execution flow diagram.

The switch statement contains one or more cases and each case has a value associated with it. At first switch statement compares the first case value with the switchValue, if it gets matched the execution starts from the first case. If it doesn't match the switch statement compares the second case value with the switchValue and if it is matched the execution starts from the second case. This process continues until it finds a match. If no case value matches with the switchValue specified in the switch statement, then a special case called default is executed.
When a case value matches with the switchValue, the execution starts from that particular case. This execution flow continues with the next case statements also. To avoid this, we use the "break" statement at the end of each case. That means the break statement is used to terminate the switch statement. However, it is optional.

Example Program | Display pressed digit in words.

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

void main(){
   int n ;
   clrscr() ;
   
   printf("Enter any digit: ") ;
   scanf("%d", &n) ;
   
   switch( n )
   {
    case 0: printf("ZERO") ; 
         break ;
    case 1: printf("ONE") ; 
         break ;
    case 2: printf("TWO") ; 
         break ;
    case 3: printf("THREE") ; 
         break ;
    case 4: printf("FOUR") ; 
         break ;
    case 5: printf("FIVE") ; 
         break ;
    case 6: printf("SIX") ; 
         break ;
    case 7: printf("SEVEN") ; 
         break ;
    case 8: printf("EIGHT") ; 
         break ;
    case 9: printf("NINE") ; 
         break ;
    default: printf("Not a Digit") ;
   }
   getch() ;
}
Output 1:
Output 2:

MOST IMPORTANT POINTS TO BE REMEMBERED
When we use switch statement, we must follow the following...

C-if-statement

'if' Statement in C


What is Decision Making Statement?

In the C programming language, the program execution flow is line by line from top to bottom. That means the c program is executed line by line from the main method. But this type of execution flow may not be suitable for all the program solutions. Sometimes, we make some decisions or we may skip the execution of one or more lines of code. Consider a situation, where we write a program to check whether a student has passed or failed in a particular subject. Here, we need to check whether the marks are greater than the pass marks or not. If marks are greater, then we decide that the student has passed otherwise failed. To solve such kind of problems in c we use the statements called decision making statements.
Decision-making statements are the statements that are used to verify a given condition and decide whether a block of statements gets executed or not based on the condition result.

In the c programming language, there are two decision-making statements they are as follows.
  1. if statement
  2. switch statement

if statement in c

In c, if statement is used to make decisions based on a condition. The if statement verifies the given condition and decides whether a block of statements are executed or not based on the condition result. In c, if statement is classified into four types as follows...
  1. Simple if statement
  2. if-else statement
  3. Nested if statement
  4. if-else-if statement (if-else ladder)

Simple if statement

Simple if statement is used to verify the given condition and executes the block of statements based on the condition result. The simple if statement evaluates specified condition. If it is TRUE, it executes the next statement or block of statements. If the condition is FALSE, it skips the execution of the next statement or block of statements. The general syntax and execution flow of the simple if statement is as follows.
Simple if statement is used when we have only one option that is executed or skipped based on a condition.

Example Program | Test whether given number is divisible by 5.

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

void main(){
   int n ;
   clrscr() ;
   printf("Enter any integer number: ") ;
   scanf("%d", &n) ;
   if ( n%5 == 0 )
      printf("Given number is divisible by 5\n") ;
   printf("statement does not belong to if!!!") ;
}
Output 1:

Output 2:

if-else statement

The if-else statement is used to verify the given condition and executes only one out of the two blocks of statements based on the condition result. The if-else statement evaluates the specified condition. If it is TRUE, it executes a block of statements (True block). If the condition is FALSE, it executes another block of statements (False block). The general syntax and execution flow of the if-else statement is as follows.
The if-else statement is used when we have two options and only one option has to be executed based on a condition result (TRUE or FALSE).

Example Program | Test whether given number is even or odd.

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

void main(){
   int n ;
   clrscr() ;
   printf("Enter any integer number: ") ;
   scanf("%d", &n) ;
   if ( n%2 == 0 )
      printf("Given number is EVEN\n") ;
   else
      printf("Given number is ODD\n") ;
}
Output 1:

Output 2:

Nested if statement

Writing a if statement inside another if statement is called nested if statement. The general syntax of the nested if statement is as follows...
The nested if statement can be defined using any combination of simple if & if-else statements.

Example Program | Test whether given number is even or odd if it is below 100.

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

void main(){
   int n ;
   clrscr() ;
   printf("Enter any integer number: ") ;
   scanf("%d", &n) ;
   if ( n < 100 )
   {
      printf("Given number is below 100\n") ;
      if( n%2 == 0)
          printf("And it is EVEN") ;
      else
          printf("And it is ODD") ;
   }
   else
       printf("Given number is not below 100") ;
}
Output 1:

Output 2:

if-else-if statement (if-else ladder)

Writing a if statement inside else of an if statement is called if-else-if statement. The general syntax of the if-else-if statement is as follows...
The if-else-if statement can be defined using any combination of simple if & if-else statements.

Example Program | Find the largest of three numbers.

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

void main(){
   int a, b, c ;
   clrscr() ;
   
   printf("Enter any three integer numbers: ") ;
   scanf("%d%d%d", &a, &b, &c) ;
   
   if( a>=b && a>=c)
        printf("%d is the largest number", a) ;
        
    else if (b>=a && b>=c)
        printf("%d is the largest number", b) ;
        
    else
        printf("%d is the largest number", c) ;
}
Output:

MOST IMPORTANT POINTS TO BE REMEMBERED
When we use a conditional control statement like if statement, the condition might be an expression evaluated to a numerical value, a variable or a direct numerical value. If the expression value or direct value is zero the condition becomes FALSE otherwise becomes TRUE.

To understand more consider the following statements.
  • if(10) - is TRUE
  • if(x) - is FALSE if x value is zero otherwise TRUE
  • if(a+b) - is FALSE if a+b value is zero otherwise TRUE
  • if(a = 99) - is TRUE because a value is non-zero
  • if(10, 5, 0) - is FALSE because it considers last value
  • if(0) - is FALSE
  • if(a=10, b=15, c=0) - is FALSE because last value is zero


C-Type-Casting-and-Conversion

Type Casting and Conversion in C


In a programming language, the expression contains data values of the same datatype or different data types. When the expression contains similar datatype values then it is evaluated without any problem. But if the expression contains two or more different datatype values then they must be converted to the single datatype of destination datatype. Here, the destination is the location where the final result of that expression is stored. For example, the multiplication of an integer data value with the float data value and storing the result into a float variable. In this case, the integer value must be converted to float value so that the final result is a float datatype value.
In a c programming language, the data conversion is performed in two different methods as follows...
  1. Type Conversion
  2. Type Casting

Type Conversion

The type conversion is the process of converting a data value from one data type to another data type automatically by the compiler. Sometimes type conversion is also called implicit type conversion. The implicit type conversion is automatically performed by the compiler.
For example, in c programming language, when we assign an integer value to a float variable the integer value automatically gets converted to float value by adding decimal value 0. And when a float value is assigned to an integer variable the float value automatically gets converted to an integer value by removing the decimal value. To understand more about type conversion observe the following...
int i = 10 ;
float x = 15.5 ;
char ch = 'A' ;

i = x ; =======> x value 15.5 is converted as 15 and assigned to variable i

x = i ; =======> Here i value 10 is converted as 10.000000 and assigned to variable x

i = ch ; =======> Here the ASCII value of A (65) is assigned to i

Example Program

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

void main(){
   int i = 95 ;
   float x = 90.99 ;
   char ch = 'A' ;
   
   i = x ;
   printf("i value is %d\n",i);
   x = i ;
   printf("x value is %f\n",x);
   i = ch ;
   printf("i value is %d\n",i);   

}
Output:

In the above program, we assign i = x, i.e., float variable value is assigned to the integer variable. Here, the compiler automatically converts the float value (90.99) into integer value (90) by removing the decimal part of the float value (90.99) and then it is assigned to variable i. Similarly, when we assign x = i, the integer value (90) gets converted to float value (90.000000) by adding zero as the decimal part.

Typecasting

Typecasting is also called an explicit type conversion. Compiler converts data from one data type to another data type implicitly. When compiler converts implicitly, there may be a data loss. In such a case, we convert the data from one data type to another data type using explicit type conversion. To perform this we use the unary cast operator. To convert data from one type to another type we specify the target data type in parenthesis as a prefix to the data value that has to be converted. The general syntax of typecasting is as follows.
(TargetDatatype) DataValue

Example

int totalMarks = 450, maxMarks = 600 ;
float average ;

average = (float) totalMarks / maxMarks * 100 ;

In the above example code, both totalMarks and maxMarks are integer data values. When we perform totalMarks / maxMarks the result is a float value, but the destination (average) datatype is a float. So we use type casting to convert totalMarks and maxMarks into float data type.

Example Program

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

void main(){
   int a, b, c ;
   float avg ;
   printf("Enter any three integer values : ") ;
   scanf("%d%d%d", &a, &b, &c) ;
   
   avg = (a + b + c) / 3 ;
   printf("avg before casting = %f\n",avg);
   
   avg = (float)(a + b + c) / 3 ;
   printf("avg after casting = %f\n",avg);
}
Output:

C-Expression-Evaluation

C Expression Evaluation


In the C programming language, an expression is evaluated based on the operator precedence and associativity. When there are multiple operators in an expression, they are evaluated according to their precedence and associativity. The operator with higher precedence is evaluated first and the operator with the least precedence is evaluated last.
An expression is evaluated based on the precedence and associativity of the operators in that expression.

To understand expression evaluation in c, let us consider the following simple example expression...
10 + 4 * 3 / 2
In the above expression, there are three operators +, * and /. Among these three operators, both multiplication and division have the same higher precedence and addition has lower precedence. So, according to the operator precedence both multiplication and division are evaluated first and then the addition is evaluated. As multiplication and division have the same precedence they are evaluated based on the associativity. Here, the associativity of multiplication and division is left to right. So, multiplication is performed first, then division and finally addition. So, the above expression is evaluated in the order of * / and +. It is evaluated as follows...
4 * 3 ====> 12
12 / 2 ===> 6
10 + 6 ===> 16
The expression is evaluated to 16.

C Operator Precedence and Associativity

What is Operator Precedence?

Operator precedence is used to determine the order of operators evaluated in an expression. In c programming language every operator has precedence (priority). When there is more than one operator in an expression the operator with higher precedence is evaluated first and the operator with the least precedence is evaluated last.

What is Operator Associativity?

Operator associativity is used to determine the order of operators with equal precedence evaluated in an expression. In the c programming language, when an expression contains multiple operators with equal precedence, we use associativity to determine the order of evaluation of those operators.
In c programming language the operator precedence and associativity are as shown in the following table.
PrecedenceOperatorOperator MeaningAssociativity
1()
[]
->
.
function call
array reference
structure member access
structure member access
Left to Right
2!
~
+
-
++
--
&
*
sizeof
(type)
negation
1's complement
Unary plus
Unary minus
increment operator
decrement operator
address of operator
pointer
returns size of a variable
type conversion
Right to Left
3*
/
%
multiplication
division
remainder
Left to Right
4+
-
addition
subtraction
Left to Right
5<<
>>
left shift
right shift
Left to Right
6<
<=
>
>=
less than
less than or equal to
greater than
greater than or equal to
Left to Right
7==
!=
equal to
not equal to
Left to Right
8&bitwise ANDLeft to Right
9^bitwise EXCLUSIVE ORLeft to Right
10|bitwise ORLeft to Right
11&&logical ANDLeft to Right
12||logical ORLeft to Right
13?:conditional operatorLeft to Right
14=
*=
/=
%=
+=
-=
&=
^=
|=
<<=
>>=
assignment
assign multiplication
assign division
assign remainder
assign addition
assign subtraction
assign bitwise AND
assign bitwise XOR
assign bitwise OR
assign left shift
assign right shift
Right to Left
15,separatorLeft to Right
In the above table, the operator precedence decreases from top to bottom and increases from bottom to top.

C-Expressions

C Expressions


What is an expression?

In any programming language, if we want to perform any calculation or to frame any condition etc., we use a set of symbols to perform the task. These set of symbols makes an expression.
In the C programming language, an expression is defined as follows.
An expression is a collection of operators and operands that represents a specific value.
In the above definition, an operator is a symbol that performs tasks like arithmetic operations, logical operations, and conditional operations, etc.
Operands are the values on which the operators perform the task. Here operand can be a direct value or variable or address of memory location.

Expression Types in C

In the C programming language, expressions are divided into THREE types. They are as follows...
  1. Infix Expression
  2. Postfix Expression
  3. Prefix Expression
The above classification is based on the operator position in the expression.

Infix Expression

The expression in which the operator is used between operands is called infix expression.
The infix expression has the following general structure.
Operand1 Operator Operand2
Example

Prefix Expression

The expression in which the operator is used before operands is called a prefix expression.
The prefix expression has the following general structure.
Operator Operand1 Operand2
Example

C-Operators

C Operators


An operator is a symbol used to perform arithmetic and logical operations in a program. That means an operator is a special symbol that tells the compiler to perform mathematical or logical operations. C programming language supports a rich set of operators that are classified as follows.
  1. Arithmetic Operators
  2. Relational Operators
  3. Logical Operators
  4. Increment & Decrement Operators
  5. Assignment Operators
  6. Bitwise Operators
  7. Conditional Operator
  8. Special Operators

Arithmetic Operators (+, -, *, /, %)


The arithmetic operators are the symbols that are used to perform basic mathematical operations like addition, subtraction, multiplication, division and percentage modulo. The following table provides information about arithmetic operators.
OperatorMeaningExample
+Addition10 + 5 = 15
-Subtraction10 - 5 = 5
*Multiplication10 * 5 = 50
/Division10 / 5 = 2
%Remainder of the Division5 % 2 = 1
 The addition operator can be used with numerical data types and character data type. When it is used with numerical values, it performs mathematical addition and when it is used with character data type values, it performs concatination (appending).

 The remainder of the division operator is used with integer data type only.

Relational Operators (<, >, <=, >=, ==, !=)


The relational operators are the symbols that are used to compare two values. That means the relational operators are used to check the relationship between two values. Every relational operator has two results TRUE or FALSE. In simple words, the relational operators are used to define conditions in a program. The following table provides information about relational operators.
OperatorMeaningExample
<Returns TRUE if the first value is smaller than second value otherwise returns FALSE10 < 5 is FALSE
>Returns TRUE if the first value is larger than second value otherwise returns FALSE10 > 5 is TRUE
<=Returns TRUE if the first value is smaller than or equal to second value otherwise returns FALSE10 <= 5 is FALSE
>=Returns TRUE if the first value is larger than or equal to second value otherwise returns FALSE10 >= 5 is TRUE
==Returns TRUE if both values are equal otherwise returns FALSE10 == 5 is FALSE
!=Returns TRUE if both values are not equal otherwise returns FALSE10 != 5 is TRUE

Logical Operators (&&, ||, !)


The logical operators are the symbols that are used to combine multiple conditions into one condition. The following table provides information about logical operators.
OperatorMeaningExample
&&Logical AND - Returns TRUE if all conditions are TRUE otherwise returns FALSE10 < 5 && 12 > 10 is FALSE
||Logical OR - Returns FALSE if all conditions are FALSE otherwise returns TRUE10 < 5 || 12 > 10 is TRUE
!Logical NOT - Returns TRUE if condition is FLASE and returns FALSE if it is TRUE!(10 < 5 && 12 > 10) is TRUE
⇒ Logical AND - Returns TRUE only if all conditions are TRUE, if any of the conditions is FALSE then complete condition becomes FALSE.
⇒ Logical OR - Returns FALSE only if all conditions are FALSE, if any of the conditions is TRUE then complete condition becomes TRUE.

Increment & Decrement Operators (++ & --)


The increment and decrement operators are called unary operators because both need only one operand. The increment operators adds one to the existing value of the operand and the decrement operator subtracts one from the existing value of the operand. The following table provides information about increment and decrement operators.
OperatorMeaningExample
++Increment - Adds one to existing valueint a = 5;
a++; ⇒ a = 6
--Decrement - Subtracts one from existing valueint a = 5;
a--; ⇒ a = 4
The increment and decrement operators are used infront of the operand (++a) or after the operand (a++). If it is used infront of the operand, we call it as pre-increment or pre-decrement and if it is used after the operand, we call it as post-increment or post-decrement.

Pre-Increment or Pre-Decrement

In the case of pre-increment, the value of the variable is increased by one before the expression evaluation. In the case of pre-decrement, the value of the variable is decreased by one before the expression evaluation. That means, when we use pre-increment or pre-decrement, first the value of the variable is incremented or decremented by one, then the modified value is used in the expression evaluation.

Example Program

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

void main(){
   int i = 5,j;
   
   j = ++i; // Pre-Increment
   
   printf("i = %d, j = %d",i,j);   

}
Output:

Post-Increment or Post-Decrement

In the case of post-increment, the value of the variable is increased by one after the expression evaluation. In the case of post-decrement, the value of the variable is decreased by one after the expression evaluation. That means, when we use post-increment or post-decrement, first the expression is evaluated with existing value, then the value of the variable is incremented or decremented by one.

Example Program

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

void main(){
   int i = 5,j;
   
   j = i++;  // Post-Increment
   
   printf("i = %d, j = %d",i,j);   

}
Output:

Assignment Operators (=, +=, -=, *=, /=, %=)


The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand side variable (Lvalue). The assignment operator is used in different variants along with arithmetic operators. The following table describes all the assignment operators in the C programming language.
OperatorMeaningExample
=Assign the right-hand side value to left-hand side variable    A = 15
+=Add both left and right-hand side values and store the result into left-hand side variable    A += 10
⇒ A = A+10
-=Subtract right-hand side value from left-hand side variable value and store the result
into left-hand side variable
    A -= B
⇒ A = A-B
*=Multiply right-hand side value with left-hand side variable value and store the result
into left-hand side variable
    A *= B
⇒ A = A*B
/=Divide left-hand side variable value with right-hand side variable value and store the result
into the left-hand side variable
    A /= B
⇒ A = A/B
%=Divide left-hand side variable value with right-hand side variable value and store the remainder
into the left-hand side variable
    A %= B
⇒ A = A%B

Bitwise Operators (&, |, ^, ~, >>, <<)


The bitwise operators are used to perform bit-level operations in the c programming language. When we use the bitwise operators, the operations are performed based on the binary values. The following table describes all the bitwise operators in the C programming language.
Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).
OperatorMeaningExample
&the result of Bitwise AND is 1 if all the bits are 1 otherwise it is 0    A & B
⇒ 16 (10000)
|the result of Bitwise OR is 0 if all the bits are 0 otherwise it is 1    A | B
⇒ 29 (11101)
^the result of Bitwise XOR is 0 if all the bits are same otherwise it is 1    A ^ B
⇒ 13 (01101)
~the result of Bitwise once complement is negation of the bit (Flipping)    ~A
⇒ 6 (00110)
<<the Bitwise left shift operator shifts all the bits to the left by the specified number of positions    A << 2
⇒ 100 (1100100)
>>the Bitwise right shift operator shifts all the bits to the right by the specified number of positions    A >> 2
⇒ 6 (00110)

Conditional Operator (?:)


The conditional operator is also called a ternary operator because it requires three operands. This operator is used for decision making. In this operator, first we verify a condition, then we perform one operation out of the two operations based on the condition result. If the condition is TRUE the first option is performed, if the condition is FALSE the second option is performed. The conditional operator is used with the following syntax.

Condition ? TRUE Part : FALSE Part;

Example

A = (10<15)?100:200; ⇒ A value is 100

Special Operators (sizeof, pointer, comma, dot, etc.)


The following are the special operators in c programming language.

sizeof operator

This operator is used to find the size of the memory (in bytes) allocated for a variable. This operator is used with the following syntax.

sizeof(variableName);

Example

sizeof(A); ⇒ the result is 2 if A is an integer

Pointer operator (*)

This operator is used to define pointer variables in c programming language.

Comma operator (,)

This operator is used to separate variables while they are declaring, separate the expressions in function calls, etc.

Dot operator (.)

This operator is used to access members of structure or union.