-->

Monday, February 16, 2015

Conditional If-Else Statement with Example in c language

To overcome the disadvantage of if statement, in computer programming the if-else statement is introduced. It is a two way decision statement which executes either first statement (or block of statements) or second statement (or block of statements) based on the condition.

For the true part if takes care and for the false part else takes care. The syntax of if-else statement along with equivalent flow chart is shown below:

if (condition)
 statement 1 or (block of statement 1)
else
 statement 2 or (block of statement 2)
Conditional If-Else Statement with Example: Turbo C

According to Flowchart, compiler will first check the condition. If the condition is true, the right side of statement(s) will execute otherwise left side of statement(s) will execute. For example 

Program to check whether the number is even or odd: Let num is the given number. After dividing num by 2, if the remainder is zero, then the given number num is even otherwise, given number num is odd. The equivalent statement can be written as:

if (num%2==0)
    Write: “Number is Even”
else
    Write: “Number is odd”
[End of if]

Algorithm:

Step 1: [Read the number to check]
              Read: NUM
Step 2: [Check the number]
              if(NUM%2==0)
                    Write: ‘Number is Even’
              else
           Write: ‘Number is Odd;
    End of if
Step 3:  Exit

The C program to perform the algorithm:

main()
{
   int num;
   printf(“Enter an integer number here:”);
   scanf(“%d”,&num);
   if(num%2==0)
      printf(“The number num %d is EVEN”,num);
   else
      printf(“The number num %d is ODD”,num);
   getch();
}

Nested-If statement

Branching Statements in Turbo C Language

In sequential statements, we know that all the statements are executed in the order specified in the program one after one. However, computer can skip execution of some statements those statements will not be execute by the compiler. This skipping feature is provided by the a set of instructions called skip instructions. These skip instructions are further called Branching Statements in technical words.

In other words the statements that alter/change the sequence of execution of the instructions, written in a program, are called branching statements. These statements or skip instructions have its own types. I will describe types of branching statement in brief:

Conditional Statements

The written instructions can be skipped based on a condition specified by the programmer. The branching statements that alter the sequence of execution of the program based on some condition are called conditional branching statements. They can also be called Selection Statements or Decision Statements.
For example, if, if-else, else-if ladder and switch statement.

Non Conditional Statements

Sometimes, user wants to transfer the control from one point to another point during execution without any condition. These type of branching statements that transfer the control from one point to another point in a program without any condition are called unconditional branching statement or unconditional control statements.
For example, goto, break, return and continue. We will understand all these statements with example.

If Condition

If or If statement is a simple selection or decision statement. When a set of statements have to be executed or skipped according to the given condition, this statement is used. Here's the syntax and flowchart of this statement:

If (Condition)
statement;
rest of code;
If flowchart in Branching Statements: Turbo C Language

According to Flowchart, compiler will first check the condition. If the condition is true, the block of statements will execute otherwise rest of code will execute. For example
if(num%2==0)
Write: ‘Even Number’
End if

Here, "Even Number" is displayed only if the condition is true. Now, let us write some simple programs that shows the application where if-statement can be used.

Program to check whether the given number is even or not.
Process: Let num is the given number. After dividing num by 2, if the remainder is equals to zero, then num will be even number. So, the equivalent algorithm and C language code is written here.

Algorithm:
Step 1: [Read the number to check]
              Read: NUM
Step 2: [Check the number]
            if(NUM%2==0)
                    Write: ‘Number is Even’
            End of if
Step 3: Exit

The C program to perform the algorithm
main()
{
   int num;
   printf(“Enter an integer number here:”);
   scanf(“%d”,&num);
   if(num%2==0)
   printf(“The number num %d is EVEN”,num);
   getch();
}

Advantage

If statement is one way decision statement. The if statement is used when a set of statements have to be executed or skipped based on one condition. That is only when the condition is true or false.

Disadvantage

If we have two statements to be executed, one on true and another on false, then if statement is not recommended. This disadvantage can be overcome using two way decision statement i.e. if-else statement.

Features of Bottom-up technique in C language


  • Program preparation starts from designing the sub-problems.
  • The solutions are clubbed in the main coordinating module.
  • The composition of solutions is generalized for main solution.
  • Program is structured as hierarchy of various tasks but viewed from bottom to upper level.
  • As the technique moves from bottom to top it is a type of generalization.
  • Main module can only be designed after the detailed design of sub-problems.
  • The tested sub-programs are used to frame the main solution.
  • Integration test is performed at the final stage of programming.
  • The code of the sub-problems are reusable.
  • The modules linking details is not available at the lower stage of programming.
  • This type of programming technique is most popular in Object Oriented Programming using C++ and Java.

If-Else-If Ladder Statement in Computer Programming: C Language

When series of actions have to be performed based on decisions one–by-one, then the statement used is called if-else-if ladder. In computer programming it is called multi-way decision statement. The if-else-if ladder is a form of nested if-statement. Here, nesting is allowed only in the else part. The orderly nesting of if statement only in the else part is called if-else-if ladder. The syntax of if-else-if ladder is shown below:

SQL Video Channel : Download all SQL Video

Syntax:

if(condition1)
    statement(s);
      else if(condition2)
    statement(s);
else if(condition3)
    statement(s);
-
-
-
    else if(conditionn)
    statement(s);
                               else
                                  statement(S);

In this statement the conditions condition1, condition2 etc. of if-else-if ladder are evaluated to true, the corresponding statement is executed and control comes out of the entire if-else-if ladder executing the rest statements that come after the if-else-if ladder.

If all the conditions are evaluated to false, then the last statement is executed, and the control comes out of if-else-if ladder and the rest statements that come after the if-else-if ladder are executed.

Problem:

Let consider a problem to display the grade obtained by a student based on the marks. The criteria to find the grade based on marks as follows:
    Marks        Grade
    0 to 34        F
    35 to 44      E
    45 to 59      D
    60 to 69      C
    70 to 79      B
    80 to 89      A
    90 to 100    A+

Algorithm:
Step1:    Read: Marks
Step2:    if(Marks<=34)
        Write: ‘Grade F’
    else if(Marks<=45)
        Write: ‘Grade E’
    else if(Marks<=59)
        Write: ‘Grade D’
else if(Marks<=69)
        Write: ‘Grade C’
else if(Marks<=79)
        Write: ‘Grade B’
else if(Marks<=89)
        Write: ‘Grade A’
else
Write: ‘Grade A+’
[End of if-else-if]
Step3:    Exit

Here's the C program to solve the above problem.

main()
{
  int marks;
  clrscr();
  printf(“Enter the student’s obtained marks here:\n”);
  scanf(“%d”,&marks);
  if(marks<=34)
     printf(“Grade F”);
  else if(marks<=45)
     printf(“Grade E”);
else if(marks<=59)
     printf(“Grade D”);
else if(marks<=69)
     printf(“Grade C”);
else if(marks<=79)
     printf(“Grade B”);
else if(marks<=89)
     printf(“Grade A”);
else
     printf(“Grade A+”);
getch();
}

Output
If-Else-If Ladder Statement in Computer Programming: C Language

Advantages:

In computer programming, situations involving series of decisions one after the other, each decision or condition may involve expression of various data types such as float, integer, char and double. In these situations the if-else-if ladder is used.

Disadvantages:

  • The nested ifs are hard to understand and modify.
  • As the depth of nesting increases, the readability of the program decreases.
  • In situations involving series of decisions one after the other, each decision or condition may involve expressions which result in integer value. In these situations the usage of if-else-if ladder is not recommended. Instead of this statement, we go for switch statement.

Get to Know about Decision Making and branching Statements in Detail: C Language

INTRODUCTION:

A statement (also known as instruction) is the smallest element of any programming language. A statement or instruction is used to inform the computer to perform an action, when a program is executed. A statement can be used to set values of variables, alter the values of a variables, accept the input, manipulate the data and display the data. Each statement in C language must be terminated by a semicolon “;”.

The expression such as “a + b”, “c = 20”, “printf()” may become statements when they are terminated by a semicolon as shown below:


a + b;                 /* statement 1 */
c = 20;                /* statement 2 */
printf();            /* statement 3 */
 

A statement can be simple statement (discussed above) or can be compound statement. The set of statements enclosed within a pair of curly braces such as “{“and “}” is considered as a compound statement. For example, the following compound statement computes and display the sum of two values.
{
  Num1 = 15;                                   
  Num2 = 35;                                   
  Sum = Num1 + Num2;                           
  printf(“The sum of Num1 %d and Num2 %d = %d”,Num1,Num2,Sum);   
}
This compound statement can be treated as a single statement. Note that in a compound statement ‘}’ must not end with semicolon. So, all the operations like arithmetic, assignment, control structures and input/output function calls are considered as statements. Now, let us see “What are control statements? What are the types of the control statements?”

Sequential Statements with FlowChart and Example

Saturday, February 14, 2015

Uses of Sequential and Compound Statements: C programming

INTRODUCTION

In our previous article, we have studied about the single statements. The order in which statements are executed known as control flow and the statements that are used to control the flow of execution of the program are called as control statements. Based on the order in which the statements are executed, the various control statements are classified as follows:
         
Uses of Sequential and Compound Statements: C Language

Now, let us consider each of the control statements one by one.

Sequential Statements

The programmer writes a sequence of statements to specify some activity in a program. All these statements in a program are executed in the order in which they appear in the program. These programming statements that are executed sequentially, i.e. one after one is known as the sequential statements. Here, no separate statements are required to make these statements executed in sequence. The flow chart and the equivalent programming statements are shown below:

Uses of Sequential and Compound Statements: C Language

Here, statement 1 is executed first followed by statement 2 followed by statement 3 and so on. In short, we can say that execution of program is normally sequential (one after one). For example, let us write a program to find the sum of two integer numbers, which is given by the following relation:

Sum = Num1 + Num2

The sequence of steps to be followed as:
•    Input two integer numbers
•    Compute the sum using Sum = Num1 + Num2
•    Display the result
•    Stop the execution

The equivalent algorithm and the flow chart for the same are shown below:

Example 1:    Algorithm and flow chart to compute the sum of two integer numbers.
Algorithms:    ADD
    [Compute the sum of two integer numbers.]
    Step 1: [Input any two integer numbers]
        Read: Num1, Num2
    Step2: [Compute the sum]
        Sum = Num1 + Num2
    Step3: [Display the result]
        Write: Sum
    Step4: [Stop]
        Exit
Uses of Sequential and Compound Statements: C Language

Example2:
main()
{
 int Num1, Num2, Sum;
 clrscr();
 printf(“Enter any two integer numbers\n”);
 scanf(“%d%d”,&Num1.&Num2);
 /* compute the sum*/
 Sum = Num1 + Num2;
 Printf(“Sum = %d”,Sum);
 getch();
}

Output:
Uses of Sequential and Compound Statements: C Language

Advantage

No other separate control statement is required to execute the sequential statements one after one.

Disadvantage:

The sequence in which statements are executed cannot be altered or changed.

Friday, February 13, 2015

Formatted input/output function in Turbo C Language

It is very easy to use unformatted input/output functions as discussed. We can read and display only characters not numbers using unformatted functions. Using formatted input/output functions, we can read integers, floating point number and characters. The formatted input function is scanf() and formatted output functions is printf().

Scanf()

Syntax
int scanf(“format string”, &var1, &var2, &var3,……..&varn);

This function scanf() is used to read any type of data such as int, char, float, double and even string from the keyboard. It accepts the following two parameters:
format string consists of one or more format specifires starts with % symbol.
&var1, &var2, &var3, …., &varn represents the list of variables. Here, symbol ‘&’ refers to the address of the variable. In the memory locations identified by these addresses, the respective values are stored.

Formatted input/output function in Turbo C Language


Return Type int: The function returns an integer value. This integer value is the number of item that have been read successfully using the keyboard. But, we rarely use this return value in our programs.
The various format specifiers along with the associated meaning are shown in the following table:

Data Type
Format Specifier
Meaning
int
%d
%o
%x
%i
%u
%h
Read a decimal integer value
Read an octal value
Read a hexadecimal value
Read a decimal, octal or hexadecimal value
Read an unsigned integer value
Read a short integer value
float
%e
%f
%g
Read a floating point number
Read a floating point number
Read a floating point number
char
%c
%s
Read a character
Read a string (series of character)
double
%f
Read a long floating point number or double
long int
%ld
Read a long integer value

The following table shows the way the user has to enter the values from the keyboard:

Input statement
Entering value
Input way
scanf(“%d%d%d”,&a,&b,&c);
3 integer value
10 20 30
Where, a=10      b=20       c=30
scanf(“%d,%d,%d”,&a,&b,&c);
3 integer value
10,20,30
Where, a=10      b=20       c=30
scanf(“%f”,&a);
1 floating point value
787.35
Where, a=787.3.5
scanf(“%c”,&a);
1 character value
P
Where, a=p
scanf(“%f,%d,%c”,&a,&b,&c);
1 floating point value
1 integer value
1 character value
787.35 10 P
Where, a=787.35, b=10, c=P
scanf(“%d-%d-%d”,&a,&b,&c);
3 integer values separated by ‘-‘ (hyphen) sign
10-20-30
Where, a=10, b=20, c=30
scanf(“%d%d%d”,&a,&b,&c);
3 integer values separated by ‘/’ (slash) symbol
10/20/30
Where, a=10, b=20, c=30

Note: Do not use any escape sequences such as \t, \n etc. in scanf().

For example: Consider the following statement:
scanf(“%d\n”,&a);
In the above statement, remove ‘\n’, otherwise it may give wrong output.
Now, let us see, some more ways of data reading using scanf() function are given below:
Input statement
Entering value
Input way
scanf(“%2d%2d%2d”,&a,&b,&c);
3 integer values
1 2 3
Where, a=1  b=2  c=3
11 22 33
Where, a=11  b=22  c=33
102030
Where, a=10  b=20  c=30
102 030 4
Where, a=10  b=2  c=3
The remaining two digits 0 and 4 are ignored or can be read by a subsequent scanf()
scanf(“%12s”,&str);
1 string
.Programming
Where, str=.Programming
scanf(“%[^\n]s”,str);
Input the string till the end of line
Wlecome! To the dotprogramming
Where, str= Wlecome! To the dotprogramming
Note:
To read a string with space gets() function will used in place of scanf().
The “scanf(“%[^\n]s”,str);” function read and stored all the character untill user will not press enter key.

Formatted Output Function
© Copyright 2013 Computer Programming | All Right Reserved