Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Utmaning: For-Loop | Loopar
C#-Grunder

bookUtmaning: For-Loop

Skapa ett program som beräknar fakulteten av ett givet tal x med hjälp av en for-loop. Om talet är 0 ska programmet returnera 1.

main.cs

main.cs

copy
12345678910111213141516171819202122232425262728
using System; namespace ConsoleApp { class Program { static void Main(string[] args) { int x = 5; int result = ___; if(x == 0) { result = ___; } else { for (___) { result *= ___; } } Console.WriteLine($"Factorial of {x} is {result}"); } } }

Initiera loopvariabeln i med värdet 2 och fortsätt loopen tills i är lika med x, så loopvillkoret blir i <= x.

main.cs

main.cs

copy
12345678910111213141516171819202122232425262728
using System; namespace ConsoleApp { internal class Program { static void Main(string[] args) { int x = 5; int result = 1; if(x == 0) { result = 0; } else { for (int i = 2; i <= x; i++) { result *= i; } } Console.WriteLine($"Factorial of {x} is {result}"); } } }
Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 4. Kapitel 2

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Suggested prompts:

Can you show me an example of how the program should work with a specific number?

What should the program do if the input is a negative number?

Can you explain why the loop starts at 2 instead of 1?

Awesome!

Completion rate improved to 1.59

bookUtmaning: For-Loop

Svep för att visa menyn

Skapa ett program som beräknar fakulteten av ett givet tal x med hjälp av en for-loop. Om talet är 0 ska programmet returnera 1.

main.cs

main.cs

copy
12345678910111213141516171819202122232425262728
using System; namespace ConsoleApp { class Program { static void Main(string[] args) { int x = 5; int result = ___; if(x == 0) { result = ___; } else { for (___) { result *= ___; } } Console.WriteLine($"Factorial of {x} is {result}"); } } }

Initiera loopvariabeln i med värdet 2 och fortsätt loopen tills i är lika med x, så loopvillkoret blir i <= x.

main.cs

main.cs

copy
12345678910111213141516171819202122232425262728
using System; namespace ConsoleApp { internal class Program { static void Main(string[] args) { int x = 5; int result = 1; if(x == 0) { result = 0; } else { for (int i = 2; i <= x; i++) { result *= i; } } Console.WriteLine($"Factorial of {x} is {result}"); } } }
Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 4. Kapitel 2
some-alt