Here is the code from class. It is, of course, not a coherent program just a set of examples
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LoopExamples { class Program { static void Main(string[] args) { //this is a simple for loop //first you set the counter, then you set //the limit, then you increment (++) the counter for (int counter = 0; counter < 20; counter++) { Console.WriteLine(counter); } //this is a for loop that outputs the prime numbers //from the previous assignment for (int i = 1; i < 41; i++) { int prime = i * i - i + 41; Console.WriteLine(prime); } //your can use a variable for the loop limit Console.WriteLine("how many loops do you want to do?"); int number = int.Parse(Console.ReadLine()); //avoid an infinite loop--infinite loops result //when the end condition will never be met for (int x = 1; x < number; x--)//decrement -1 { Console.WriteLine(x); if (x == -10) { break; } } //you can use other operators that ++ or -- //this one counts up by 3s for (int i = 1; i < 20; i += 3) { Console.WriteLine(i); } // +=, -=, *=, /=, %= //number -= 2 equivalent to number = number - 2 // number *= 2 equivelant to number = number * 2 Console.WriteLine("how many numbers do you want to enter"); int num = int.Parse(Console.ReadLine()); //I declare these outside the loop so that I can use them //outside--if I declared them in the loop they would //have the "scope" of the loop. In general a variable has the scope //of the block "{}" it is declared in double sum = 0; double average = 0; for (int i = 1; i <= num; i++) { Console.WriteLine("enter a number"); double myNumber = double.Parse(Console.ReadLine()); sum += myNumber; } Console.WriteLine("the sum is {0}", sum); average = sum / num; Console.WriteLine("The average is {0}", average); //a while loop continues looping until the critera //set at the beginning is no longer true string quit = "no"; //Equals is equivalent to "==" but works better with strings while (quit.Equals("no") || quit.Equals("No")) { Console.WriteLine("Are your ready to quit 'yes/no"); quit = Console.ReadLine(); quit = quit.ToLower();//this forces everything to lower case } bool goodNumber = false; int number2=0; //this loops until the user enters a good number while (goodNumber == false) { Console.WriteLine("enter a valid number"); goodNumber = int.TryParse(Console.ReadLine(), out number2); } Console.WriteLine("Your Number is {0}", number2); // a do while loop is like a while loop except it checks its //criteria at the end. that means it is guaranteed to execute //at least once do { Console.WriteLine("enter a valid number"); goodNumber = int.TryParse(Console.ReadLine(), out number); } while (goodNumber == false); Console.ReadKey(); } } }
No comments:
Post a Comment