Computer Science

if else in C

The "if else" statement in C is a conditional statement that allows for the execution of different code blocks based on a specified condition. If the condition is true, the code within the "if" block is executed; otherwise, the code within the "else" block is executed. This provides a way to create branching logic in a program based on different conditions.

Written by Perlego with AI-assistance

6 Key excerpts on "if else in C"

  • ANSI C Programming
    eBook - ePub

    ANSI C Programming

    Learn ANSI C step by step

    4 The Decision Control Structure Decisions! Decisions! The if Statement The Real Thing Multiple Statements within if The if-else Statement Nested if-elses Forms of if Use of Logical Operators The else if Clause The ! Operator Hierarchy of Operators Revisited A Word of Caution The Conditional Operators Summary Exercise W e all need to alter our actions in the face of changing circumstances. If the weather is fine, then I will go for a stroll. If the highway is busy, I would take a diversion. If the pitch takes spin, we would win the match. If she says no, I would look elsewhere. If you like this book, I would write the next edition. You can notice that all these decisions depend on some condition being met. C language too must be able to perform different sets of actions depending on the circumstances. In fact, this is what makes it worth its salt. C has three major decision making instructions—the if statement, the if-else statement, and the switch statement. A fourth, somewhat less important structure is the one that uses conditional operators. In this chapter, we will explore all these ways (except switch, which has a separate chapter devoted to it, later) in which a C program can react to changing circumstances. Decisions! Decisions! In the programs written in Chapter 1, we have used sequence control structure in which the various steps are executed sequentially, i.e. in the same order in which they appear in the program. In fact, to execute the instructions sequentially, we don’t have to do anything at all. By default, the instructions in a program are executed sequentially. However, in serious programming situations, seldom do we want the instructions to be executed sequentially. Many a time, we want a set of instructions to be executed in one situation, and an entirely different set of instructions to be executed in another situation. This kind of situation is dealt with in C programs using a decision control instruction
  • Learn C Programming from Scratch
    eBook - ePub

    Learn C Programming from Scratch

    A step-by-step methodology with problem solving approach (English Edition)

    There are instances when a programmer needs to execute a set of instructions based on certain conditions. For example, executing instructions only if a specific condition is met, such as determining if an input number is even. Similarly, there are cases where a programmer wants to execute a set of instructions continuously until a certain state is reached or a condition is fulfilled. Additionally, there may be situations where it is necessary to skip a set of statements and proceed to a different set of instructions. In such scenarios, the flow of execution may not follow a strict sequential order. For instance, instruction 5 might be followed by instruction 9, or instructions 10, 11, and 12 could be executed multiple times. Furthermore, it may be necessary to skip instructions 21, 22, and 23 and proceed directly to the subsequent instructions.
    These scenarios are enabled by the presence of control statements in our program. Let us try to have an idea of them, then try our hand at some associated examples. Refer to the Figure 3.1 :
    Figure 3.1: Condition based logic
    There are four basic control statements in C:
    • Conditional (decision-making) statements
    • Switch statements
    • Loop statements
    • Jump statements (Go To)
    Decision making statements
    For decision-making, programmers must define constructs that will be assessed or tested by the program, along with statements to be performed if the condition is true and, optionally, some statements that will be run if the condition is false.
    The following is the general form of a typical decision-making structure found in most of the programming languages: C programming language assumes any non-zero and non-null values as true; if it is either zero or null, it is assumed as false. It also provides the following types of decision-making statements: if statement
    The if statement executes a block of code if a condition is true. The if construct consists of a Boolean expression followed by a block of statements to be executed if the condition evaluates to TRUE .
    Syntax:
    if (condition) {
    Set of instructions to be executed
    } For example: a=10; b=20; if (a>b) { printf("a is greater"); }
    An if statement controls the execution of instructions based on the results of a Boolean expression. if statement starts with an if clause, followed by a condition and a BLOCK of instructions. An if clause may also be followed by (an optional) else clause (or one or more else-if '
  • 'C' Programming in an Open Source Paradigm
    • K. S. Oza, S. R. Patil, R. K. Kamat(Authors)
    • 2022(Publication Date)
    • River Publishers
      (Publisher)
    C language has three branching statements: if statement, if-else statement, and switch statement. These statements control the behavior of a program. Each branch consists of set of instructions to be executed depending upon some condition. If that condition evaluates to true, then the corresponding block of statements get executed. The “if statement” is the simplest form. It takes an expression in parenthesis, and if the expression evaluates to true, then the statement/statements get executed; otherwise, they are skipped.

    2.2 The if Statement

    The if statement is used to make one time decision. Here either the statement is true or false, like binary decision. General form:
    if (condition is true)
        execute statement;
    where if is a keyword:    condition—expression using C’s relational operator    statement—block of code to be executed. The block of code is executed if and only if the condition is true; otherwise, compiler skips it.

    2.3 The if-else Statement

    The if statement facilitates execution of block of code if condition is true; otherwise, it does nothing. The if-else statement provides a way to execute a set of instructions if condition is true or false.
    General form:
    if (condition is true)
           execute statement;
    else
           execute statement;  // if condition is false
    Here, else part will execute if condition will evaluate to false.
    Program 2.1 Use of if-else statement to predict leap year Leap year comes once in four years. It has 29 days in February. User is asked to enter the year, which is then divided by 4; and if the remainder is zero, then the year is leap year, else not.
  • C Programming For Dummies
    • Dan Gookin(Author)
    • 2020(Publication Date)
    • For Dummies
      (Publisher)
    Hint: The best solution changes only one line of code.)

    Adding a third option

    Not every decision made in a program is either-or. Sometimes, you find yourself in need of an either-or-or-and-then type of thing. No word exists in English to describe such a structure, but it exists in C. It looks like this:
    if(expression ){ statement (s );}else if(expression ){ statement (s );}else{ statement(s);}
    When the first expression proves false, the else if statement makes another test. If that expression proves true, its statements are executed. When neither condition is true, the statements belonging to the final else are executed.
    Exercise 8-13: Using the source code from Listing 8-2 as a base, create an if-if else-else structure that handles three conditions. The first two conditions are specified in Listing 8-2 , and you need to add the final possibility using a structure similar to the one shown in this section.
    C has no limit on how many else if statements you can add to an if decision process. Your code could show an if , followed by three else-if conditions, and a final else . This process works, though it may not be the best approach. See the later section “Making a multiple-choice selection ,” for a better way.

    Multiple Comparisons with Logic

    Some comparisons are more complex than those presented by the simple operators illustrated earlier, in Table 8-1 . For example, consider the following math-thingie:
    -5 <= x <= 5
    In English, this statement means that x represents a value between –5 and 5, inclusive. That's not a C language if comparison, but it can be, when you employ logical operators.

    Building a logical comparison

    It’s possible to load two or more comparisons into a single if statement. The results are then compared by using a logical operator. When the entire thing is true, the if condition is considered true, as shown in Listing 8-7
  • Clean ABAP
    eBook - ePub

    Clean ABAP

    A Style Guide for Developers

    • Klaus Haeuptle, Florian Hoffmann, Rodrigo Jordão, Michel Martin, Anagha Ravinarayan, Kai Westerholz(Authors)
    • 2020(Publication Date)
    • SAP PRESS
      (Publisher)
    CASE statements is an indicator that your code needs refactoring.
    Finally, in Section 8.5 , we’ll explain the reasoning behind the usage of pseudo loops, which are executed exactly one time, and describe why pseudo loops should be avoided or, if already used, should be refactored to clean up the code.

    8.1    IFs

    One of the most basic parts of a programming language is the ability to execute code only if a certain condition is met. As in many other languages, the keyword IF is followed by a condition. If the condition is true, the code that follows the IF is executed until an ELSE or ENDIF statement or an explicit earlier exit of the branch is reached. The statement itself does not make the code complex to understand; the usage of the statement is what adds complexity.
    In this section, we’ll discuss IF branches and how to keep your IF statements understandable.

    8.1.1    IF Branches

    In its most basic form, an IF statement has two branches: one that is executed if the condition is true and one branch executed if the condition is false. However, this construct can be reduced further. If no action is specified to respond in a case where the condition is false, an empty ELSE branch does not add value to the code, and therefore, an empty ELSE branch should be deleted. Some conditions are constructed in such a way that the executed code is written only in the ELSE branch, and the IF branch is empty. The general rule that only branches should be introduced that have coding in them also applies. For this example, the condition should be changed so that the coding can be relocated into the actual IF branch and the ELSE
  • C
    eBook - ePub

    C

    From Theory to Practice, Second Edition

    • George S. Tselikis, Nikolaos D. Tselikas(Authors)
    • 2017(Publication Date)
    • CRC Press
      (Publisher)
    5 Program Control
    Up to this point, we have seen that program’s statements are executed from top to bottom, in the order that they appear inside the source code. However, in real programming, certain statements should be executed only if specific conditions are met. This chapter will teach you how to use the
    if
    and
    switch
    selection statements to control the flow of your program and make it select a particular execution path from a set of alternatives. It also introduces the conditional operator ?: , which can be used to form conditional expressions.

    The if Statement

    The
    if
    statement controls program flow based on whether a condition evaluates to true or false. The simplest form of the
    if
    statement is:
    if (condition) { ... /* block of statements */ }
    If the value of the condition is true, the block of statements between the braces will be executed. For example:
    int x = 3; if (x != 0) { printf("Yes\n"); }
    Since x is not 0 , the
    if
    condition is true and the program displays Yes .
    if (x)
    is equivalent to
    if (x != 0)
    If the value of the condition is false, the block of statements won’t be executed. For example, the following code displays nothing:
    int x = -3; if (x == 0) { printf("Yes\n"); }
    if (!x)
    is equivalent to
    if (x == 0)
    The position of the braces, not only in case of
    if
    , but also in the loop statements of Chapter 6 , is a matter of personal preference. For example, many programmers prefer the K&R style:
    if (x == 0){ printf("Yes\n"); }
    The reason we don’t prefer this style is because the left brace is not clearly shown. Our preference is to put each brace in a separate line, so that we can easily check that they match. You may choose the style you like more. However, the common practice, and this is what we strongly recommend, is to indent the inner statements in order to make clearer their grouping and the code easier to read. We use the same style for the loop statements in Chapter 6
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.