At the moment I am learning loops. I am trying to create a console application which uses a do while loop to print all odd integers between 20 and 0.
Why when I uncomment if statement below my code does not print anything and never finishes?
using System;
class Program
{
static void Main(string[] args)
{
int i = 20;
do
{
// if (i%2 !=0)
{
Console.WriteLine(
"When counting down from 20 the odd values are: {0}", i--);
}
} while (i >=0);
}
}
I think the main issue you're having is that the decrement (i--) only occurs inside the if block. That means when the condition fails, you will enter an infite loop. You can move the decrement outside the if block to fix that. Try this:
Console.Write("When counting down from 20 the odd values are: ");
do
{
if (i % 2 != 0)
{
Console.Write(" {0}", i);
}
i--;
} while (i >= 0);
I also moved the first Console.Write outside the loop to reduce redundancy in the output. This will produce:
When counting down from 20 the odd values are: 19 17 15 13 11 9 7 5 3 1
A for loop may be easier to follow:
Console.WriteLine("When counting down from 20 the odd values are: ");
for( int i = 20; i >= 0; i--)
{
if (i%2 !=0)
{
Console.Write(" " + i);
}
}
Sorry, I know this is really old and the initial question was for a DO not a FOR, but I wanted to add what I did to accomplish this outcome. When I Googled the question initially, this is what was returned first despite my query being for a FOR loop. Hopefully someone down the road will find this helpful.
The below will print the odd number index of an array - in this case, Console App args.
using System;
namespace OddCounterTest
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < args.Length; i++)
{
Console.WriteLine(i);
i++;
}
}
}
}
Output with 6 arguments will be:
1
3
5
Moving i++ to the first step in the for loop will get you the even numbers.
using System;
namespace EvenCounterTest
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < args.Length; i++)
{
i++;
Console.WriteLine(i);
}
}
}
}
Output will be:
2
3
4
This is setup so you can get the also actual values of the args too rather than simply the count and print of the args index. Just create a string and set the string to args[i]:
string s = args[i];
Console.WriteLine(s);
If you need to count and exclude "0" in the event your are printing numbers like the question initially asks, then setup your for loop like so:
for (int i = 1; i <= args.Length; i++);
Notice how "i" is initially set to 1 in this example and i is less than or equal to the array length rather than simply less than. Be mindful of your less than and less than/equal to's or you will get OutOfRangeExceptions.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Do_while_Test
{
class Program
{
static void Main(string[] args)
{
int i = 20;
Console.WriteLine();
Console.WriteLine("A do while loop printing odd values from 20 - 0 ");
do
{
if (i-- %2 !=0)
{
Console.WriteLine("When counting down from 20 the odd values are: {0}", i--);
}
} while (i >=0);
Console.ReadLine();
}
}
}
Related
This question already has answers here:
Check if a value is in an array (C#)
(10 answers)
Closed 4 years ago.
I'm working on a problem and i've tried it every way I can think of with a for loop but i can't figure out how to make it work as I only started on c# and programming as a whole a few weeks ago.
Write an app that inputs five numbers. As each number is read search the array if the number doesn’t exist in the array output the word “new” and insert the number into the array. If the number does exist in the array output “exists”. Once all five numbers have been entered output the content of the array.
This is what I have so far. Thanks for any help
using System;
public class Program
{
// Main method begins execution of C# application
public static void Main(string[] args)
{
int[] array = new int[5];
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("Enter a number:");
array[i] = Convert.ToInt32(Console.ReadLine());
for (int a = 0; a < 5; a++)
{
if (array[i] != array[a])
{
array[i] = int.Parse(Console.ReadLine());
Console.WriteLine("new\n");
}
}
array[i] = int.Parse(Console.ReadLine());
Console.WriteLine("exists\n");
}
Console.WriteLine(array);
Console.ReadKey();
}
} // end class
First of all try thinking about a solution before you actually start writing some code, couple of hints
You expect some user input, we will use a variable to save the user input
You need to validate that the values does not exist in you array or structure, this can be done using the Contains method.
If it exists we continue to the next user input and print the required message.
If the value does not exists we add the value and print the new message
We will do this until the Count of the structure is equal to 5.
for reference use this While loop, Hashset.Contains and Hashset
try this:
var numbers = new HashSet<int>();
while(numbers.Count < 5)
{
Console.WriteLine("Enter a number:"); //1.
var number = Convert.ToInt32(Console.ReadLine());
if (numbers.Contains(number)) // 2.
{
Console.WriteLine("exists\n"); //3.
continue;
}
Console.WriteLine("new\n"); //4.
numbers.Add(number);
}
foreach (var n in numbers)
{
Console.WriteLine(n);
}
Use .Any() in System.Linq. Also, you don't need to continuously grab user input in your loop:
using System;
using System.Linq;
public class Program
{
// Main method begins execution of C# application
public static void Main(string[] args)
{
int[] array = new int[5];
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("Enter a number:");
// Get user input and convert to integer:
int input = Convert.ToInt32(Console.ReadLine());
// Check if given input is already in the array:
if (! array.Any(number => number == input))
{
array[i] = input;
Console.WriteLine("new\n");
}
else
{
Console.WriteLine("exists\n");
}
}
// Print the contents of array separated by ','
Console.WriteLine(string.Join(", ", array));
Console.ReadKey();
}
}
Edit: Another variant if you want the user to fill the array completely:
using System;
using System.Linq;
public class Program
{
public static void Main(string[] args)
{
// Btw, if this is not an array of nullables,
// we will not be able to insert a zero later, as
// we will treat them as duplicates.
int?[] array = new int?[5];
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("Enter a number:");
int input = 0;
bool duplicateAttempt = false;
do {
// Get and convert the input.
input = Convert.ToInt32(Console.ReadLine());
// See if this number is already in.
duplicateAttempt = array.Contains(input);
// Report if we attempt to insert a duplicate.
if (duplicateAttempt) Console.WriteLine("exists");
}
while (duplicateAttempt); // Keep asking while we don't get a unique number.
array[i] = input; // Store the number
Console.WriteLine("new");
}
// Print the contents of array separated by ','
Console.WriteLine(string.Join(", ", array));
Console.ReadKey();
}
}
A couple of issues with your code. You should only increment the array index if successful - otherwise the missing values will be zero. It's also a good idea to validate the input in case the user entered an invalid value. You can use linq to check if the value already exists in the array:
Here's an example:
static void Main(string[] args)
{
int[] array = new int[5];
var index = 0;
while (index < array.Length)
{
Console.WriteLine("Enter a number:");
var input = Console.ReadLine();
var value = 0;
if (!int.TryParse(input, out value))
{
Console.WriteLine("Error - value entered was not a number");
}
else
{
var match = array.Where(a => a == value);
if (match.Any())
{
Console.WriteLine("exists\n");
}
else
{
array[index] = value;
Console.WriteLine("new\n");
index++;
}
}
}
foreach (var item in array)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
This appears to be a homework question, so I think it's more helpful to explain what you've done wrong and tell you what you should do...
It won't help you learn to copy and paste other people's answers.
using System;
public class Program
{
// Main method begins execution of C# application
public static void Main(string[] args)
{
int[] array = new int[5];
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("Enter a number:");
// you are putting the value into your array here. so it will always 'exist' below
array[i] = Convert.ToInt32(Console.ReadLine());
// you need to do this check before you insert the number into the array
// put the ReadLine into a variable, not directly into the array.
// then check if it's in the array already
for (int a = 0; a < 5; a++)
{
if (array[i] != array[a])
{
// here you are trying to read another value from the user.
// Console.ReadLine() will always wait for user input
// use the variable from above. but only after you have looped through all the items.
// and verified that it is not present
array[i] = int.Parse(Console.ReadLine());
Console.WriteLine("new\n");
}
}
// this is the third time you have assigned the number to the array
// and the third time you've asked for user input per loop
array[i] = int.Parse(Console.ReadLine());
Console.WriteLine("exists\n");
}
Console.WriteLine(array);
Console.ReadKey();
}
} // end class
To summarize:
you need a for loop that runs 5 times.
The for loop will do the following:
assign the user input to a variable
loop through your array (second loop) and see if it contains this variable
if the number is found, set a boolean to true. (found)
if after the loop is over, found = false, then print false
also add the number to the array (at the index of the outer loop is fine)
I am trying to get input from user 5 times and add those values to marks array;
Then, it will calculate the average and print positive or negative accordingly. However, I can not take input from the user it just prints "Enter 5 elements". After getting input from user how can I add them to marks array? Any tips would be helpful.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
double average =0;
int [] marks = new int[] { };
for (int a = 0; a < 5; a++){
Console.WriteLine("Enter 5 elements:");
string line = Console.ReadLine();
Console.WriteLine(line);
}
for (int i = 0; i < marks.Length; i++){
average = marks.Average();
}
if(average>0){
Console.WriteLine("Positive");
}else{
Console.WriteLine("Negative");
}
}
}
I would use a while loop combined with int.TryParse to check if the user input is a number. Also it doesn't make any sense to put average = marks.Average(); inside a for loop, because LINQ Average calculates the average of a collection (in your case the marks array).
static void Main()
{
int[] marks = new int[5];
int a = 0;
Console.WriteLine("Enter 5 elements:");
while (a < 5)
{
if (int.TryParse(Console.ReadLine(), out marks[a]))
a++;
else
Console.WriteLine("You didn't enter a number! Please enter again!");
}
double average = marks.Average();
if (average > 0)
Console.WriteLine("Positive");
else
Console.WriteLine("Negative");
}
DEMO HERE
Edited my answer to illustrate solving your problem without a for loop.
class Program
{
const int numberOfMarks = 5;
static void Main()
{
List<int> marks = new List<int>();
Enumerable.Range(1, numberOfMarks)
.ForEach((i) => {
Console.Write($"Enter element {i}:");
marks.Add(int.TryParse(Console.ReadLine(), out var valueRead) ? valueRead : 0);
Console.WriteLine($" {valueRead}");
});
Console.WriteLine(marks.Average() >= 0 ? "Positive" : "Negative");
}
}
This will help you, just copy and paste it.
There are some explanation with comments.
class Program
{
static void Main()
{
const int numberOfMarks = 5;
int[] marks = new int[numberOfMarks];
Console.WriteLine("Enter 5 elements:");
for (int a = 0; a < numberOfMarks; a++)
{
// If entered character not a number, give a chance to try again till number not entered
while(!int.TryParse(Console.ReadLine(), out marks[a]))
{
Console.WriteLine("Entered not a character");
}
Console.WriteLine("You entered : " + marks[a]);
}
// Have to call Average only once.
var avg = marks.Average();
Console.WriteLine(avg > 0 ? "Positive average" : "Negative average");
Console.ReadLine();
}
}
Follow Stackoverflow Answer
since integer array is being used, and as input from the console is a string value, you need to convert it using Parse() Method. For e.g.
string words = "83";
int number = int.Parse(words);
Edit: using string variable in parsing.
I am trying to create a console application where the user inputs a base 10 number and the program outputs the number in binary.
I want to get the exact number of times to execute the for loop to get correct value (the value HERE in the code below).
I also have to reverse everything that the console is now outputting for everything to be correct but that I can do on my own later.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Decimal_to_Binary
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter a number and the computer will convert it into binary.");
string NumberIn = Console.ReadLine();
decimal Number = Decimal.Parse(NumberIn);
decimal[] Squared = new decimal[100];
for (int i = 0; i < HERE + 1; i++)
{
//Squared[i] = Math.Pow(2, i);
Squared[i] = 2 ^ i ;
if (Number == Squared[i])
{
Console.Write("1");
}
else
{
Console.Write("0");
}
}
Console.ReadKey();
}
}
}
A nice feature of logarithms is that they'll tell you the highest order bit (in the case of log2) or digit that is set for any number. You can use log2 to find out the highest order bit set and then shift the number repeatedly checking for the 0th bit and print the binary representation.
using System;
using System.Text;
namespace BinaryCount
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter a number and the computer will convert it into binary.");
string NumberIn = Console.ReadLine();
int Number = Int32.Parse(NumberIn);
double loopCount = Math.Log(Number, 2); // Log2 of a number will tell you the highest order bit that's set
StringBuilder s = new StringBuilder();
for (int i = 0 ; i < loopCount ; ++i)
{
if (Number % 2 == 1)
s.Append("1");
else
s.Append("0");
Number = Number >> 1;
}
StringBuilder done = new StringBuilder();
for (int i = s.Length - 1 ; i >= 0 ; i--)
{
done.Append(s[i]);
}
Console.WriteLine(done);
Console.ReadLine();
}
}
}
I am trying to make a program that calculates some specific data from numbers given by a user.
In this example, my program counts amount of numbers in range (10,103) that are divisible by 2, and amount of numbers that are in range (15,50) divisible by 3 within numbers given by user.
On this stage, my program gives the results, when 10 numbers are given (as I specified it in the loop). How can I make my program stop reading numbers and give the results when user imputs an empty line no matter if he, entered 5 or 100 numbers before?
Here is my code, as it looks for now:
using System;
namespace Program1
{
class MainClass
{
public static void Main (string[] args)
{
int input10_103_div_2 = 0;
int input15_50_div_3 = 0;
for (int i = 0; i < 10; i++)
{
string input = Console.ReadLine ();
double xinput = double.Parse (input);
if (xinput > 10 && xinput <= 103 && (xinput % 2) == 0)
{
input10_103_div_2++;
}
if (xinput > 15 && xinput < 50 && (xinput % 3) == 0)
{
input15_50_div_3++;
}
}
Console.WriteLine ("Amount of numbers in range (10,103) divisible by 2: " + input10_103_div_2);
Console.WriteLine ("Amount of numbers in range (15,50) divisible by 3: " + input15_50_div_3);
}
}
}
instead of for, do:
string input = Console.ReadLine();
while(input != String.Empty)
{
//do things
input = Console.ReadLine();
}
if you're trying to allow any number of inputs. Or
if(input == "")
break;
if you want the for loop
Change your loop to go forever and break out of the loop when the string is empty:
for (;;)
{
string input = Console.ReadLine ();
if (String.IsNullOrEmpty(input))
{
break;
}
// rest of code inside loop goes here
}
If you want to restructure the loop, you can use a do while loop:
string input;
do{
input = Console.ReadLine();
//stuff
} while(!string.IsNullOrEmpty(input));
If you just want to be able to break early:
string input = Console.ReadLine ();
if(string.IsNullOrEmpty(str))
break;
double xinput = double.Parse (input);
Below is a program that I wrote to practice some C# basics and principles.
This program asks the user for how large they want an int array to be, then to fill the array and finally return the average of the individual elements of the array.
I know that I can do this using LINQ but since I'm learning I need to learn the nuts and bolts way.
As it stands, the method I wrote doesn't return anything to the console, can someone give me a clue as to what's wrong with it?
There's also a comment near one of the for loops that I need some help understanding why it's behaving that way.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _9_21_Test
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("enter the amount of numbers you would like to find the average of: ");
int arraylength = Int32.Parse(Console.ReadLine());
int[] AverageArray = new int[arraylength];
////filling the array with user input
for (int i = 0; i < AverageArray.Length; i++)
{
Console.Write("enter the numbers you wish to find the average for: ");
AverageArray[i] = Int32.Parse(Console.ReadLine());
}
//printing out the array, without the -1 the array prints out more one number than it should, don't know why
Console.WriteLine("here is your array: ");
for (int i = 0; i < AverageArray.Length -1 ; i++)
{
Console.WriteLine(AverageArray[i]);
}
Console.WriteLine(Calcs.FindAverage(AverageArray));
Console.ReadLine();
}
}
//Method to find the average is another class for learning porpoises
class Calcs
{
public static double FindAverage(int[] averageNumbers)
{
int arraySum = 0;
for (int i = 0; i < averageNumbers.Length; i++)
arraySum += averageNumbers[i];
return arraySum / averageNumbers.Length;
}
}
}
I've tried debugging, your code is working OK. It's just you don't need the ArrayLength-1 in the second loop. Use ArrayLength instead.
static void Main(string[] args)
{
Console.WriteLine("enter array length ");
int arraylength = Int32.Parse(Console.ReadLine());
int[] AverageArray = new int[arraylength];
for (int i = 0; i < AverageArray.Length; i++)
{
Console.Write("enter the numbers you wish to find the average for: ");
AverageArray[i] = Int32.Parse(Console.ReadLine());
}
Console.WriteLine("here is your array: ");
for (int i = 0; i < AverageArray.Length ; i++)
{
Console.WriteLine(AverageArray[i]);
}
Console.WriteLine("here is the result");
Console.WriteLine(Calcs.FindAverage(AverageArray));
Console.ReadLine();
}
Well I think Visual Studio C#(Sharp) Will give you an error on the second statement of code before the for loop,Because the Array uses the constant variable for the index size.
Console.WriteLine("enter array length ");
const int arraylength = Int32.Parse(Console.ReadLine());
int[] AverageArray = new int[arraylength];
also Check Calcs does not exist in the current context.