Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Challenge: If Statement | Introduction to Conditional Statements
Practice
Projects
Quizzes & Challenges
Quizer
Challenges
/
Mastering Conditional Statements in C
Seksjon 1. Kapittel 2
single

single

bookChallenge: If Statement

Sveip for å vise menyen

You have already explored the importance of control flow in programming. Now, it is time to focus on the basic building block of decision-making in C: the if statement. The if statement allows you to execute a block of code only when a specific condition is true. Its syntax is straightforward:

main.c

main.c

copy
123
if (condition) { // Statements to execute if condition is true }

Here, the condition is an expression that evaluates to either true (non-zero) or false (zero). If the condition is true, the code inside the braces runs; otherwise, it is skipped.

main.c

main.c

copy
123456789101112
#include <stdio.h> int main() { int age = 20; // User is an adult if (age >= 18) printf("Access granted.\n"); return 0; }

This simple structure enables your programs to make decisions and respond differently to various inputs or situations.

Oppgave

Swipe to start coding

Write a function that uses an if statement to check if a given integer is positive. If the number is greater than zero, return a value indicating that it is positive.

  • Use an if statement to test if number is greater than zero.
  • If true, return a value (such as 1) to indicate the number is positive.
  • Otherwise, return a value (such as 0) to indicate the number is not positive.

Løsning

Switch to desktopBytt til skrivebordet for virkelighetspraksisFortsett der du er med et av alternativene nedenfor
Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 1. Kapittel 2
single

single

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

some-alt