C else if statement

Created By: chatGPT

In C, the else if statement is used to test multiple conditions. This allows you to execute different blocks of code based on varying conditions. The else if statement is a more efficient way to handle multiple conditions than using multiple if statements. You can combine if, else if, and else to create a branching structure. Here's the syntax for using else if:
if (condition1) {
    // Code block for condition1
} else if (condition2) {
    // Code block for condition2
} else {
    // Code block if none of the above conditions are true
}
Let's consider an example where we evaluate a student's grade based on their score. If the score is greater than or equal to 90, the student receives an 'A'. If the score is between 80 and 89, the student receives a 'B'. If the score is between 70 and 79, the student receives a 'C'. If the score is less than 70, the student receives a 'F'. Here's how you can implement this logic using an else if statement:
#include <stdio.h>

int main() {
    int score;
    printf("Enter the score: ");
    scanf("%d", &score);

    if (score >= 90) {
        printf("Grade: A\n");
    } else if (score >= 80) {
        printf("Grade: B\n");
    } else if (score >= 70) {
        printf("Grade: C\n");
    } else {
        printf("Grade: F\n");
    }

    return 0;
}

In this code:

  • We include the stdio.h header to use input-output functions.
  • We declare an integer variable called score to store the user's input.
  • We use printf to prompt the user to enter their score.
  • scanf reads the score value from the user.
  • We then use an if...else if...else structure to determine and print the corresponding grade based on the input score.

This implementation ensures that only one grade is printed, depending on the score entered by the user.

Introduction And SetupVariablesData TypesIntFloatDoubleCharVoidUnsignedSignedConstantsEnumerationsArraysStringsStructsUnionsTypedefsPointersDynamic Memory AllocationMallocCallocReallocFreeFunctionsFunction DeclarationsFunction DefinitionsFunction CallsReturn StatementInline FunctionsRecursionHeader FilesPreprocessor DirectivesControl FlowIf StatementElse StatementElse If StatementSwitch StatementCase StatementDefault CaseLoopsFor LoopWhile LoopDo While LoopBreak StatementContinue StatementGoto StatementLabelsOperatorsArithmetic OperatorsRelational OperatorsLogical OperatorsBitwise OperatorsAssignment OperatorsConditional (ternary) OperatorComma OperatorSizeof OperatorData StructuresLinked ListsStacksQueuesTreesGraphsFunction PointersCallbacksMacrosCommentsSingle Line CommentsMulti Line CommentsSyntaxSyntax ErrorsCompilation ErrorsDebuggingStandard Input OutputPrintfScanfFile HandlingFopenFcloseFreadFwriteFprintfFgetsFputsError HandlingErrnoAssertionsExit FunctionExit CodesEvent HandlingSignal HandlingInterrupts