C Dilinde Koşullu İfadeler: If, Else, İç İçe If ve Örnekleri

⚡ Akıllı Özet

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.

  • 🔤 Eğer koşulu: 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.
  • 🇧🇷 İlişkisel operatörler: 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.
  • Üçlü operatör: The ?: conditional expression writes a compact if-else that returns one of two values in a single line.
  • 🤖 Yapay zeka yardımı: 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

C'de Koşullu İfade Nedir?

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

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

'C' programlamada koşullu ifadeler aşağıdaki iki yapının yardımıyla mümkündür:

  1. If ifadesi
  2. Eğer-değilse ifadesi

Bir program, değerlendirilen koşulun sonucuna göre hangi ifadenin yürütüleceğine karar verdiği için buna dallanma da denir.

If ifadesi

Güçlü koşullu ifadelerden biridir. If ifadesi bir programın yürütme akışını değiştirmekten sorumludur. If ifadesi her zaman bir koşulla birlikte kullanılır. If'in gövdesinde herhangi bir ifade yürütülmeden önce ilk olarak koşul değerlendirilir. If ifadesinin sözdizimi aşağıdaki gibidir:

 if (condition) 
     instruction;

Koşul doğru veya yanlış olarak değerlendirilir. True her zaman sıfır olmayan bir değerdir, false ise sıfır içeren bir değerdir. Talimatlar tek bir talimat veya küme parantezleri { } içine alınmış bir kod bloğu olabilir.

Aşağıdaki program, 'C' programlamada if yapısının kullanımını göstermektedir:

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

Çıktı:

num1 is smaller than num2

Yukarıdaki program, iki sayının eşitliğini kontrol etmek için if yapısının kullanımını göstermektedir.

If Statement flowchart in C

  1. Yukarıdaki programda num1, num2 ile değerleri sırasıyla 1, 2 olan iki değişkeni başlattık.
  2. Daha sonra hangi sayının en küçük, hangi sayının en büyük olduğunu kontrol etmek için bir test ifadesiyle if'i kullandık. İf yapısında ilişkisel bir ifade kullandık. num1'in değeri num2'den küçük olduğundan koşul doğru olarak değerlendirilecektir.
  3. Böylece ifadeyi If bloğunun içine yazdıracaktır. Bundan sonra kontrol bloğun dışına çıkacak ve program başarılı bir sonuçla sonlandırılacaktır.

İlişkisel Operaları

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

Eşitlik testinin (==) atama operatöründen (=) farklı olduğuna dikkat edin çünkü bu, bir programcının bunları karıştırırken karşılaştığı en yaygın sorunlardan biridir.

Örneğin:

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

Çıkış:

 You succeed

Sıfır dışında bir değer olarak değerlendirilen bir koşulun doğru olarak kabul edildiğini unutmayın.

Örneğin:

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

Çıktı:

There is someone present in the classroom

If-Else ifadesi

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.

Aşağıdaki programlar if-else yapısının kullanımını göstermektedir:

Bir değişkeni belirli bir değerle başlatacağız ve değerin ondan küçük veya ondan büyük olup olmadığını belirleyecek bir program yazacağız.

Hadi başlayalım.

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

Çıktı:

The value is greater than 10

If-Else statement example output in C

  1. 19 değerinde bir değişken başlattık. Bir 'C' programı kullanarak sayının 10'dan büyük veya küçük olduğunu bulmamız gerekiyor. Bunun için if-else yapısını kullandık.
  2. Burada num<10 koşulunu sağladık çünkü değerimizi 10 ile karşılaştırmamız gerekiyor.
  3. Gördüğünüz gibi ilk blok her zaman doğru bir bloktur; bu, eğer test ifadesinin değeri doğruysa o zaman If olan ilk bloğun yürütüleceği anlamına gelir.
  4. İkinci blok bir else bloğudur. Bu blok, test ifadesinin değerinin yanlış olması durumunda yürütülecek ifadeleri içerir. Programımızda num değeri 10'dan büyük olduğundan test koşulu false olur, aksi halde blok çalıştırılır. Böylece çıktımız “Değeri XNUMX’dan büyük” olan else bloğundan olacaktır. If-else sonrasında program başarılı bir sonuçla sonlandırılacaktır.

'C' programlamasında, if-else ifadelerinin iç içe geçmesi olarak adlandırılan birden fazla if-else yapısını birbiri içinde kullanabiliriz.

Koşullu İfadeler

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.

Örneğin:

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

Çıktı:

y =2

İç İçe If-else İfadeleri

Bir dizi karar gerektiğinde iç içe if-else kullanılır. Yuvalama, bir if-else yapısının başka bir yapı içinde kullanılması anlamına gelir.

İç içe if-else kullanımını gösteren bir program yazalım.

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

Çıktı:

The value is:1

Yukarıdaki program bir sayının 10'dan küçük veya büyük olup olmadığını kontrol eder ve sonucu iç içe if-else yapısını kullanarak yazdırır.

Nested If-else statement in C

  1. Öncelikle değeri 1 olan bir num değişkeni tanımladık. Daha sonra if-else yapısını kullandık.
  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 değişken 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.

İç içe Else-if ifadeleri

Nested Else-if ladder in C

Çok yollu kararlar gerektiğinde iç içe else-if kullanılır.

'C' programlamasında else-if merdivenlerinin nasıl oluşturulduğunun genel sözdizimi aşağıdaki gibidir:

 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.

Bir program yardımıyla gerçek çalışmayı görelim.

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

Çıktı:

First class

Yukarıdaki program notu bir testte alınan notlara göre yazdırır. Yukarıdaki programda else-if ladder yapısını kullandık.

  1. İşaretli bir değişkeni başlattık. else-if ladder yapısında çeşitli şartları sağladık.
  2. Değişken işaretlerinden elde edilen değer, ilk koşulla karşılaştırılacaktır çünkü onunla ilişkili ifadenin doğru olması çıkış ekranında yazdırılacaktır.
  3. İlk test koşulu yanlış çıkarsa ikinci koşulla karşılaştırılır.
  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.

Değeri değiştirmeyi deneyin ve çıktıdaki değişikliği fark edin.

SSS

An if-else tests any Boolean expression, including ranges and relational checks. A yer değiştir 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 Yardımcı Pilotu 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.

Bu yazıyı şu şekilde özetleyin: