Betingede sætninger i C: If, Else, Nested If med eksempel

⚡ Smart opsummering

Conditional statements in C control the flow of a program by executing blocks of code only when a tested condition evaluates to true, enabling decision making through if, if-else, nested, and else-if ladder constructs.

  • 🔤 Hvis-sætning: An if statement runs its block only when the condition is a non-zero true value, while zero means false.
  • 🔀 If-else: The if-else construct adds a false branch, running one block when the condition is true and another when it is false.
  • ⚖️ Relationelle operatører: Six operators (<, <=, >, >=, ==, !=) build the Boolean expressions that every condition tests.
  • 🪜 Else-if ladder: A nested else-if ladder checks several expressions top to bottom and runs the first true branch, or a default else.
  • Ternær operator: The ?: conditional expression writes a compact if-else that returns one of two values in a single line.
  • 🤖 AI assistance: GitHub Copilot drafts and reviews if-else logic, flags missing braces, and suggests cleaner conditions.

C Conditional Statement: IF, IF Else and Nested IF Else

Hvad er en betinget erklæring i C?

Conditional Statements in C programming are used to make decisions based on the conditions. Conditional statements execute sequentially when there is no condition around the statements. If you put some condition for a block of statements, the execution flow may change based on the result evaluated by the condition. This process is called decision making in ‘C.’

I modsætning til loops in C that repeat code, conditional statements pick one path.

I 'C'-programmering er betingede udsagn mulige ved hjælp af følgende to konstruktioner:

  1. Hvis udsagn
  2. If-else-sætning

Det kaldes også forgrening, da et program bestemmer, hvilken sætning der skal udføres baseret på resultatet af den evaluerede tilstand.

Hvis udsagn

Det er en af ​​de stærke betingede erklæringer. If-sætningen er ansvarlig for at ændre strømmen af ​​eksekvering af et program. Hvis sætning bruges altid med en betingelse. Betingelsen evalueres først, før der udføres en erklæring inde i brødteksten af ​​If. Syntaksen for if-sætning er som følger:

 if (condition) 
     instruction;

Betingelsen evalueres til enten sand eller falsk. Sand er altid en værdi, der ikke er nul, og falsk er en værdi, der indeholder nul. Instruktioner kan være en enkelt instruktion eller en kodeblok omgivet af krøllede klammeparenteser { }.

Følgende program illustrerer brugen af ​​if-konstruktion i 'C'-programmering:

#include<stdio.h>
int main()
{
	int num1=1;
	int num2=2;
	if(num1<num2)		//test-condition
	{
		printf("num1 is smaller than num2");
	}
	return 0;
}

Output:

num1 is smaller than num2

Ovenstående program illustrerer brugen af ​​if-konstruktion til at kontrollere lighed mellem to tal.

If Statement flowchart in C

  1. I ovenstående program har vi initialiseret to variable med henholdsvis num1, num2 med værdien 1, 2.
  2. Derefter har vi brugt if med et testudtryk til at kontrollere, hvilket tal der er det mindste, og hvilket tal der er det største. Vi har brugt et relationelt udtryk i if-konstruktion. Da værdien af ​​num1 er mindre end num2, vil betingelsen evalueres til sand.
  3. Således vil den udskrive erklæringen inde i blokken af ​​If. Herefter vil styringen gå uden for blokken, og programmet vil blive afsluttet med et vellykket resultat.

Relationel Operatorer

C has six relational operators that can be used to formulate a Boolean expression for making a decision and testing conditions, which returns true or false:

  • < — less than
  • <= — less than or equal to
  • > — greater than
  • >= — greater than or equal to
  • == — equal to
  • != — not equal to

Bemærk, at den lige test (==) er forskellig fra opgaveoperatøren (=), fordi det er et af de mest almindelige problemer, som en programmør står over for ved at blande dem.

For eksempel:

int x = 41;
x =x+ 1;
if (x == 42) {
   printf("You succeed!");}

Output:

 You succeed

Husk, at en betingelse, der evalueres til en værdi, der ikke er nul, betragtes som sand.

For eksempel:

int present = 1;
if (present)
  printf("There is someone present in the classroom \n");

Output:

There is someone present in the classroom

If-Else-erklæringen

C If-Else Statement flowchart

The if-else statement is an extended version of If. The general form of if-else is as follows:

if (test-expression)
{
    True block of statements
}
Else
{
    False block of statements
}
Statements;

In this type of a construct, if the value of test-expression is true, then the true block of statements will be executed. If the value of test-expression is false, then the false block of statements will be executed. In any case, after the execution, the control will be automatically transferred to the statements appearing outside the block of If.

Følgende programmer illustrerer brugen af ​​if-else konstruktionen:

Vi vil initialisere en variabel med en vis værdi og skrive et program for at bestemme, om værdien er mindre end ti eller større end ti.

Lad os begynde.

#include<stdio.h>
int main()
{
	int num=19;
	if(num<10)
	{
		printf("The value is less than 10");
	}
	else
	{
		printf("The value is greater than 10");
	}
	return 0;
}

Output:

The value is greater than 10

If-Else statement example output in C

  1. Vi har initialiseret en variabel med værdien 19. Vi skal finde ud af, om tallet er større eller mindre end 10 ved hjælp af et 'C'-program. For at gøre dette har vi brugt if-else-konstruktionen.
  2. Her har vi givet en betingelse num<10, fordi vi skal sammenligne vores værdi med 10.
  3. Som du kan se, er den første blok altid en sand blok, hvilket betyder, at hvis værdien af ​​test-udtryk er sand, vil den første blok, som er If, blive udført.
  4. Den anden blok er en anden blok. Denne blok indeholder de sætninger, som vil blive udført, hvis værdien af ​​test-udtrykket bliver falsk. I vores program er værdien af ​​num større end ti, derfor bliver testbetingelsen falsk, og ellers udføres blokeringen. Således vil vores output være fra en anden blok, som er "Værdien er større end 10". Efter if-else vil programmet afsluttes med et vellykket resultat.

I 'C'-programmering kan vi bruge flere if-else-konstruktioner inden i hinanden, som omtales som nesting of if-else-sætninger.

Betingede udtryk

Another way to express an if-else statement is by introducing the ?: operator. In a conditional expression the ?: operator has only one statement associated with the if and the else.

For eksempel:

#include <stdio.h>
int main() {
  int y;
  int x = 2;
   y = (x >= 6) ?  6 : x;/* This is equivalent to:  if (x >= 5)    y = 5;  else    y = x; */
   printf("y =%d ",y);
  return 0;}

Output:

y =2

Indlejrede If-else-erklæringer

Når en række beslutninger er påkrævet, bruges indlejret if-else. Nesting betyder at bruge én if-else-konstruktion i en anden.

Lad os skrive et program for at illustrere brugen af ​​indlejret if-else.

#include<stdio.h>
int main()
{
	int num=1;
	if(num<10)
	{
		if(num==1)
		{
			printf("The value is:%d\n",num);
		}
		else
		{
			printf("The value is greater than 1");
		}
	}
	else
	{
		printf("The value is greater than 10");
	}
	return 0;
}

Output:

The value is:1

Ovenstående program kontrollerer, om et tal er mindre eller større end 10, og udskriver resultatet ved hjælp af indlejret if-else-konstruktion.

Nested If-else statement in C

  1. For det første har vi erklæret en variabel num med værdi som 1. Derefter har vi brugt if-else konstruktion.
  2. In the outer if-else, the condition provided checks if a number is less than 10. If the condition is true then and only then it will execute the inner block. In this case, the condition is true hence the inner block is processed.
  3. In the inner block, we again have a condition that checks if our variable contains the value 1 or not. When a condition is true, then it will process the If block otherwise it will process an else block. In this case, the condition is true hence the If block is executed and the value is printed on the output screen.
  4. The above program will print the value of a variable and exit with success.

Try changing the value of variabel see how the program behaves.

NOTE: In nested if-else, we have to be careful with the indentation because multiple if-else constructs are involved in this process, so it becomes difficult to figure out individual constructs. Proper indentation makes it easy to read the program.

Indlejrede Else-if-udsagn

Nested Else-if ladder in C

Nested else-if bruges, når multipath-beslutninger er påkrævet.

Den generelle syntaks for, hvordan else-if-stiger er konstrueret i 'C'-programmering, er som følger:

 if (test - expression 1) {
    statement1;
} else if (test - expression 2) {
    Statement2;
} else if (test - expression 3) {
    Statement3;
} else if (test - expression n) {
    Statement n;
} else {
    default;
}
Statement x;

This type of structure is known as the else-if ladder. This chain generally looks like a ladder hence it is also called as an else-if ladder. The test-expressions are evaluated from top to bottom. Whenever a true test-expression if found, statement associated with it is executed. When all the n test-expressions becomes false, then the default else statement is executed.

Lad os se det faktiske arbejde ved hjælp af et program.

#include<stdio.h>
int main()
{
	int marks=83;
	if(marks>75){
		printf("First class");
	}
	else if(marks>65){
		printf("Second class");
	}
	else if(marks>55){
		printf("Third class");
	}
	else{
		printf("Fourth class");
	}
	return 0;
}

Output:

First class

Ovenstående program udskriver karakteren i henhold til karaktererne i en test. Vi har brugt else-if ladder-konstruktionen i ovenstående program.

  1. Vi har initialiseret en variabel med mærker. I else-if-stigestrukturen har vi givet forskellige betingelser.
  2. Værdien fra variabelmærkerne vil blive sammenlignet med den første betingelse, da det er sandt, at den erklæring, der er knyttet til den, vil blive udskrevet på outputskærmen.
  3. Hvis den første testbetingelse viser sig at være falsk, sammenlignes den med den anden betingelse.
  4. This process will go on until all expressions are evaluated otherwise control will go out of the else-if ladder, and default statement will be printed.

Prøv at ændre værdien og bemærk ændringen i outputtet.

Ofte Stillede Spørgsmål

An if-else tests any Boolean expression, including ranges and relational checks. A skift ... sag compares one variable against fixed constant values and often compiles to a faster jump table for many cases.

The dangling else problem is ambiguity over which if an else belongs to when if statements are nested without braces. In C, an else always pairs with the nearest unmatched if. Adding curly braces removes the confusion.

Yes. Logical operators join conditions: && requires both sides true, || needs at least one true, and ! reverses a result. For example, if (age > 18 && citizen) tests two conditions together in one if.

Braces are optional when the body is a single statement, so C runs only the next line. For two or more statements, braces are required to group them. Using braces always is a safe habit that prevents logic errors.

Short-circuit evaluation stops as soon as the result is known. With &&, a false left side skips the right side. With ||, a true left side skips the right. This avoids unnecessary work and unsafe operations.

Yes. An else-if ladder is evaluated top to bottom and stops at the first true condition. Placing broad conditions before narrow ones can hide the narrow cases, so order the tests from most specific to most general.

Yes. AI coding assistants draft conditional blocks from a comment, convert long if-else chains into cleaner structures, and flag likely bugs such as using = instead of ==. Always test the generated logic before trusting it.

GitHub Copilot autocompletes if, else-if, and nested conditions from your comments or surrounding code. It suggests relational and logical expressions and can add missing braces, though you should review each suggestion.

Opsummer dette indlæg med: