Hello had a pretty simple problem, I'm trying to create a console program in C# that gets 3 inputs from the user. The start, stop and number of steps.
It's supposed to be a for loop but I don't really get how I can put user input in the for loop, I tried making int's of the user input and then placing the names of the int's in the for loop but it's giving me errors.
The program is supposed to look like the following program in "Ovning 1" site is in Swedish but I hope you guys will get it, tried searching the site but there was never an explanation given. http://csharpskolan.se/showarticle.php?id=119
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ovning12
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Mata in Start");
int startNummer = int.Parse(Console.ReadLine());
Console.WriteLine("Mata in Stop");
int stopNummer = int.Parse(Console.ReadLine());
Console.WriteLine("Mata in Steg");
int stegNummer = int.Parse(Console.ReadLine());
for (int startNummer; startNummer >= stopNummer; startNummer + stegNummer)
{
Console.WriteLine();
}
}
}
}
static void Main(string[] args)
{
Console.WriteLine("Mata in Start");
int startNummer = int.Parse(Console.ReadLine());
Console.WriteLine("Mata in Stop");
int stopNummer = int.Parse(Console.ReadLine());
Console.WriteLine("Mata in Steg");
int stegNummer = int.Parse(Console.ReadLine());
for (int n = startNummer; n < stopNummer; n += stegNummer)
{
Console.Write(n + " ");
Console.Write("{0} ", n); //(Alternative)
}
}
a for loop should look like this
for (int i = startNummer; i <= stopNummer; i += stegNummer)
{
Console.Write(i + " ");
}
there are 3 mistakes in your current code:
for (int startNummer; startNummer >= stopNummer; startNummer + stegNummer)
you can't initialize a variable twice int startNummer; - that won't compile
your comparison heads into the wrong direction (except you're working with negative steps) startNummer >= stopNummer
you're not assigning the calculated new step here startNummer + stegNummer - it should be startNummer += stegNummer or startNummer = startNummer + stegNummer
Most of it looks okay. But couple of things do not make sense,
for (int startNummer; startNummer >= stopNummer; startNummer + stegNummer);
{
Console.WriteLine();
}
there's a semi colon ';' at the end of for loop. This ends for loop, making next curly braces syntax error. Also startNumber >= stopNumber and then startNumber + stegNumber would possibly either not run it at all, or run an infinite loop based on the inputs.
Is this for loop supposed to be like below?
for (int start = startNummer /*have to initialize the start value*/;
start < stopNummer;
start += stegNummer)
{
Console.Write(start + " "); //need Console.Write to print all numbers on same line. Console.WriteLine puts each index on its own line
}
Related
I'm new to programming and I've got confused on how to display the index number of a value in an array. I want to be able to type a random number and if the number I have entered is in the array, then it should tell me what the position (index) of the number is within the array.
For example if I enter the number 6, and 6 is in my array and it's index is 4, then the output should be "That number exists, it is positioned at 4 in the array". I've tried to do this but my code is the reverse of this, for example if I type in 6, then it looks for index 6 and outputs the number corresponding to index 6.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace searcharray
{
class Program
{
static void Main(string[] args)
{
int n = 10;
Random r = new Random();
int[] a;
a = new int[n + 1];
for (int i = 1; i <= n; i++)
a[i] = r.Next(1, 100);
for (int i = 1; i <= n; i++)
Console.WriteLine(" a [" + i + "] = " + a[i]);
Console.ReadLine();
Console.WriteLine("Enter a number: ");
int b = Convert.ToInt32(Console.ReadLine());
if (a.Contains(b))
{
Console.WriteLine("That number exists and the position of the number is: " + a[b]);
}
else
{
Console.WriteLine("The number doesn't exist in the array");
}
Console.WriteLine();
Console.ReadLine();
}
}
}
You can use Array.IndexOf(gives you the index of given value in Array) instead of a[b] like this:
if (a.Contains(b))
{
Console.WriteLine("That number exists and the position of the number is: " + Array.IndexOf(a, b));
}
else
{
Console.WriteLine("The number doesn't exist in the array");
}
You need to use Array.IndexOf() like below:
Console.WriteLine("That number exists and the position of the number is: " + Array.IndexOf(a, b));
Array.IndexOf returns -1 if the item dont exists in the array
var itemIndex = Array.IndexOf(a, b);
if (itemIndex != -1)
{
Console.WriteLine("That number exists and the position of the number is: " + itemIndex);
}
else
{
Console.WriteLine("The number doesn't exist in the array");
}
I have this code and I am trying to work out the time complexity of it when n=2, n=4 and n=6. Can anyone help me? I'm confused as how I do it? Big-O Notation please.
using System;
class TimeComplexityTest
{
public static void Main( string[] args)
{
int n;
Console.WriteLine("Please enter the value of n");
n = Int32.Parse(Console.ReadLine());
Console.Write("\n");
for (int i = 1; i <= 1.5*n; i++)
Console.WriteLine(i);
for (int i = n; i >= 1; i--)
Console.WriteLine(i);
Console.Read();
}
}
You have 2 loops: one running 1.5n times, and the other running 1n times.
The time complexity for that is 2.5n, which is O(n).
Basically I've created a times table app. At the end of the app, I've been able to say how many times I got it wrong, and how many times I got it right.
However I want it to say:
You got:
6 x 4 wrong 6 times.
5 x 2 wrong 9 times.
etc...
Rather than you got 20 correct, and 8 wrong.
So I can see the specific multiplications I got wrong. I know where I need to add the code (under the else statement). But not sure how to go about this.
I thought the best solution would be storing all the wrongs as a string in an array, then counting identical strings and outputting a number. But I have no idea how to do this.
Here's my code:
namespace TimesTablesGame
{
class multiplication
{
Random rng = new Random();
int randomNumber;
int randomNumberTables;
int c = 0;
int w = 0;
int numberOfGos = 0;
int minRangeTables;
int maxRangeTables;
int minRange;
int maxRange;
public multiplication()
{
start:
Console.Clear();
Console.WriteLine("\nPlease enter the lowest number range you would like to practice your times tables on: ");
minRangeTables = int.Parse(Console.ReadLine());
Console.WriteLine("\nPlease enter the higest number range you would like to practice your times tables on: ");
maxRangeTables = int.Parse(Console.ReadLine());
Console.WriteLine("\nPlease enter the number of times you would like play: ");
numberOfGos = int.Parse(Console.ReadLine());
Console.WriteLine("\nPlease enter the minimum range you would like to multiply by: ");
minRange = int.Parse(Console.ReadLine());
Console.WriteLine("\nPlease enter the maximum range you would like to multiply by: ");
maxRange = int.Parse(Console.ReadLine());
repeat:
Console.Clear();
for (int i = 1; i <= numberOfGos; i++)
{
randomNumberTables = rng.Next(minRangeTables, maxRangeTables + 1);
randomNumber = rng.Next(minRange, maxRange + 1);
Console.Write("\n\n{0}: {1} x {2} = ", i, randomNumberTables, randomNumber);
if (randomNumberTables * randomNumber == int.Parse(Console.ReadLine()))
{
Console.WriteLine("Correct");
c++;
}
else
{
Console.WriteLine("Wrong it is: " + randomNumberTables * randomNumber);
w++;
}
}
Console.WriteLine("\nYou were correct {0} times, and wrong {1} times.", c, w);
Console.ReadLine();
Console.WriteLine("Would you like to play again? Type y for Yes with new settings, r for repeat using last settings, and any other key to exit.");
char again = Console.ReadKey().KeyChar;
if (again == 'y')
{
c = 0;
w = 0;
goto start;
}
else if (again == 'r')
{
c = 0;
w = 0;
goto repeat;
}
}
}
}
I'd keep track in a Dictionary....
Resisting the urge to re-write the GOTO stuff.....here's a relatively simple way to do it:
Dictionary<string, int> wrongs;
//Console questions...
//Begin looping logic
wrongs = new Dictionary<string, int>();
for (int i = 1; i <= numberOfGos; i++)
{
randomNumberTables = rng.Next(minRangeTables, maxRangeTables + 1);
randomNumber = rng.Next(minRange, maxRange + 1);
string eq = String.Format("{0} x {1} = ", randomNumberTables, randomNumber);
Console.Write("{0}: " + eq, i);
if (randomNumberTables * randomNumber == int.Parse(Console.ReadLine()))
{
Console.WriteLine("Correct");
c++;
}
else
{
Console.WriteLine("Wrong it is: " + randomNumberTables * randomNumber);
if (wrongs.Any(x => x.Key == eq))
{
wrongs[eq]++;
}
else
{
wrongs.Add(eq, 1);
}
w++;
}
}
Console.WriteLine("\nYou were correct {0} times, and wrong {1} times.", c, w);
Console.WriteLine("\n\nYou got:");
foreach (var item in wrongs)
{
Console.WriteLine("{0} wrong {1} times", item.Key, item.Value);
}
//Your logic to repeat/restart
Also....note that this does not count "2 x 4" and "4 x 2" as the same equation....
Also also....You can easily do this without using GOTO....please consider it.
I'm trying to get a factorial to be displayed as for example (factorial of 5 is 5*4*3*2*1)
I'm using a method for the factorial, but it doesn't accept the line Console.Write(i + " x "); in my code.
Any help would be great.
here is my code.
//this method asks the user to enter a number and returns the factorial of that number
static double Factorial()
{
string number_str;
double factorial = 1;
Console.WriteLine("Please enter number");
number_str = Console.ReadLine();
int num = Convert.ToInt32(number_str);
// If statement is used so when the user inputs 0, INVALID is outputed
if (num <= 0)
{
Console.WriteLine("You have entered an invalid option");
Console.WriteLine("Please enter a number");
number_str = Console.ReadLine();
num = Convert.ToInt32(number_str);
//Console.Clear();
//topmenu();
//number_str = Console.ReadLine();
}
if (num >= 0)
{
while (num != 0)
{
for (int i = num; i >= 1; i--)
{
factorial = factorial * i;
}
Console.Write(i + " x ");
Console.Clear();
Console.WriteLine("factorial of " + number_str.ToString() + " is " + factorial);
factorial = 1;
Console.WriteLine("(please any key to return to main menu)");
Console.ReadKey();
Console.Clear();
topmenu();
}
}
return factorial;
}
Thank you!
The problem is that your for loop isn't using braces, so the scope is just one line.
Try adding braces appropriately:
for (int i = num; i >= 1; i--)
{
factorial = factorial * i;
Console.Write(i.ToString() + " x ");
}
Console.WriteLine("factorial of " + number_str.ToString() + " is " + factorial);
Without the braces, the i variable only exists on the next statement (factorial = factorial * i;), and no longer exists in scope by the time you call Console.Write.
You will likely also want to remove the call to Console.Clear immediately following this Write, or you will not see it.
here's a solution to consider
public static void Main()
{
Console.WriteLine("Please enter number");
int input;
while (!int.TryParse(Console.ReadLine(), out input) || input <= 0)
{
Console.WriteLine("You have enter an invald option");
Console.WriteLine("Please enter number");
}
Console.Write("Factorial of " + input + " is : ");
int output = 1;
for (int i = input; i > 0; i--)
{
Console.Write((i == input) ? i.ToString() : "*" + i);
output *= i;
}
Console.Write(" = " +output);
Console.ReadLine();
}
int.TryParse() will be beneficial for you, so the program doesn't crash if the user inputs a non-integer
also, you may want something besides an integer. Factorials get very large very fast - anything over 16 will return a wrong result.
In C# how do i ask user for starting and stopping point within the array?
Below is my code so far:
class Program
{
static void Main(string[] args)
{
double[] num = { 10, 20, 30, 40, 50 };
double n = num.Length;
Console.Write("Elements of, arrary are:" + Environment.NewLine);
for (int i = 0; i < n; i++)
{
Console.WriteLine(num[i]);
}
double sum = 0;
for (int i = 0; i < n; i++)
{
sum = sum + num[i];
}
Console.WriteLine("The sum of elements:" + sum);
Console.ReadKey();
}
}
You'll take the sum of the elements between starting and stopping point, as I guess. Take two inputs from the user and assign them to starting and ending points to the for-loop. Such as:
int startingPoint = Convert.ToInt32(Console.ReadLine());
int endingPoint = Convert.ToInt32(Console.ReadLine());
for(int i = startingPoint; i <= endingPoint; i++)
{
//take sum etc.
}
Don't forget to inform the user about the element values in the array and what input value they are entering at that moment.
Another important thing here is to control the inputs. They should be numeric and between 0-n, starting point should be smaller than ending point.
For numeric control you can write like follows:
if (int.TryParse(n, out startingPoint))
{
// operate here
}
else
{
Console.WriteLine("That's why I don't trust you, enter a numeric value please.");
}
startingPoint should be between 0-n and cannot be n. To control it:
if (startingPoint >= 0 && startingPoint < n)
{
// operate here
}
else
{
Console.WriteLine("Please enter a number between 0 and " + n + ".");
}
After taking startingPoint successfully, you should control if endingPoint. It should be between startingPoint-n. After controlling for being numeric you can write as follows:
if (endingPoint >= startingPoint && endingPoint < n)
{
// operate here
}
else
{
Console.WriteLine("Please enter a number between " + startingPoint + " and " + n + ".");
}
I don't know what can I explain more for this question. Please let me know for further problems.
If you want to prompt the user for the start and end indexes:
Console.WriteLine("Please enter start index");
string startIndexAsString = Console.ReadLine();
int startIndex = int.Parse(startIndexAsString);
Console.WriteLine("Please enter end index");
string endIndexAsString = Console.ReadLine();
int endIndex = int.Parse(endIndexAsString);
var sum = num.Skip(startIndex).Take(endIndex - startIndex + 1).Sum();