Nestled loops with IF statements c# - c#

Trying to solve a simple c# question and I did but my teacher wants me to do it with a nestled loop instead of with a boolean.
Problem: Show all numbers from input number that is divisible by 3 and 7. If no number is found show "No number found".
How i solved it with bool:
Console.WriteLine("Put in a number: ");
int nummer = int.Parse(Console.ReadLine());
bool FoundLegitNumber = false;
for (int i = 1; i <= nummer; i++)
{
if (i % 3 == 0 && i % 7 == 0)
{
FoundLegitNumber = true;
Console.WriteLine($"The number {i} is evenly divisible by 3 and 7");
}
}
if (!FoundLegitNumber)
{
Console.WriteLine("Didnt find any number...");
}
How I'm trying to solve it with a for loop:
Console.WriteLine("Put in a number: ");
int nummer = int.Parse(Console.ReadLine());
for (int i = 0; i <= nummer; i++)
{
for (int j = 0; i >= j; j++)
{
if (i % 3 == 0 && i % 7 == 0)
{
Console.WriteLine($"The number {i} is evenly divisible by 3 and 7");
}
else if (j == 0)
{
Console.WriteLine("Didnt find any number...");
break;
}
}
}
I know, it doesnt make any sense but I cant figure out how to solve it. I know that I want to give J + 1 if (i % 3 == 0 && i % 7 == 0) was not true.

If you want a method that involves a nested for without distorting the basic problem, maybe you could add a dividers array like this:
int number = 21;
int[] dividers = new int[] { 3, 7 };
for (int i = 0; i <= number; i++)
{
bool matchAllDividers = true;
for (int j = 0; j < dividers.Length; j++)
{
if (i % dividers[j] != 0)
{
matchAllDividers = false;
break;
}
}
if (matchAllDividers)
{
Console.WriteLine("The number {0} is evenly divisible by all dividers".FormatWith(i));
}
else
{
Console.WriteLine("The number {0} is not evenly divisible by all dividers".FormatWith(i));
}
}

Related

How do I print x number of integers per line and only display the odd numbers in those lines?

So far I can display the correct amount of integers per line, but I need to show only the odd numbers in the sequence. This is what I have so far:
Edited code:
for ( counter = 1; counter <= max; ++counter)
{
if( counter % 2 != 0 )
{
Console.Write(counter+"");
int printcounter = counter;
if (printcounter % 4 == 0)
{
Console.WriteLine();
}
else
{
Console.Write('\t');
}
printcounter++;
}
Console.WriteLine();
}
The output I'm getting
1
3
5
7
9
The output I'm trying to get:
1 3 5 7
9 11 13 15
Declare your printCounter variable BEFORE the loop so that it persists and correctly tracks the number of things you've printed:
public static void Main (string[] args) {
int max = 21;
int printCounter = 0;
for (int counter = 1; counter <= max; counter++)
{
if(counter % 2 != 0 )
{
Console.Write(counter + "\t");
printCounter++;
if (printCounter % 4 == 0)
{
Console.WriteLine();
}
}
}
}
You almost got it… try it like below…
int max = 100;
int printCount = 0;
for (int counter = 1; counter <= max; ++counter) {
if (counter % 2 != 0) {
Console.Write(counter + " ");
if (++printCount % 4 == 0) {
Console.WriteLine("");
}
}
}
Console.ReadKey();
Note: the line…
if (++printCount % 4 == 0) {
is shorthand for ….
printCount++;
if (printCount % 4 == 0) {
You only want to increment printCount when you print a number.

why is the output in lottery code isn't working?

I'm supposed to make a code in c# (microsoft visual studio 2017) that lets the user input six numbers, and then compare them to an array of six randomly generated numbers(with no duplicates).
If the user has one match, he's supposed to get a message saying he had one match, and different messages for two or three matches, and so on.
This is what I got so far:
static bool isValueInArray(int value, int[] a)
{
for (int i = 0; i < a.Length; i++)
{
if (a[i] == value)
{
return true;
}
}
return false;
}
static void Main(string[] args)
{
int min = 0;
int max = 6;
Random randnum = new Random();//random number generator
int[] numbers = new int[6];// generates six numbers
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = randnum.Next(min, max);//sets the numbers between 0 to 6
if(isValueInArray( i, numbers))
{
numbers[i] = randnum.Next(min, max);
}
}
try
{
Console.WriteLine("Hello and Welcome to our little game of lottery! lets see just how much luck you got!"); // greetings and instructions
Console.WriteLine("You'll now get to choose 6 different numbers between 0 to 6 to play with.");
Console.WriteLine("Go ahead and type them in.");
int[] lottery = new int[6];
for (int i = 0; i < lottery.Length; i++)
{
lottery[i] = int.Parse(Console.ReadLine()); // array to catch six numbers input
if (lottery[i] > 6)//checking if the numbers fit between 0 and 6
{
Console.WriteLine("whoops! the number you enetered isn't in range! please try again ^^");
break;
}
int x = 6;
for (int a = 0; a < lottery.Length; a++)
{
for (int b = 0; b < numbers.Length; b++)
{
if (lottery[a] == numbers[b])
{
a++;
x--;
if (x == 6)
{
Console.WriteLine("six match");
break;
}
else if (x == 5)
{
Console.WriteLine("five match");
break;
}
else if (x == 4)
{
Console.WriteLine("four match");
break;
}
else if (x == 3)
{
Console.WriteLine("three match");
break;
}
else if (x == 2)
{
Console.WriteLine("two match");
break;
}
else if (x == 1)
{
Console.WriteLine("one match");
break;
}
}
}
}
}
}
catch (FormatException)// checking if the input is in char format
{
Console.WriteLine("only numbers please!");
}
}
My problem is with the output. The program seems to go over all of the "else if" options and print all of them, instead of picking and printing just one of them.
You have everything mixed together. Write out the steps:
Generate numbers
Get input from user
Count number of matches
Print results
Each step should be performed separately.
// These should be the min/max lottery numbers
int min = 1;
int max = 100;
int numberOfLotteryNumbers = 6;
// Renamed for clarity
int[] lotteryNumbers = new int[numberOfLotteryNumbers];
int[] userNumbers = new int[numberOfLotteryNumbers];
// Step 1 - generate numbers
for (int i = 0; i < lotteryNumbers.Length; i++) {
int randomNumber;
do {
randomNumber = randnum.Next(min, max);
} while (isValueInArray(randomNumber, lotteryNumbers));
lotteryNumbers[i] = randomNumber;
}
// Step 2 - get numbers from user
for (int i = 0; i < lottery.Length; i++) {
int userInput;
do {
userInput = int.Parse(Console.ReadLine());
} while (userInput < min || userInput > max || isValueInArray(userInput, userNumbers));
userNumbers[i] = userInput;
}
// Step 3 - calc matches
int matches = 0;
for (int i = 0; i < userNumbers.Length; i++) {
if (isValueInArray(userNumbers[i], lotteryNumbers) {
matches += 1;
}
}
// Step 4 - print results
Console.WriteLine("There are {0} matches.", matches);
You may have to rearrange the code blocks in a way to get user input first, calculate the number of matches first, then display results as following code:
Note: Your approach to guarantee unique numbers in the randomly generated number ain't going to work as you expect to, you are passing "i" where you may want to pass "numbers[i]" instead to the isValueInArray" function. Let aside the idea that you will always end with values 0-5 in the array since you want 6 numbers.
int min = 0;
int max = 6;
Random randnum = new Random();//random number generator
int[] numbers = new int[6];// generates six numbers
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = randnum.Next(min, max);//sets the numbers between 0 to 6
if (isValueInArray(i, numbers))
{
numbers[i] = randnum.Next(min, max);
}
}
try
{
Console.WriteLine("Hello and Welcome to our little game of lottery! lets see just how much luck you got!"); // greetings and instructions
Console.WriteLine("You'll now get to choose 6 different numbers between 0 to 6 to play with.");
Console.WriteLine("Go ahead and type them in.");
int[] lottery = new int[6];
int x = 0;
//read user numbers
for (int i = 0; i < lottery.Length; i++)
{
lottery[i] = int.Parse(Console.ReadLine()); // array to catch six numbers input
while (lottery[i] > 6)//checking if the numbers fit between 0 and 6
{
Console.WriteLine("whoops! the number you enetered isn't in range! please try again ^^");
lottery[i] = int.Parse(Console.ReadLine()); // array to catch six numbers input
}
}
//count number of matches
for (int a = 0; a < lottery.Length; a++)
{
for (int b = 0; b < numbers.Length; b++)
{
if (lottery[a] == numbers[b])
{
//a++;
x++;
break;
}
}
}
//display results
if (x == 6)
{
Console.WriteLine("six matches");
}
else if (x == 5)
{
Console.WriteLine("five matches");
}
else if (x == 4)
{
Console.WriteLine("four matches");
}
else if (x == 3)
{
Console.WriteLine("three matches");
}
else if (x == 2)
{
Console.WriteLine("two matches");
}
else if (x == 1)
{
Console.WriteLine("one match");
}
}
catch (FormatException)// checking if the input is in char format
{
Console.WriteLine("only numbers please!");
}
Console.Read();
}
You can use a counter to achieve your goal. Just increment counter value on match:
int counter = 0;
for (int i = 0; i < lottery.Length; i++)
{
// ..
if (x == number)
{
counter++;
break;
}
// ..
}
Console.WriteLine("You have " + counter + " matches");

Input string is not in correct format error for C# program

I want to print Ready if CL (count lucky) is greater than CUL(count unlucky). My criteria is N is some number and array A is upto N. and the contents of array are checked whether individual content is even/odd. If even CL++, or else CUL++
When I tried to enter input in the format
5
1 2 3 4 5
the error is "input string is not in correct format".
I can get the output if the format of the input is
5
1
2
3
4
5
What should be changed to get the output while using earlier format?
Code:
class Program
{
static void Main(string[] args)
{
int N = int.Parse(Console.ReadLine());
if (N <= 100)
{
int[] A = new int[N];
int cL = 0; int CUL = 0;
int j;
for (j = 0; j < N; j++)
{
A[j] = Convert.ToInt32(Console.ReadLine());
if (A[j] % 2 != 0)
{
CUL++;
}
else
{
cL++;
}
}
if (cL > CUL)
{
Console.WriteLine("READY FOR BATTLE");
}
else
{
Console.WriteLine("NOT READY");
}
}
Console.ReadKey();
}
}
When input is in form of "1 2 3 4 5" (a string) you have to split it into items and parse each item into integer:
int N = int.Parse(Console.ReadLine());
String line = Console.ReadLine();
int[] A = line
.Split(new Char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(item => int.Parse(item))
.ToArray();
// given N differs from actual one
if (N != A.Length) {
// Throw an exception or re-assign N
N = A.Length;
}
// A as well as N are obtained
for (j = 0; j < N; j++)
if A[j] % 2 != 0
CUL++;
else
cL++;
if (cL > CUL)
Console.WriteLine("READY FOR BATTLE");
else
Console.WriteLine("NOT READY");

Solving with only loop

The number 124 has the property that it is the smallest number whose first three multiples contain the digit 2. Observe that
124*1 = 124, 124*2 = 248, 124*3 = 372 and that 124, 248 and 372 each contain the digit 2. It is possible to generalize this property to be the smallest number whose first n multiples each contain the digit 2. Write a function named smallest(n) that returns the smallest number whose first n multiples contain the digit 2. Hint: use modulo base 10 arithmetic to examine digits.
Its signature is
int smallest(int n)
Examples
If n is return because
4 624 because the first four multiples of 624 are 624, 1248, 1872, 2496 and they all contain the
digit 2. Furthermore 624 is the smallest number whose first four multiples contain the digit 2.
5 624 because the first five multiples of 624 are 624, 1248, 1872, 2496, 3120. Note that 624 is also
the smallest number whose first 4 multiples contain the digit 2.
6 642 because the first five multiples of 642 are 642, 1284, 1926, 2568, 3210, 3852
7 4062 because the first five multiples of 4062 are 4062, 8124, 12186, 16248, 20310, 24372, 28434.
Note that it is okay for one of the multiples to contain the digit 2 more than once (e.g., 24372).
I tried to solve this by this way
//Its a incomplete code
public static int smallest(int n)
{
int i = 1;
for (; ; )
{
int temp = 0;
int myNum = 0;
for (int j = 1; j <= n; j++)
{
myNum = i * j;
//check for condition
}
//if condition ture break
}
}
But I am stick to the problem is I cannot create hard coded n times variable.. Can you help me proceed that?
You may assume that such a number is computable on a 32 bit machine, i.e, you do not have to detect integer overflow in your answer.
using System;
using System.Collections.Generic;
namespace firstconsoleproject
{
class MainClass
{
public static void Main (string[] args)
{
int first=4;
int c=0;
int ax;
int ai;
Console.WriteLine ("please enter n");
ax = Convert.ToInt32( Console.ReadLine());
for (int i=11 ; ax>0 ;)
{ if (first==1)
{
c = ax+1;
i++;
}
c--;
ai=i*c;
for (int ten=10 ; ; )
{
if(ai%ten==2)
{
first=0;
break;
}else if (ai==0)
{
first=1;
break;
}
ai/=10;
}
if (c==0){Console.WriteLine("number is "+i);break;}
}Console.ReadKey ();
}
}
}
// Function smallest n
public int smallest(int a)
{
int temp = 0, holder = 0, k = 0;
if (a <= 0) return 0;
else
{
for (int i = 100; i < Int16.MaxValue; i++)
{
int count = 0;
k = 0;
int[] array = new int[a];
for (int j = 1; j < 9; j++)
{
holder = i * j;
temp = holder;
while (temp > 0)
{
int rem = temp % 10;
if (rem == 2)
{
count++;
if (k < a)
{
array[k] = j;
k++;
break;
}
}
temp /= 10;
}
if (count == a)
{
int countTemp = 0;
for (int h = 0; h < a; h++)
{
if (h + 1 < a)
{
if (array[h + 1] == array[h] + 1 && array[0] == 1 && array[h] > 0)
{
countTemp++;
if (countTemp == a - 1)
return i;
}
}
}
}
}
}
}
return 0;
}
public static int smallest(int n)
{
int i = 1;
for (; ; )
{
int contain = 0;
int temp = 0;
int myNum = 0;
for (int j = 1; j <= n; j++)
{
myNum = i * j;
temp = myNum;
while (true)
{
if (temp % 10 == 2)
{
contain++;
break;
}
temp = temp / 10;
if (temp <= 0)
break;
}
}
if (contain == n)
break;
i++;
}
return i;
}

"myList.Count" is less then the amount of elements inside the list

I have a task to write a program that takes some numbers and step as input. Then it must make a sequence of binary representation of those numbers and destroy bits at positions 1, 1*step, 2*step, 3*step... Here is the code:
using System;
using System.Collections.Generic;
class BitKiller
{
static void Main()
{
int
amountNumbers = int.Parse(Console.ReadLine()),
step = int.Parse(Console.ReadLine()),
counter = 0,
number = 0
;
int[]
numBin= new int[8],
numbers = new int[amountNumbers]
;
var sequence = new List<int>();
for(int i = 0; i < amountNumbers; i++)
{
numbers[i] = int.Parse(Console.ReadLine());
numBin = ToBin(numbers[i]);
sequence.InsertRange(counter * 8, numBin);
foreach(int b in sequence)
{
Console.Write(b);
}
Console.WriteLine("");
counter++;
}
if(step == 1)
{
Console.WriteLine(0);
return;
}
for(int i = sequence.Count; i >= 0; i--)
{
if(i % step == 1)
{
sequence.RemoveAt(i);
}
}
Console.WriteLine("List count = {0}", sequence.Count);
if(sequence.Count % 8 != 0)
{
int padding = 8 - (sequence.Count % 8);
for(int i = 0; i < padding; i++)
{
sequence.Add(0);
}
}
foreach(int b in sequence)
{
Console.Write(b);
}
Console.WriteLine("");
for(int i = 7, power = 0, y = 0; y < sequence.Count; i--, y++, power++)
{
number = number + (sequence[i]) * ToPower(2, power);
if(i == 0)
{
Console.WriteLine("Result = {0}", number);
sequence.RemoveRange(0, 8);
foreach(int b in sequence)
{
Console.Write(b);
}
Console.WriteLine("");
number = 0;
i = 7;
y = 0;
power = 0;
}
}
}
static int[] ToBin(int number)
{
var binSequence = new int[8];
for(int i = 7; i >= 0; number /= 2, i--)
{
if(number % 2 == 0 || (number == 0 && i >= 0))
{
binSequence[i] = 0;
}
else
{
binSequence[i] = 1;
}
}
return binSequence;
}
static int ToPower(int number, int power)
{
int numberReturn = number;
if(power == 0)
{
return 1;
}
if(number == 1)
{
return number;
}
for(int i = 0; i < power - 1; i++)
{
numberReturn = numberReturn * number;
}
return numberReturn;
}
}
Now, there are a couple of extra print lines so you can see the binary numbers coming up as you input numbers. In short my program converts the numbers to lists containing only '1' and '0' and then removes values from this list according to my formula. My main question is why is:
sequence.Count
returning 22, when there are obviously 24 '1's inside the list. Test it with the following input: 3,19,255,255,255. The Result will be: 255, 254, 252, while the correct output would be 255, 255, 252.
It is happening, because of this code:
if(sequence.Count % 8 != 0)
{
int padding = 8 - (sequence.Count % 8);
for(int i = 0; i < padding; i++)
{
sequence.Add(0);
}
}
Because the sequence.Count is 22 ( why? ) the condition is true and the following for loop is replacing my last two '1's with 2 zeros. Which is causing the wrong output. So back to the point. Why is sequence.Count equal to 22, when there are 24 '1's in the list.
Sorry, if it is a bit long and confusing, but I posted the whole code, because I have no idea what and how could be interfering to cause this issue.
You are removing two items from the list in this code:
for(int i = sequence.Count; i >= 0; i--)
{
if(i % step == 1)
{
sequence.RemoveAt(i);
}
}
With the example input you gave, sequence.RemoveAt is being called when i == 20 and when i == 1. There were 24 items, then you removed 2 of them.
Duly noted: A whole day into programming affects my basic calculus. The list count and if conditions are both performing properly. After another hour of testing I realized that the problem was that I need to set both 'y' and 'i' to - 1 value, because they are incrementing instantly by 1 when they hit the for loop. Thanks for the tips.

Categories

Resources