I am trying to achieve the following:
User enters 100 numbers and then the numbers are printed in 3 columns.
This is what I have so far, it works but it does not print the last value of the array.
What am I doing wrong?
static void Main(string[] args)
{
int digit = 0;
const int LIMIT = 100;
int[] row = new int[LIMIT];
for (int i = 0; i < row.Length; i++)
{
Console.WriteLine("Geef getal nummer " + (i + 1) + " in: ");
digit = int.Parse(Console.ReadLine());
row[i] = digit;
}
for (int i = 0; i < row.Length - 2; i+=3)
{
Console.WriteLine(row[i] + "\t" + row[i + 1] + "\t" + row[i + 2]);
}
}
Use this print instead
for (int i = 0; i < row.Length; i++)
{
Console.Write(row[i] + "\t");
if (i % 3 == 2)
Console.WriteLine();
}
Your issue is that you don't simply use Console.Write, and try to write your lines in one shot.
In fact, it would be even cleaner to use a StringBuilder here.
Replace
for (int i = 0; i < row.Length - 2; i+=3)
{
Console.WriteLine(row[i] + "\t" + row[i + 1] + "\t" + row[i + 2]);
}
by
StringBuilder sb = new StringBuilder();
int count = 0;
for (int i = 0; i < row.Length; i++)
{
count++;
if (count == 3)
{
sb.AppendLine(row[i])
count = 0;
}
else
sb.Append(row[i]).Append('\t');
}
Console.WriteLine(sb.ToString());
I think it's pretty explicit, but if you need clarifications, feel free to ask. Of course, the use of count here is pretty scholar, a real program could use % operator, like shown in other answers.
You have wrong condition in for loop. If you don't mind LINQ, you can use the following:
foreach (string s in row.Select((n, i) => new { n, i })
.GroupBy(p => p.i / 3)
.Select(g => string.Join("\t", g.Select(p => p.n))))
Console.WriteLine(s);
If you're not ok with LINQ, you can do this:
int colIndex = 0;
foreach (int n in row)
{
Console.Write(n);
if (colIndex == 2)
Console.WriteLine();
else
Console.Write('\t');
colIndex = (colIndex + 1) % 3;
}
jonavo is correct.
after 96+3 = 99
and you have done row.length-2, change it to row. length+2.
and in print dont print if the i+1 or I+2 >= max
It doesn't print it because 100 is not evenly divisible by 3 and your for-loop increases the variable by 3 on each iteration, so the last element wil be skipped.
Maybe this after the loop:
int rest = row.Length % 3;
if(rest > 0)
Console.WriteLine(row[row.Length - rest] + "\t" + row.ElementAtOrDefault(row.Length - rest + 1));
Its because of your index.
Your running index i goes from
0, 3, 6, 9, ... 96, 99
So this would output the array positions:
0,1,2 3,4,5 6,7,8 9,10,11 ... 96,97,98 99,100,101 (index out of bounds)
row.Length equals 100, so your loop-condition (i < row.Length - 2) is correct, but even better would be (i < row.Length - 3).
So your problem is how to print the last number... You see, you have 3 columns for 100 digits. This makes 33 rows and than there is one digit left.
Maybe you just add some Console.WriteLine(row[row.Length-1]); beneeth your loop.
Looks like you've got a lot of options at your disposal. Here's an approach using nested loops:
int numCols = 3;
for (int i = 0; i < row.Length; i += numCols)
{
for (int j = i; j < i + numCols && j < row.Length; j++)
{
Console.Write(row[j] + "\t");
}
Console.WriteLine();
}
Try this code.
Using this loop you can also change the number of rows/columns without code changes. Also, using the temporary buffer you output to the console an entire row at a time.
static void Main(string[] args)
{
int digit = 0;
const int LIMIT = 10;
const int COLS = 3;
int[] row = new int[LIMIT];
for (int i = 0; i < row.Length; i++)
{
Console.WriteLine("Geef getal nummer " + (i + 1) + " in: ");
// Re-try until user insert a valid integer.
while (!int.TryParse(Console.ReadLine(), out digit))
Console.WriteLine("Wrong format: please insert an integer number:");
row[i] = digit;
}
PrintArray(row, COLS);
// Wait to see console output.
Console.ReadKey();
}
/// <summary>
/// Print an array on console formatted in a number of columns.
/// </summary>
/// <param name="array">Input Array</param>
/// <param name="columns">Number of columns</param>
/// <returns>True on success, otherwise false.</returns>
static bool PrintArray(int[] array, int columns)
{
if (array == null || columns <= 0)
return false;
if (array.Length == 0)
return true;
// Build a buffer of columns elements.
string buffer = array[0].ToString();
for (int i = 1; i < array.Length; ++i)
{
if (i % columns == 0)
{
Console.WriteLine(buffer);
buffer = array[i].ToString();
}
else
buffer += "\t" + array[i].ToString();
}
// Print the remaining elements
if (array.Length % columns != 0)
Console.WriteLine(buffer);
return true;
}
Just for completeness
Note that int.Parse(Console.ReadLine()) can throw an Exception if unexpected characters are typed. It's better to use int.TryParse() as documented here. This method don't throw an exception but return a boolean that report a successful conversion.
while (!int.TryParse(Console.ReadLine(), out digit))
Console.WriteLine("Wrong format: please insert an integer number:");
This code tell the user that the typed string can't be interpreted as an integer and prompt again until a successful conversion is done.
Related
I found this code that i need for an assigment, but it only reads odd numbers and i need it to read even numbers too, but i don't know whats wrong. I need it to make the random magic squares go from 1 to 10.
Still very much a beginner and don't understand functions yet, please let me know if there is a way to dolve this.
using System;
class GFG
{
// Function to generate odd sized magic squares
static void generateSquare(int n)
{
int[,] magicSquare = new int[n, n];
// Initialize position for 1
int i = n / 2;
int j = n - 1;
// One by one put all values in magic square
for (int num = 1; num <= n * n;)
{
if (i == -1 && j == n) // 3rd condition
{
j = n - 2;
i = 0;
}
else
{
// 1st condition helper if next number
// goes to out of square's right side
if (j == n)
j = 0;
// 1st condition helper if next number is
// goes to out of square's upper side
if (i < 0)
i = n - 1;
}
// 2nd condition
if (magicSquare[i, j] != 0)
{
j -= 2;
i++;
continue;
}
else
// set number
magicSquare[i, j] = num++;
// 1st condition
j++;
i--;
}
// print magic square
Console.WriteLine("The Magic Square for " + n
+ ":");
Console.WriteLine("Sum of each row or column "
+ n * (n * n + 1) / 2 + ":");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
Console.Write(magicSquare[i, j] + " ");
Console.WriteLine();
}
}
// driver program
public static void Main()
{
Console.WriteLine("Value of n: ");
int n = int.Parse(Console.ReadLine());
// Works only when n is odd
generateSquare(n);
}
}
Step through the program with a debugger. Using n = 2 as an example, on your second loop through the for loop you get to this with i = 1 and j = 1:
if (magicSquare[i, j] != 0)
{
j -= 2;
i++;
continue;
}
And that makes i = 2 on the next loop through. Because there is no 2 index in the array you have created, it crashes when it gets to this same check the next loop.
Presumably odd numbers are working because they are getting floored on division (in the case of n = 5 -> i = 2).
That should be enough to point you in the right direction.
can you help me to create a logic for magic square metric. In given example, I have created a code for generate Magic Square for odd numbers like 3x3, 5x5, 7x7 metric and double even numbers like 4×4 , 8×8 but unable to found a proper solution for create single even value magic square metric like 6x6, 10x10 etc.
In current implementation anyone can enter a number (n) in input and it will create a nxn magic square metric. But not working fine with single even numbers
class Program
{
public static void Main(string [] args )
{
Console.WriteLine("Please enter a number:");
int n1 = int.Parse(Console.ReadLine());
// int[,] matrix = new int[n1, n1];
if (n1 <= 0)
{
Negativ();
}
else if (n1 == 2)
{
Zwei();
}
else if ((n1 != 2) && !(n1 < 0) && (n1 % 2 != 0))
{
Odd (n1 );
}
else if ((n1 != 2) && !(n1 < 0) && ((n1 - 2) % 4 == 0))
{//singl Even
SingleEven(n1);
}
else if ((n1 != 2) && !(n1 < 0) && (n1 % 4 == 0))
{
DoubleEven (n1);
}
}
private static void Negativ(){
Console.WriteLine("Sorry, the number must be positive and greater than 3 ");
Console.ReadLine();
}
public static void Zwei(){
Console.WriteLine("Sorry,there is no magic square of 2x2 and the number must be and greater than 3 ");
Console.ReadLine();
}
public static void Odd ( int n)// odd method
{
int[,] magicSquareOdd = new int[n, n];
int i;
int j;
// Initialize position for 1
i = n / 2;
j = n - 1;
// One by one put all values in magic square
for (int num = 1; num <= n * n; )
{
if (i == -1 && j == n) //3rd condition
{
j = n - 2;
i = 0;
}
else
{
//1st condition helper if next number
// goes to out of square's right side
if (j == n)
j = 0;
//1st condition helper if next number is
// goes to out of square's upper side
if (i < 0)
i = n - 1;
}
//2nd condition
if (magicSquareOdd[i, j] != 0)
{
j -= 2;
i++;
continue;
}
else
{
//set number
magicSquareOdd[i, j] = num++;
//1st condition
j++; i--;
}
}
// print magic square
Console.WriteLine("The Magic Square for " + n + " is : ");
Console.ReadLine();
for ( i = 0; i < n; i++)
{
for ( j = 0; j < n; j++)
Console.Write(" " + magicSquareOdd[i, j] + " ");
Console.WriteLine();
Console.ReadLine();
}
Console.WriteLine(" The sum of each row or column is : " + n * (n * n + 1) / 2 + "");
Console.ReadLine();
}
public static void SingleEven(int n )
{
// int n = magic .Length ;
int[,] magicSquareSingleEven = new int[n, n];
int halfN = n / 2;
int k = (n - 2) / 4;
int temp;
int[] swapcol = new int[n];
int index = 0;
int[,] minimagic = new int[halfN, halfN];
*Odd(minimagic) ;* // here is the problem
for (int i = 0; i < halfN; i++)
for (int j = 0; j < halfN; j++)
{
magicSquareSingleEven[i, j] = minimagic[i, j];
magicSquareSingleEven[i+ halfN , j+halfN ] = minimagic[i, j]+ halfN *halfN ;
magicSquareSingleEven[i, j + halfN] = minimagic[i, j] +2* halfN * halfN;
magicSquareSingleEven[i + halfN, j] = minimagic[i, j] +3* halfN * halfN;
}
for (int i =1; i< k ;i ++)
swapcol [index ++]=i ;
for (int i = n-k+2; i <= n ; i++)
swapcol[index++] = i;
for (int i =1; i<=halfN ;i ++)
for (int j = 1; j<= index ; j ++)
{
temp = magicSquareSingleEven[i - 1, swapcol[j - 1] - 1];
magicSquareSingleEven[i-1,swapcol[j-1]-1]=magicSquareSingleEven[i +halfN-1,swapcol[j-1]-1];
magicSquareSingleEven[i+halfN-1,swapcol[j-1]-1]=temp;
}
//swaping noses
temp=magicSquareSingleEven[k,0];
magicSquareSingleEven[k,0]=magicSquareSingleEven[k+halfN,0];
magicSquareSingleEven[k+halfN,0]=temp;
temp=magicSquareSingleEven[k+halfN,k];
magicSquareSingleEven[k+halfN,k]=magicSquareSingleEven[k,k];
magicSquareSingleEven[k,k]=temp;}
//end of swaping
// print magic square
Console.WriteLine("The Magic Square for " + n + " is : ");
Console.ReadLine();
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
Console.Write(" " + magicSquareSingleEven[i, j] + " ");
Console.WriteLine();
Console.ReadLine();
}
Console.WriteLine(" The sum of each row or column is : " + n * (n * n + 1) / 2 + "");
Console.ReadLine();
}
I need help with C#
I'm currently trying to find the minimum value in a 2D array. I have managed to do this however, after I have found the minimum value I want the corresponding values index number (Where it is stored in my 2D array) to be output. For example, I have a 2D and a 1D array. Once the minimum value has been discovered the index value for the 2D array needs to be changed in the 1D array.
The 2d array is c[i,j]
and the 1D array is a[i]
so how would i be able to display the j number in my c array in my a array. For example, if my minimum value was at c[1,5] I want the value in a[5] to be changed from 0 to 1. Any help would be great thanks!
P.S. if ive made this sound really confusing I apologise I'm new to this !
int n = 5, m = 10, MinValue = 100, MaxValue = 1, Total = 0, Sum = 0; //n = number of values m = max value in array MinValue = Lowest number in array
Random Rand = new Random();
int[] A = new int[n + 1];
for (int i = 1; i < n+1; i++) //Reached and unreached array - creation
{
A[i] = 0;
}
A[1] = 1;
int[,] c = new int[n + 1, n + 1]; //Create array
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
c[i, j] = Rand.Next(1, m); //Randomise the array
if (i == j)
{
c[i, j] = 99; // give void spaces the value of 99
}
if (c[i, j] > MaxValue && c[i, j] < 99)
{
MaxValue = c[i, j]; // max value takes the highest value (that isnt 99)
}
}
}
for (int p = 1; p <= n; p++)
{
for (int i = 1; i <= n+1; i++)
{
for (int j = 1; i <= n+1; i++)
{
if (c[i, j] <= MinValue)
{
if (A[i] == 1)
{
if (A[i] == 0)
{
Total = Sum + MinValue;
Sum = Total;
A[i] = 1;
}
}
}
}
}
}
Console.WriteLine("Total Value = " + Total);
Console.WriteLine("");
Console.WriteLine("The tracking array - what has been reached and what hasn't"); // Output reaching array
Console.WriteLine("");
for (int i = 1; i <= n; i++)
{
Console.WriteLine("A[" + i + "] = " + A[i].ToString("00") + " ");
//Output the array to screen
}
Console.WriteLine("");
Console.WriteLine("The link length array"); // Output link length array
Console.WriteLine("");
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
Console.Write("c[" + i + "," + j + "] = " + c[i, j].ToString("00") + " ");
}
Console.WriteLine();
//Output the array to screen
}
Console.WriteLine("");
Console.ReadLine();
I am having a hard time with a program I need to write. The requirements are that the user enters in the size of the Array. Then they enter the elements of the array after this the program needs to display the values entered then how many times each value occurs. While everything seems to work except its not display the "occurs" part properly. Lets say "1 1 2 3 4" is entered (Array size being 5) It prints
1 occurs 1 time.
1 occurs 1 time.
2 occurs 1 time.
3 occurs 1 time.
4 occurs 2 times.
this isn't right because 1 occured 2 times and 4 is only 1 time. Please Help...
static void Main(string[] args)
{
int[] arr = new int[30];
int size,
count=0,
count1=0,
count2=0;
Console.Write("Enter Size of the Array: ");
size = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the elements of an Array: ");
for (int i=0; i < size; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}
Console.Write("Values Entered: \n");
for (int i = 0; i < size; i++)
{
Console.WriteLine(arr[i]);
if (arr[i] <= 10)
count++;
else
count1++;
}
for(int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if (arr[i] == arr[j])
count2++;
else
count2 = 1;
}
Console.WriteLine(arr[i] + " Occurs " + count2 + " Times.");
}
Console.WriteLine("The number of valid entries are: " + count + "\nThe number of invalid entries are: " + count1);
Console.ReadKey();
}
if you can use Linq, this is easy job:
After
Console.Write("Values Entered: \n");
add
var grouped = arr.GroupBy(x => x);
foreach (var group in grouped)
{
Console.WriteLine("number {0} occurs {1} times", group.Key, group.Count());
}
EDIT
Since OP isn't allowed to use Linq, here's array-only solution. Much more code than that dictionary approach, but with arrays only.
Console.Write("Values Entered: \n");
//an array to hold numbers that are already processed/counted. Inital length is as same as original array's
int[] doneNumbers = new int[arr.Length];
//counter for processed numbers
int doneCount = 0;
//first loop
foreach (var element in arr)
{
//flag to skip already processed number
bool skip = false;
//check if current number is already in "done" array
foreach (int i in doneNumbers)
{
//it is!
if (i == element)
{
//set skip flag
skip = true;
break;
}
}
//this number is already processed, exit loop to go to next one
if (skip)
continue;
//it hasn't been processed yes, so go through another loop to count occurrences
int occursCounter = 0;
foreach (var element2 in arr)
{
if (element2 == element)
occursCounter++;
}
//number is processed, add it to "done" list and increase "done" counter
doneNumbers[doneCount] = element;
doneCount++;
Console.WriteLine("number {0} occurs {1} times", element, occursCounter);
}
You can simply use dictionary:
static void Main(string[] args)
{
var dic = new Dictionary<int, int>();
Console.Write("Enter Size of the Array: ");
int size = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the elements of an Array: ");
for (int i = 0; i < size; i++)
{
int val = Convert.ToInt32(Console.ReadLine());
int current;
if (dic.TryGetValue(i, out current))
{
dic[val] = current + 1;
}
else
{
dic.Add(val, 1);
}
}
foreach (int key in dic.Keys)
{
Console.WriteLine(key + " Occurs " + dic[key] + " Times.");
}
Console.Read();
}
The problem is that you're resetting count2 to 1 any time you find a mismatch.
What you should do instead is set count2 to 0 in the outer loop (so it basically resets once for each item), and then let the inner loop count all the instances of that number:
// For each item 'i' in the array, count how many other items 'j' are the same
for (int i = 0; i < size; i++)
{
count2 = 0; // processing a new item, so reset count2 to 0
for (int j = 0; j < size; j++)
{
if (arr[i] == arr[j]) count2++;
}
Console.WriteLine(arr[i] + " occurs " + count2 + " times.");
}
Hey I am slightly new to C# it has been a week today. Ive managed to get this far but I cant seem to just out put the sum of the even numbers I've cubed i get the whole output and the last number is the total summed except i just want the last to show. Any help would be much appreciated and apologies for the horrendous code. Thanks
using System;
public class Test
{
public static void Main()
{
int j = 0; //Declaring + Assigning the interger j with 0
int Evennums = 0; // Declaring + Assigning the interger Evennums with 0
int Oddnums = 0; //Declaring + Assigning the interger Oddnums with 0
System.Console.WriteLine("Calculate the sum of all even numbers between 0 and the user’s number then cube it!"); //Telling console to write what is in ""
Console.WriteLine("Please enter a number");
uint i = uint.Parse(Console.ReadLine());
Console.WriteLine("You entered: " + i);
Console.WriteLine("Your number cubed: " + i*i*i);
if (i % 2 == 0)
while (j <= i * i * i)
{
if(j % 2 == 0)
{
Evennums += j; //or sum = sum + j;
Console.WriteLine("Even numbers summed together " + Evennums);
}
//increment j
j++;
}
else if(i%2 != 0)
//reset j to 0 like this: j=0;
j=0;
while (j<= i * i * i)
{
if (j%2 == 0)
{
Oddnums += j;
//Console.WriteLine(Oddnums);
}
//increment j
j++;
}
}
}
if you want to show the last sum, but not every summing process, change the location of print statement
if (i % 2 == 0)
{
while (j <= i * i * i)
{
if(j % 2 == 0)
{
Evennums += j; //or sum = sum + j;
}
//increment j
j++;
}
Console.WriteLine("Even numbers summed together " + Evennums);
}
same thing applies for the else if block.
You could try to achieve that you want like below, using LINQ:
// Calculate the cube of i.
int cube = i*i*i;
int sum = 0;
string message;
// Check if cube is even.
if(cube%2==0)
{
sum = Enumerable.Range(0,cube).Where(x => x%2==0).Sum();
message = "The sum of the even numbers in range [0,"+cube+"] is: ";
}
else // The cube is odd.
{
sum = Enumerable.Range(0,cube).Where(x => x%2==1).Sum();
message = "The sum of the odd numbers in range [0,"+cube+"] is: ";
}
// Print the sum.
Console.WriteLine(message+sum);