- Back to Home »
- C#.NET »
- C#.NET While loop
Posted by :
Sudhir Chekuri
Thursday, 31 December 2015
While loop is used to execute a set of statements till the condition is met. It doesn’t have initialization and increment or decrement operators as part of its syntax.
Syntax
While(condition)
{
<Statements>
}
C#.NET While loop program
Program
Output
0
1
2
3
4
5
6
7
8
9
Examples
1
Amstrong number because 1^3 = 1
121
Not amstrong number because 1^3+2^3+1^3 = 1+8+1= 10.
10 not equal to 121
153
Amstrong number because 1^3+5^3+3^3 = 1+ 125 + 27 =153
153 equal to 153.
C#.NET program to say Armstrong or not
using System;
Explanation: In this program the number entered is stored in a variable num.
The value inside variable num is copied into variable num1 to match the result with this number at the last.
While loop is used to retreive the last number of the given number and to find the cube of that number which are added and stored in variable sum.
After coming out of while loop the value in sum and num1 is matched to know wheather the given number is amstrong or not.
If they are matched the value given is amstrong otherwise not.
Syntax
While(condition)
{
<Statements>
}
C#.NET While loop program
Program
using System;
namespace ConsoleTasks
{
class Program
{
static void Main(string[] args)
{
int i = 0;
while (i < 10)
{
Console.WriteLine(i);
i++;
}
Console.ReadKey();
}
}
}
Output
0
1
2
3
4
5
6
7
8
9
Armstrong Number program
If the sum of the cubes of digits in a number is equal to that number then it is known as Armstrong number.Examples
1
Amstrong number because 1^3 = 1
121
Not amstrong number because 1^3+2^3+1^3 = 1+8+1= 10.
10 not equal to 121
153
Amstrong number because 1^3+5^3+3^3 = 1+ 125 + 27 =153
153 equal to 153.
C#.NET program to say Armstrong or not
using System;
namespace Armstrong
{
class Program
{
static void Main(string[] args)
{
int num, num1, temp, q, sum = 0;
num
= Convert.ToInt32(Console.ReadLine());
num1
= num;
while (num > 0)
{
q = num / 10;
temp = num % 10;
sum = sum + (temp * temp * temp);
num = q;
}
if (sum == num1)
{
Console.WriteLine("{0} is Armstrong ");//153
}
else
{
Console.WriteLine("{0} is not Armstrong");//121
}
Console.ReadLine();
}
}
}
Explanation: In this program the number entered is stored in a variable num.
The value inside variable num is copied into variable num1 to match the result with this number at the last.
While loop is used to retreive the last number of the given number and to find the cube of that number which are added and stored in variable sum.
After coming out of while loop the value in sum and num1 is matched to know wheather the given number is amstrong or not.
If they are matched the value given is amstrong otherwise not.