Output a sequence of ten numbers to console - c#

The user must provide the starting point and indicate whether the sequence should be ascending or descending. Thus far it starts counting and never stops. How do I make it stop after increment it by 10. Would I use an if statement to let the user choose to make it ascending or descending?
class Program
{
static void Main(string[] args)
{
int val;
Console.WriteLine("Please enter a number!");
val = Int32.Parse(Console.ReadLine());
for (int i = val; i <= (val + 10); val++)
Console.WriteLine(val);
Console.ReadLine();
}
}

It never stops because you increase val, and i will always be less than val + 10 (you never increase i). You should increase i instead, and use i inside the loop.
static void Main(string[] args)
{
int val;
Console.WriteLine("Please enter a number!");
val = Int32.Parse(Console.ReadLine());
for (int i = val; i <= (val + 10); i++)
Console.WriteLine(i);
Console.ReadLine();
}
For the ascending vs. descending part, you also need to take a second input from the user and if he choose descending, make a loop that checks if i >= (val - 10), and that goes i-- each iteration instead.

using System;
using System.Linq;
class Sample {
static void Main(){
const char down = '-';
Console.Write("Please enter a number! n[{0}]:", down);
string input = Console.ReadLine();
char ch = input.Last();
int diff = (ch == down) ? -1 : 1;
int val = Int32.Parse(input.TrimEnd(down));
for(var i = 1; i <= 10; i++, val += diff)
Console.WriteLine(val);
}
}
DEMO
Please enter a number! n[-]:10-
10
9
8
7
6
5
4
3
2
1
Please enter a number! n[-]:5
5
6
7
8
9
10
11
12
13
14

Change to:
static void Main(string[] args)
{
int val;
Console.WriteLine("Please enter a number!");
val = Int32.Parse(Console.ReadLine());
for (int i = val; i <= (val + 10); i++)
Console.WriteLine(i);
Console.ReadLine();
}

static void Main(string[] args)
{
int val, isDecrement;
Console.WriteLine("Please enter a number!");
val = Int32.Parse(Console.ReadLine());
Console.WriteLine("Please enter 1 to go Descending order!");
isDecrement = Int32.Parse(Console.ReadLine());
if(isDecrement ==1)
{
for (int i = val; i >= (val - 10); i--)
Console.WriteLine(i);
}
else
{
for (int i = val; i <= (val + 10); i++)
Console.WriteLine(i);
}
Console.ReadLine();
}

Related

Setting a max and min value for user number input in console

Console.WriteLine(" **************************************");
Console.WriteLine(" ****** Reviewer Awarding Points ******");
Console.WriteLine(" **************************************");
Console.WriteLine();
string[]properties= { "Clarity", "Orginality", "Difficulty" };
int[] a = new int[3];
int[] b = new int[3];
for(int i = 0; i < 3; i++)
{
Console.WriteLine(" ***" + properties[i]+"***");
Console.Write(" Alice: ");
a[i] = Convert.ToInt16(Console.ReadLine());
if(a[i]>100 || a[i] < 1)
Console.Write(" Bob: ");
b[i] = Convert.ToInt16(Console.ReadLine());
Console.WriteLine();
}
Console.Read();
}
I want user to enter a value between 1 and 100(including 1 and 100).So what I am gonna do?
your question is not clear
try
int value;
do{
Console.Write("Enter a value");
value=int.parse(Console.ReadLine());
}while(value<1 || value>100);
Make a method that checks the result for being in range:
public int AskInt(string question, int min, int max){
while(true){
Console.WriteLine(question);
string input = Console.ReadLine();
if(int.Tryparse(input, out int value) && value >= min && value <= max)
return value;
}
}
The only way to escape the loop is to enter a valid number that is in range, otherwise the question just repeats
Then you can use it multiple times in your code:
int age = AskInt("Enter an age between 10 and 100: ", 10, 100);
int weight = AskInt("Enter a weight between 100 and 350: " 100, 350);
Try this:
if(a[i]>=100 || a[i] <= 1)
You can learn about C# operators at this site: https://www.w3schools.com/cs/cs_operators.php

Making a word into a sentinel value in C#

I am currently working on a program that is a loop with a sentinel value that asks the user to enter a number or enter -99 to end the program and it runs perfectly. If I were to change that -99 to just the word "Quit" is there a certain parameter that I would have to put? For example, if I want to use a letter, I know that I could use:
char (undefined parameter) = 'A'
But how would I do this with a word? When I simply try to change the value of -99 to Quit, I receive an error as expected.
using System;
class Program {
public static void Main (string[] args) {
int sum = 0;
int counter = 0;
int max = Int32.MinValue;
int min = Int32.MaxValue;
bool keepGoing = true;
while(keepGoing) {
Console.WriteLine("Please enter a number or enter -99 to stop the program:");
int number = Convert.ToInt32(Console.ReadLine());
if (number == -99){
keepGoing = false;
} else {
counter++;
sum += number;
if (number >= max) {
max = number;
}
if (number <= min) {
min = number;
}
}
}
double average = (double) sum / counter;
Console.WriteLine($"{counter} numbers were entered.");
Console.WriteLine("The average is:" + average);
Console.WriteLine("The sum is:" + sum);
Console.WriteLine("The maximum value is:" + max);
Console.WriteLine("The minimum value is:" + min);
}
}
It's difficult to store "Quit" in an int, so the root of your problem is that you have no separation between pulling the string from the console and converting it to an int:
int number = Convert.ToInt32(Console.ReadLine());
if (number == -99){
keepGoing = false;
} else {
counter++;
If you did have a separation, it becomes possible:
string input = Console.ReadLine();
if (input == "Quit"){
keepGoing = false;
} else {
int number = Convert.ToInt32(input);
counter++;

Trying to remove the last "and" at the end of my output list

For my C# programming homework, we had to write a program that allows the user to input an integer and use a loop to print out the factors of that integer.
I got the program to output the integers.
The problem is, for example, when I enter in the integer "24", I want the output to be
1 and 2 and 3 and 4 and 6 and 8 and 12 and 24
but the output that comes out is
1 and 2 and 3 and 4 and 6 and 8 and 12 and 24 and
I don't want the extra "and" at the end of my Factors List
Here is what my code looks like:
using System;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
int a, b;
Console.WriteLine("Please enter your integer: ");
a = int.Parse(Console.ReadLine());
for (b = 1; b <= a; b++)
{
if (a % b == 0)
{
Console.Write(b + " ");
}
}
Console.ReadLine();
}
}
}
EDIT: The output has to be formatted as
1 and 2 and 3 and 4 and 6 and 8 and 12 and 24
or else I won't get credit for the assignment
You can enumerate factors, and then Join them with " and "
private static IEnumerable<int> Factors(int value) {
// Simplest, not that efficient
for (int i = 1; i <= value; ++i)
if (value % i == 0)
yield return i;
}
...
Console.Write(string.Join(" and ", Factors(24)));
Or you can add " and " before, not after printing factors (i)
int value = 24;
bool firstTime = true;
// Simplest, not that efficient
for (int i = 1; i <= value; ++i) {
if (value % i == 0) {
// print "and" before printing i
if (!firstTime)
Console.Write(" and ");
firstTime = false;
Console.Write(i);
}
}
How about adding the numbers to a List and printing after the loop:
int a, b;
a = int.Parse(Console.ReadLine());
var result = new List<int>();
for (b = 1; b <= a; b++)
{
if (a % b == 0)
{
result.Add(b);
}
}
Console.Write(string.Join(" and ", result));
static void Main(string[] args)
{
//get input from user
Console.WriteLine("Please enter your integer: ");
int a = int.Parse(Console.ReadLine());
//enumerate factors
var factors = Enumerable.Range(1, a)
.Where(i => a % i == 0).ToArray();
//join for nicely printed output
Console.Write(string.Join(" and ", factors));
Console.ReadLine();
}
I would recommend you to create a string and output that string becouse it allows you to do more things with it, then do something like this:
int a, b;
string x="";
Console.WriteLine("Please enter your integer: ");
a = int.Parse(Console.ReadLine());
for (b = 1; b <= a; b++)
{
if (a % b == 0)
{
x=x + b.toString() +" and";
}
}
if you know that always will be an "and" at the end you can simply do this
string x = x.Substring(0, x.Length - 3);
and then
Console.Write(x);
Console.ReadLine();

Calculating The Factorial of a Number

When I enter the number 6 to calculate its factorial, it returns 30 (which is wrong).
Why is my program producing incorrect output?
using System;
namespace Scenario1_2
{
class Program
{
static void Main(string[] args)
{
int counter, number, fact;
Console.WriteLine("Please enter the number you wish to factorize");
number = int.Parse(Console.ReadLine());
fact = number;
for (counter = number - 1; counter >= 1; counter--)
{
fact = fact * counter;
Console.WriteLine("The number you entered was {0} and it's factorial is {1}", number, fact);
Console.ReadLine();
}
}
}
}
You look new to programming, or least C#, so just for fun, this will blow your mind:
using System;
namespace Scenario1_2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter the number you wish to factorize");
int number = int.Parse(Console.ReadLine());
Console.WriteLine("The number you entered was {0} and it's factorial is {1}", number, Factorial(number));
Console.ReadKey(true);
}
static int Factorial(int n)
{
if (n >= 2) return n * Factorial(n - 1);
return 1;
}
}
}
No loops anywhere, and the function calls itself.
You can also do it like this:
using System;
namespace Scenario1_2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter the number you wish to factorize");
int number = int.Parse(Console.ReadLine());
Console.WriteLine("The number you entered was {0} and it's factorial is {1}", number, Factorial(number));
Console.ReadKey(true);
}
static int Factorial(int n)
{
return Enumerable.Range(1, n).Aggregate((i, r) => r * i);
}
}
}
Which is all kinds of messed up :) ...but it does get the significant work down to a single line of code.
Then there's my personal favorite, the infinite enumerable:
using System;
namespace Scenario1_2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter the number you wish to factorize");
int number = int.Parse(Console.ReadLine());
Console.WriteLine("The number you entered was {0} and it's factorial is {1}", number, Factorials().Skip(number-1).First());
Console.ReadKey(true);
}
static IEnumerable<int> Factorials()
{
int n = 1, f = 1;
while (true) yield return f = f * n++;
}
}
}
The program is paused waiting for some input. You need to move the second Console.ReadLine() out of the loop. And likely the Console.WriteLine() unless you want to see each iteration completing.
You need to move two lines out from the for loop. The modified code look like this.
using System;
namespace Scenario1_2
{
class Program
{
static void Main(string[] args)
{
int counter, number, fact;
Console.WriteLine("Please enter the number you wish to factorize");
number = int.Parse(Console.ReadLine());
fact = number;
for (counter = number - 1; counter >= 1; counter--)
{
fact = fact * counter;
}
Console.WriteLine("The number you entered was {0} and it's factorial is {1}", number, fact);
Console.ReadLine();
}
}
}
There are lots of ways to calculate Factorial. You can also do it by creating a recursive function. Google can help you a lot on these basic things.
Thanks!
int n = 4, fact = n;
for (int i = n; i > 1; i--)
{
fact *= (i - 1);
}
Console.WriteLine(fact);
Console.ReadLine();
why are You printing the message inside the loop.put it outside the loop
Console.WriteLine("The number you entered was {0} and it's factorial is {1}", number, fact);
using System;
namespace factorial
{
class Program
{
static void Main(string[] args)
{
int fact = 1;
Console.Write("Enter a number to find factorial:");
int n = int.Parse(Console.ReadLine());
for (int i = n; i > 0; i--)
{
fact = fact * i;
}
Console.Write("Factorial of" + n +"is :"+fact);
Console.ReadLine();
}
}
}
import java.util.Scanner;
public class Chapter5ProblemTwelve
{
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
int number;
int factor = 1;
int counter;
System.out.print("Enter a positive integer to display the factorial number: ");
number = keyboard.nextInt();
//If the number entered is less then zero. The program will tell the user to enter a positive number
if (number <= 0)
{
System.out.println("Please enter a postive number and rerun the program again.");
}
else
{
// Math work preformed if user enters a postive number. Example if user enters 4.
// 1*1 = 1, 1*2 = 2,1*3 = 3, 1*4 = 4, The program will multiple all the answers together 1*2*3*4 = 24
for (counter = 1; counter <= number; counter++)
{
factor = factor * counter;
}
//display
System.out.println("The factorial number of " + number + " is: " + factor);
}
}
}
using System;
namespace septtwenty
{
class Program
{
static void Main(string[] args)
{
int i, number, fact;
System.Console.WriteLine("Enter the Number");
number = int.Parse(Console.ReadLine());
fact = number;
for (i = number -1; i>=1; i--)
{
fact = fact * i;
}
System.Console.WriteLine("\nFactorial of Given Number is: "+fact);
Console.ReadLine();
}
}
}

Using "if" statement to remove min/max user input data

I'm new to C#, well, coding in general.
I have done fairly well by myself to date, in this introduction course I am taking, but I ran into a road bump.
I am trying to figure out how to code a if statement that will run inside a loop to analyze 5 different ints as they are entered and to put the max int and min int seperatly so that I can ue the remaining three ints to make a calculation.
To be exact, validate user input and remove the min/max user input to average the remaining three.
PS, I tried an array but for some reason it wasn't working well. I don't have the code as I'm at work right now though. I was told in a lecture that an if statement should be used but arrays are possible too.
Thank you for your time and any possible answers.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string userIsFinished = "";
string name, city, value;
double rating, avg = 0;
double[] array1 = new double[5];
double max = 0;
double min = double.MaxValue;
double score, totalScore = 0;
//get basic information
do
{
Console.WriteLine("Please enter divers name.");
name = Console.ReadLine();
Console.WriteLine("Please enter the divers city.");
city = Console.ReadLine();
//get and validate user input for 1 dive rating
Console.WriteLine("Please enter a dive rating between 1.00 and 1.67.");
rating = Double.Parse(Console.ReadLine());
while (rating < 1 || rating > 1.69)
{
Console.WriteLine("Oops, you entered an invalid number. Please, enter a dive rating between 1.00 and 1.67.");
rating = Double.Parse(Console.ReadLine());
}
Console.ReadLine();
// get and validate user input for 5 judge scores
for (int s = 1; s <= 5; s++)
{
Console.WriteLine("Please enter the score for judge {0}.", s);
value = Console.ReadLine();
score = Convert.ToDouble(value);
while (score < 0 || score > 10)
{
Console.WriteLine("Invalid entry, please enter a number in between 0 - 10.");
score = Convert.ToDouble(Console.ReadLine());
}
array1[s] = Convert.ToDouble(score); //----this line keeps throwing an exception
}
Console.ReadLine();
//calculate totalScore by dropping min/max scores and averaging them times dive rating
foreach (int i in array1)
{
if (i > max)
max = i;
if (i < min)
min = i;
avg += i;
}
totalScore = avg * rating;
//Print gathered and calculated information
Console.WriteLine("Divers name: {0}", name);
Console.WriteLine("Divers city: {0}", city);
Console.WriteLine("Dive degree of difficulty: {0}", rating);
Console.WriteLine("Total dive score is: {0}", totalScore);
// Ask if user wants to process another diver and continue or exit program
Console.WriteLine("Would you like to enter another divers information? [Y]es [N]o: ");
userIsFinished = Console.ReadLine();
}
while
(userIsFinished.ToLower() != "n");
Console.ReadLine();
}
}
}
or you can go list route and
List<int> apples = new List<int>();
apples.Add(31);
apples.Add(34);
apples.Add(100);
apples.Add(57);
apples.Add(1);
int min = apples.Min();
int max = apples.Max();
apples.Remove(min);
apples.Remove(max);
decimal average = (decimal)(apples.Sum()) / apples.Count;
Not sure about your question... You want to know, the max and min about 5 values, and the avarage about the three others...
int[] n = { 4, 7, 29, 3, 87 };
int max = 0;
int min = int.MaxValue;
double avg = 0;
foreach (int i in n)
{
if (i > max)
max = i;
if (i < min)
min = i;
avg += i;
}
avg = avg / n.Count - 2;
try this code:
int[] a = new int[5];
int minpos;
int maxpos;
int min = Int32.MaxValue;
int max = a[0];
int temp = 0;
for (int i = 0; i < 5; i++)
{
Console.WriteLine(" Enter number " + (i + 1));
Int32.TryParse(Console.ReadLine(), out temp);
a[i] = temp;
//Decision Making Logic
if (min > temp)
{
min = temp;
minpos = i;
}
if (max < temp)
{
max = temp;
maxpos = i;
}
}
//At the end of this loop you will see that minpos contains the index of minimum element
//and maxpos contains index of maximum element,values in remaining indeces contain elements that are neither max or min in that //collection
Thanks guys, it appears I needed a good night of sleep. Thanks a ton for all these helpful answers as I'm sure I will be delving into those methods soon and it will be good to be able to get a head start on them. Here is my code,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string userIsFinished = "";
string name, city;
double rating, avg = 0;
double max = 0;
double min = 10;
double score, value = 0, totalScore = 0, finalScore = 0;
//get basic information
do
{
Console.WriteLine("\n");
Console.WriteLine("Please enter divers name.");
name = Console.ReadLine();
Console.WriteLine("Please enter the divers city.");
city = Console.ReadLine();
//get and validate user input for 1 dive rating
Console.WriteLine("Please enter a dive rating between 1.00 and 1.67.");
rating = Double.Parse(Console.ReadLine());
while (rating < 1 || rating > 1.69)
{
Console.WriteLine("Oops, you entered an invalid number. Please, enter a dive rating between 1.00 and 1.67.");
rating = Double.Parse(Console.ReadLine());
}
Console.ReadLine();
// get and validate user input for 5 judge scores
for (int s = 1; s <= 5; s++)
{
Console.WriteLine("Please enter the score for judge {0}.", s);
score = Convert.ToDouble(Console.ReadLine());
while (score < 0 || score > 10)
{
Console.WriteLine("Invalid entry, please enter a number in between 0 - 10.");
score = Convert.ToDouble(Console.ReadLine());
}
if (score > max)
max = score;
if (score < min)
min = score;
totalScore = score + totalScore;
}
Console.ReadLine();
\\Calculate values
value = totalScore - max - min;
avg = value / 3;
finalScore = avg * rating;
//Print gathered and calculated information
Console.WriteLine("Divers name: {0}", name);
Console.WriteLine("Divers city: {0}", city);
Console.WriteLine("Dive degree of difficulty: {0}", rating);
Console.WriteLine("Total dive score is: {0}", finalScore);
Console.WriteLine("\n");
// Ask if user wants to process another diver and continue or exit program
Console.WriteLine("Would you like to enter another divers information? [Y]es [N]o: ");
userIsFinished = Console.ReadLine();
}
while
(userIsFinished.ToLower() != "n");
Console.ReadLine();
Console.WriteLine("\n");
}
}
}

Categories

Resources