Ehdolliset lausekkeet C:ssä: If, Else, Nested If esimerkin avulla

⚡ Älykäs yhteenveto

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.

  • 🔤 Jos-lauseke: 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.
  • 🇧🇷 Relaatiooperaattorit: 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.
  • Kolmikantainen operaattori: The ?: conditional expression writes a compact if-else that returns one of two values in a single line.
  • 🤖 AI-apu: 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

Mikä on ehdollinen lauseke C:ssä?

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.’

Toisin kuin loops in C that repeat code, conditional statements pick one path.

'C'-ohjelmoinnissa ehdolliset lauseet ovat mahdollisia seuraavien kahden konstruktin avulla:

  1. Jos lausunto
  2. Jos-muuten-lauseke

Sitä kutsutaan myös haarautumiseksi, koska ohjelma päättää, minkä käskyn se suorittaa arvioidun ehdon tuloksen perusteella.

Jos lausunto

Se on yksi vahvimmista ehdollisista lausunnoista. If-lause on vastuussa ohjelman suoritusvirran muuttamisesta. Jos lauseketta käytetään aina ehdon kanssa. Ehto arvioidaan ensin ennen kuin suoritetaan mitään käskyä Ifin rungossa. If-lausekkeen syntaksi on seuraava:

 if (condition) 
     instruction;

Ehto arvioi joko tosi tai epätosi. True on aina nollasta poikkeava arvo, ja false on arvo, joka sisältää nollan. Ohjeet voivat olla yksittäisiä käskyjä tai koodilohkoja, jotka on suljettu aaltosulkeilla { }.

Seuraava ohjelma havainnollistaa if-konstruktin käyttöä 'C'-ohjelmoinnissa:

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

lähtö:

num1 is smaller than num2

Yllä oleva ohjelma havainnollistaa if-konstruktin käyttöä kahden luvun yhtäläisyyden tarkistamiseen.

If Statement flowchart in C

  1. Yllä olevassa ohjelmassa olemme alustaneet kaksi muuttujaa num1, num2 arvoilla 1, 2 vastaavasti.
  2. Sitten olemme käyttäneet if testilausekkeella tarkistamaan, mikä luku on pienin ja mikä suurin. Olemme käyttäneet relaatiolauseketta if-konstruktissa. Koska num1:n arvo on pienempi kuin num2, ehdon arvo on tosi.
  3. Siten se tulostaa lausunnon If-lohkon sisään. Sen jälkeen ohjaus menee lauseen ulkopuolelle ja ohjelma lopetetaan onnistuneella tuloksella.

omainen OperaTors

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

Huomaa, että yhtäläisyystesti (==) eroaa osoitusoperaattorista (=), koska se on yksi yleisimmistä ongelmista, joita ohjelmoija kohtaa sekoittamalla niitä.

Esimerkiksi:

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

Lähtö:

 You succeed

Muista, että ehto, joka laskee nollasta poikkeavaan arvoon, katsotaan tosi.

Esimerkiksi:

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

lähtö:

There is someone present in the classroom

If-Elsen lausunto

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.

Seuraavat ohjelmat havainnollistavat if-else-rakenteen käyttöä:

Alustamme muuttujan jollakin arvolla ja kirjoitamme ohjelman, joka määrittää, onko arvo pienempi kuin kymmenen vai suurempi kuin kymmenen.

Aloitetaan.

#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;
}

lähtö:

The value is greater than 10

If-Else statement example output in C

  1. Olemme alustaneet muuttujan, jonka arvo on 19. Meidän on selvitettävä 'C'-ohjelmalla, onko luku suurempi vai pienempi kuin 10. Tätä varten olemme käyttäneet if-else-rakennetta.
  2. Tässä olemme antaneet ehdon numero <10, koska meidän on verrattava arvoamme 10:een.
  3. Kuten näet, ensimmäinen lohko on aina tosi lohko, mikä tarkoittaa, että jos testilausekkeen arvo on tosi, ensimmäinen lohko, joka on If, suoritetaan.
  4. Toinen lohko on else-lohko. Tämä lohko sisältää lausunnot, jotka suoritetaan, jos testilausekkeen arvo tulee epätosi. Ohjelmassamme arvon num on suurempi kuin kymmenen, joten testiehdosta tulee epätosi ja muuten lohko suoritetaan. Siten lähtömme tulee muusta lohkosta, joka on "Arvo on suurempi kuin 10". Jos-else-komennon jälkeen ohjelma päättyy onnistuneella tuloksella.

'C'-ohjelmoinnissa voimme käyttää useita if-else-rakenteita toistensa sisällä, joita kutsutaan if-else-käskyjen sisäkkäisiksi.

Ehdolliset lausekkeet

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.

Esimerkiksi:

#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;}

lähtö:

y =2

Sisäkkäiset If-else-lausunnot

Kun tarvitaan sarja päätöstä, käytetään sisäkkäisiä if-else-asetuksia. Sisäkkäisyys tarkoittaa yhden if-else -rakenteen käyttämistä toisen sisällä.

Kirjoitetaan ohjelma havainnollistamaan sisäkkäisen if-else käyttöä.

#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;
}

lähtö:

The value is:1

Yllä oleva ohjelma tarkistaa, onko luku pienempi vai suurempi kuin 10, ja tulostaa tuloksen käyttämällä sisäkkäistä if-else -rakennetta.

Nested If-else statement in C

  1. Ensin olemme ilmoittaneet muuttujan num, jonka arvo on 1. Sitten olemme käyttäneet if-else -konstruktia.
  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 muuttuja 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.

Sisäkkäiset Else-if-lauseet

Nested Else-if ladder in C

Sisäkkäistä else-if -toimintoa käytetään, kun tarvitaan monitiepäätöksiä.

Yleinen syntaksi sille, kuinka else-if tikkaat rakennetaan "C"-ohjelmoinnissa, on seuraava:

 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.

Katsotaanpa todellista toimintaa ohjelman avulla.

#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;
}

lähtö:

First class

Yllä oleva ohjelma tulostaa arvosanan kokeessa saatujen pisteiden mukaan. Olemme käyttäneet else-if tikapuurakennetta yllä olevassa ohjelmassa.

  1. Olemme alustaneet muuttujan merkeillä. Muu-if-tikapuurakenteessa olemme tarjonneet erilaisia ​​ehtoja.
  2. Muuttujamerkkien arvoa verrataan ensimmäiseen ehtoon, koska se on totta, siihen liittyvä lause tulostetaan tulosnäytölle.
  3. Jos ensimmäinen testiehto osoittautuu vääräksi, sitä verrataan toiseen ehtoon.
  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.

Yritä muuttaa arvoa ja huomaa muutoksen lähdössä.

UKK

An if-else tests any Boolean expression, including ranges and relational checks. A switch…case 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.

Tiivistä tämä viesti seuraavasti: