Basically I'm writing a method where I want to find the summation of whole numbers with a for loop.
The output should be something like this:
Enter value of number 1: 23
Enter value of number 2: 23
Enter value of number 3: 23
The sum is: 69
The user will be able choose of many numbers to be added.
My code currently looks like this:
private void ReadInput()
{
Console.Write("Number of values to sum?");
numOfInput = int.Parse(Console.ReadLine());
Console.WriteLine();
}
private void ReadInput()
{
Console.Write("Number of values to sum?");
numOfInput = int.Parse(Console.ReadLine());
Console.WriteLine();
}
private void SumNumbers()
{
int index;
int num = 0;
for (index = 0; index < numOfInput; index++)
{
Console.WriteLine("Please give the value of no " + index);
num = int.Parse(Console.ReadLine());
}
}
how should I fix it
private void SumNumbers()
{
int index;
int num = 0;
for (index = 0; index < numOfInput; index++)
{
Console.WriteLine("Please give the value of no <whole numbers> " + index);
num += int.Parse(Console.ReadLine());
num = sum;
}
}
private void ShowResults()
{
Console.WriteLine("----------------------------------------------\n");
Console.WriteLine("The sum is \t{0}", sum);
Seems to be the solution + the classes above it are still used but yes.
Thank y'all very much
Try this,
private static void SumNumbers()
{
int numOfInput = 3;
int index;
int num = 0;
for (index = 1; index <= numOfInput; index++)
{
Console.WriteLine("Please give the value of no " + index);
num += int.Parse(Console.ReadLine());
}
Console.WriteLine("The sum is:" + num.ToString());
Console.ReadLine(); // to keep console alive
}
Hope helps,
private void SumNumbers()
{
int index;
int num = 0;
for (index = 0; index < numOfInput; index++)
{
Console.WriteLine("Please give the value of no " + index);
num += int.Parse(Console.ReadLine());
Console.WriteLine("The sum so far is : "+num.ToString("N0")+". Enter another number to continue summation.");
}
Console.WriteLine("Maximum input received. Total is: "+num.ToString("N0")+".");
Console.ReadLine();
}
This will work as per your need:
int index;
int num = 0;
Console.WriteLine("Number of values to sum: ");
int numOfInput = int.Parse(Console.ReadLine());
for (index = 1; index <= numOfInput; index++)
{
Console.WriteLine("Please give the value of no " + index);
num += int.Parse(Console.ReadLine());
}
Console.WriteLine("The sum is: " + num);
The following output will be generated:
Number of values to sum: 3
Please give the value of no 1
23
Please give the value of no 2
23
Please give the value of no 3
23
The sum is: 69
Related
For some reason my program won't print the correct index that corresponds with the value and the correct value that corresponds with the array.
private static void askNumber(int[] numbers)
{
Console.WriteLine("Please enter a number: ");
int number = int.Parse(Console.ReadLine());
for(int i = 0; i < numbers.Length - 1; i++)
{
if(number == numbers[i]) //if the user input is equal to the number at the index
{
Console.WriteLine("Your index for your number {0} is {1}", number, i);
}
}
}
private static void randomNumberArray(int upperLimit, int[] numbers)
{
Random randInt = new Random(); //random function
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = randInt.Next(upperLimit); //random number is chosen between 0 and upperLimit
}
foreach(int i in numbers)
{
Console.WriteLine(numbers[i]);
}
}
private static void askIndex(int[] numbers)
{
Console.WriteLine("Please enter an index: ");
int index = int.Parse(Console.ReadLine());
Console.WriteLine("The value at index {0} is {1}", index, numbers[index]); //fetches number at an index entered
}
All of the code I have put in here doesn't output the correct index and number. I have also included the random number generator for the array. I just can't seem to find the problem and I don't know how.
Thanks!
Your problem is here:
foreach(int i in numbers)
{
Console.WriteLine(numbers[i]);
}
Assuming you want to print an array of generated numbers:
foreach(int i in numbers)
{
Console.WriteLine(i);
}
I need to write a console app that asks the user how many number (double) to enter. After accepting that many numbers, display every other number entered. There always seems to be an error when I try to use a double. I also get this error "System.IndexOutOfRangeException was unhandled
HResult=-2146233080
Message=Index was outside the bounds of the array."
after the the for loop has gone through the last loop for this line
myArrai1[i] = int.Parse(Console.ReadLine());
in the first for loop
this all the code I have been able to try to brainstorm with.
class Program
{
static void Main(string[] args)
{
Console.Write("Enter Item Count: ");
int number = int.Parse(Console.ReadLine());
int[] myArrai1 = new int[number];
int i = 0;
for (i = 1; i <= number; i++)
{
Console.WriteLine("Enter Number " + i.ToString() + ": ");
myArrai1[i] = int.Parse(Console.ReadLine());
}
for (i = 0; i < number; i++)
{
Console.WriteLine("Every other number entered: ");
Console.WriteLine(myArrai1[i += 2]);
}
Console.ReadLine();
}
}
}
Not too far off, main changes to fix fix this was loop#1 was set to 0 index to prevent out of range and loop#2 was simplified by intervaling at 2 of ++.
The rest of the changes were aesthetic; I changed the input Console.WriteLine to just Console.Write to keep the input on the same line, and moved the Every Other Line statement to precede the output display loop instead of being written on every iteration.
Console.Write("Enter Item Count: ");
int number = int.Parse(Console.ReadLine());
int[] myArrai1 = new int[number];
for (int i = 0; i < number; i++) {
Console.Write("Enter Number " + (i + 1) + ": ");
myArrai1[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("Every other number entered: ");
for (int j = 0; j < number; j = j + 2) {
Console.WriteLine(myArrai1[j]);
}
I am writing a program that takes the scores of homework assignments, puts them in a array, then averages them. But I need to make it so that these grades range from 1-10. I am not sure how to make it only accept Numbers 1-10. Everything else is complete.
Here is what i have so far:
namespace AverageScore
{
class AverageScore
{
//prompt user to enter the size of the array
public int GetNum()
{
Console.WriteLine("Please enter how many scores you want to save!");
string strNum = Console.ReadLine();
int num = int.Parse(strNum);
return num;
}
static void Main(string[] args)
{
AverageScore scoreObject = new AverageScore();
int arraySize = scoreObject.GetNum();
//define a double array to save scores
double[] scoreArray = new double[arraySize];
string inValue = "";
double sum = 0,
intValue;
Console.WriteLine("Please enter all homework scores");
int counter = 0;
while (counter < arraySize)
{
inValue = Console.ReadLine();
while (double.TryParse(inValue, out intValue) == false)
{
Console.WriteLine("Invalid input = 0 stored in intValue");
inValue = Console.ReadLine();
}
sum += intValue;
scoreArray[counter] = intValue;
counter++;
}
Array.Sort(scoreArray);
double lowest= scoreArray[0];
double highest = scoreArray[arraySize-1];
sum = sum - lowest - highest;
double average = sum / arraySize;
Console.WriteLine("The average grade of the scores is" + average);
Console.WriteLine("The Lowest Score is" + lowest);
Console.WriteLine("The Highest Score is" + highest);
Console.Read();
}
}
}
so your problem is to restrict a input to 1-10 correct?
Why not just:
public int InputGrade()
{
Console.Clear();
Console.WriteLine("Please enter a grade [1-10]");
var grade = -1;
if (!Int32.TryParse(Console.ReadLine(), out grade))
return InputGrade();
if (grade < 1 || grade > 10)
return InputGrade();
return grade;
}
then you should be able to use it like this and it is cleaner:
while (counter < arraySize)
{
var grade = InputGrade();
sum += grade;
scoreArray[counter++] = grade;
}
recommendation
Indeed you should refactor the input from the calculation part - you code will get much more cleaner and more readable:
IEnumberable<int> InputGrades()
{
var count = GetNum();
var grades = new List<int>();
for (var i = 0; i < count; i++)
grades.Add(InputGrade());
return grades;
}
void OutputScores(IEnumerable<int> grades)
{
var scores = grades.Cast<doulbe>().ToArray();
var lowest = scores.Min();
var highest = scores.Max();
var average = scores.Average();
Console.WriteLine("The average grade of the scores is" + average);
Console.WriteLine("The Lowest Score is" + lowest);
Console.WriteLine("The Highest Score is" + highest);
}
Adjust the while loop condition to check that the number is in range (added a simple string format to present the previous invalid entry):
while (double.TryParse(inValue, out intValue) == false || intValue < 1.0 || intValue > 10.0**)
{
Console.WriteLine(String.Format("Invalid input = {0} stored in intValue", intValue));
inValue = Console.ReadLine();
}
This should do it:
while (counter < arraySize){
inValue = Console.ReadLine();
while (true){
if(double.TryParse(inValue ,out intValue) {
if(intValue >=1 && intValue <=10){
break;
}else{
Console.WriteLine("Input must be in the range 1-10");
inValue = Console.ReadLine();
}
}else{
Console.WriteLine("Invalid input = 0 stored in intValue");
inValue = Console.ReadLine();
}
}
sum += intValue;
scoreArray[counter] = intValue;
counter++;
}
Uses a loop to check if the value entered is correct:
while (int.Parse(inValue) < 1 || int.Parse(inValue) > 10) inValue = Console.ReadLine();
Hi guys so i'm starting to learn C# and I came up with this problem when I was trying to mix things up
It says "Input string was not in correct format" at the
n = Convert.ToInt32(Console.ReadLine());
Here's the whole code
namespace Exercise13
{
class Program
{
static void Main(string[] args)
{
char choice;
Console.Write("What operation would you like to use?");
Console.WriteLine("\na. Addition \tb. Subtraction \tc.Multiplication \td.Division");
choice = (char)Console.Read();
if (choice == 'a')
{
sumValues();
}
else if (choice == 'b')
{
minusValues();
}
else if (choice == 'c')
{
timesValues();
}
Console.ReadLine();
}
static void sumValues()
{
int n = 0;
int sum = 0;
int i = 0,val = 0;
Console.Write("How many numbers do you want calculate: ");
n = Convert.ToInt32(Console.ReadLine());
for (i = 0; i < n; i++)
{
Console.Write("\nInput number: ");
val = Convert.ToInt32(Console.ReadLine());
sum += val;
}
Console.Write("\nThe Answer is: "+sum);
}
static void minusValues()
{
int diff = 0, m, z, value;
Console.Write("How many numbers do you want calculate: ");
m = int.Parse(Console.ReadLine());
for (z = 0; z < m; z++)
{
Console.Write("\nInput number: ");
value = int.Parse(Console.ReadLine());
diff -= value;
}
Console.Write("\nThe Answer is: " + diff);
}
static void timesValues()
{
int prod = 0, e, i, val;
Console.Write("How many numbers do you want to calculate: ");
e = Convert.ToInt32(Console.ReadLine());
for (i = 0; i < e; i++)
{
Console.Write("\nInput number: ");
val = int.Parse(Console.ReadLine());
prod *= val;
}
Console.Write("\nThe answer is: " + prod);
}
}
}
Use Integer.TryParse to handle the strings potentially not being numbers. Then prompt the user if the input is not parsable to enter valid input.
Convert and Parse both will throw exceptions if the string is not an exact number.
https://msdn.microsoft.com/en-us/library/f02979c7%28v=vs.110%29.aspx
int n = 0;
int sum = 0;
int i = 0,val = 0;
Console.Write("How many numbers do you want calculate: ");
var isValidNumber = Int32.TryParse(Console.ReadLine(), out n);
if(!isValidNumber) {
Console.WriteLine("Invalid number entered!");
}
else {
//Use the number
}
This is what I have so far:
namespace factorials
{
class Program
{
static void Main(string[] args)
{
int number;
do
{
Console.WriteLine("What non-negative integer do you want to factorial?");
while (!int.TryParse(Console.ReadLine(), out number))
Console.WriteLine("Please enter a whole number only");
calculate(ref number);
} while (number >= 0);
Console.WriteLine("Please enter a non-negative number");
}
static void calculate(ref int number)
{
int factorial;
int counter;
for (counter = number; counter <= number; counter++)
{
factorial = number * number;
Console.WriteLine("The factorial of {0} is {1}", number, factorial);
}
}
}
}
Right now it just gives me the square of the numbers, not the factorial of them. How do I make it repeat the number of times as the input so it results in a factorial?
Also I am not sure if it's necessary to limit the program to non-negative integers only but if I want to that part is just ending the program right there instead of looping back to the beginning.
The for loop doesn't make any sense at all! If you are looking for a factorial, then you have to multiply all the numbers from one to the given number. That would be:
int factorial = 1;
for (counter = 1; counter <= number; counter++)
{
factorial = factorial * counter;
}
Console.WriteLine("The factorial of {0} is {1}", number, factorial);
This would calculate the factorial of one number. You would have to repeat it for all the numbers you wanted.
Your loop assigns the square of the number to the result in a loop, and exits right away. You need to change it so that the result is repeatedly multiplied by numbers from 1 to N, inclusive.
Assign 1 to factorial, and multiply it by counter inthe loop:
factorial *= counter;
Don't forget to start your counter at 1.
I will give you hint.
Have a variable initialized to 1. Let's say it as Answer.
Run a loop from 1 to Number doing the operation of Answer = Answer * loopIterationVariable. After each iteration, increment loop iteration variable by 1.
static void Main(string[] args)
{
Console.WriteLine("Enter an integer number to factorise");
int ans = 1;
int a = int.Parse(Console.ReadLine());
for (int i = 1; i <= a; i++)
{
ans = ans * i;
}
Console.WriteLine(ans.ToString());
Console.ReadLine();
}
string str = Interaction.InputBox("Enter the number to find the factorial of: ");
double counter = double.Parse(str);
long factorial = 1;
while (counter > 1)
{
factorial *= (long)counter--;//factorial = factorial * counter - 1
}
MessageBox.Show("The factorial of " + str + " is " + String.Format("{0:N}", factorial));
I used a Microsoft.VisualBasic reference for Interaction.InputBox() method
Recursive Implementation as well as basic implementation is as follows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication50
{
class Program
{
static void Main(string[] args)
{
NumberManipulator manipulator = new NumberManipulator();
Console.WriteLine("Please Enter Factorial Number:");
int a= Convert.ToInt32(Console.ReadLine());
Console.WriteLine("---Basic Calling--");
Console.WriteLine("Factorial of {0} is: {1}" ,a, manipulator.factorial(a));
Console.WriteLine("--Recursively Calling--");
Console.WriteLine("Factorial of {0} is: {1}", a, manipulator.recursively(a));
Console.ReadLine();
}
}
class NumberManipulator
{
public int factorial(int num)
{
int result=1;
int b = 1;
do
{
result = result * b;
Console.WriteLine(result);
b++;
} while (num >= b);
return result;
}
public int recursively(int num)
{
if (num <= 1)
{
return 1;
}
else
{
return recursively(num - 1) * num;
}
}
}
}
private void btnCalculate_Click(object sender, EventArgs e)
{
try
{
userinputF = Int32.Parse(txtFaculteit.Text);
for (counter = 1; counter <= userinputF; counter++)
{
answer = answer *= counter;
}
}
catch (Exception exception)
{
MessageBox.Show("Please fill in a number " + exception.Message);
}
lblAnswerFaculteit.Text = lblAnswerFaculteit.Text + "The faculty of " + userinputF + " = " + answer;
}
}
}
int userinputF;
int counter;
int answer =1;
public Form1()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
try
{
userinputF = Int32.Parse(txtFaculteit.Text);
for (counter = 1; counter <= userinputF; counter++)
{
answer = answer *= counter;
}
}
catch (Exception exception)
{
MessageBox.Show("Please fill in a number " + exception.Message);
}
lblAnswerFaculteit.Text = lblAnswerFaculteit.Text + "The faculty of " + userinputF + " = " + answer;
}
}
}