C# Tutorial
This C# program is used to find the sum of number for the given user input number.
for loop is used here to compute sum of numbers and displayed output in the console using WriteLine method in Console class of System namespace..
using System; // System is a namespace public class SumOfNumber { // Main method which starts the program execution. public static void Main() { int number, sum=0; Console.Write("Enter number: "); number = int.Parse(Console.ReadLine()); Console.Write("Sum of Number '"+number+ "' : "); for (int i = 1; i <= number; i++) { sum = sum + i; } Console.WriteLine(sum); Console.ReadKey(); } }
Output:,/p>
C:> csc SumOfNumber.cs C:> SumOfNumber Enter number: 10 Sum of Number '10' : 55
This C# program is not having the for loop block and computes the sum of number using only single line for loop.
using System; // System is a namespace public class SumOfNumber { // Main method which starts the program execution. public static void Main() { int number, sum=0; Console.Write("Enter number: "); number = int.Parse(Console.ReadLine()); Console.Write("Sum of Number '"+number+ "' : "); for (int i = 1; i <= number; sum = sum + i, i++) ; Console.WriteLine(sum); Console.ReadKey(); } }
Output:,/p>
C:> csc SumOfNumber.cs C:> SumOfNumber Enter number: 10 Sum of Number '10' : 55
When you use single line for loop, needs to be correctly used sequence of statements in increment section.
Let us consider the alternate way of placing sum=sum+i and i++ statements,
using System; // System is a namespace public class SumOfNumber { // Main method which starts the program execution. public static void Main() { int number, sum=0; Console.Write("Enter number: "); number = int.Parse(Console.ReadLine()); Console.Write("Sum of Number '"+number+ "' : "); for (int i = 1; i <= number; i++, sum = sum + i) ; Console.WriteLine(sum); Console.ReadKey(); } }
Output:,/p>
C:> csc SumOfNumber.cs C:> SumOfNumber Enter number: 10 Sum of Number '10' : 65
This program computes the sum of number is 65 and this is wrong because last iteration variable 'i' value is added 2 times.
This incorrect computation is because of placing the statements in increment section.
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page