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);
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.
In one of my classes I was given an assignment to write a simple program that combines multiple numbers entered from the console, but only adding up the even ones. I was able to do the summing up part pretty easily but I can't figure out how to check for even numbers! If anyone can figure out how or explain for a beginner how to do it would be greatly appreciated.
Here's the full code so far:
using System;
namespace Test_3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Amount of numbers n = ");
var n = int.Parse(Console.ReadLine());
Console.WriteLine("Enter numbers:");
var sum = 0;
for (int i = 0; i < n; i++)
{
if (sum%2 == 0)
{
}
else
{
}
var num = int.Parse(Console.ReadLine());
sum = sum + num;
}
Console.WriteLine("The sum of the numbers is " + sum);
}
}
}
You seem to already know how to get the even numbers but here is how to apply it!
Console.WriteLine("Amount of numbers n = ");
var n = int.Parse(Console.ReadLine());
Console.WriteLine("Enter numbers:");
var sum = 0;
for (int i = 0; i < n; i++)
{
var num = int.Parse(Console.ReadLine()); //first read a number from the console
if (num % 2 == 0) //then check if it is even
{
sum = sum + num; //if it is, then add it to sum
}
}
Console.WriteLine("The sum of the numbers is " + sum);
You seem not to get the idea of an if-clause, let me explain this, using the following pieces of code:
Your code:
for (int i = 0; i < n; i++)
{
if (sum%2 == 0)
{
}
else
{
}
var num = int.Parse(Console.ReadLine());
sum = sum + num;
}
This calculates the sum of all numbers (you check whether a number is even or not, but you don't use that information).
My proposal: (you check if a number is even, and you use that information)
for (int i = 0; i < n; i++)
{
if (sum%2 == 0)
{
var num = int.Parse(Console.ReadLine());
sum = sum + num;
}
else
{
}
}
Another one, how to calculate the sum of the odd numbers? (Here you check if a number is even, but you use the case where it is not)
for (int i = 0; i < n; i++)
{
if (sum%2 == 0)
{
}
else
{
var num = int.Parse(Console.ReadLine());
sum = sum + num;
}
}
So, you see? You can use if-clauses to filter out what you want to do when a condition is met or when a condition is not met, that's the whole idea behind it.
You need to check whether the variable num is divisible by two instead of the sum. The code you have checks if the sum is even and if so does nothing since you didn't add anything to the if statement. Instead, you should be doing if ( num % 2 == 0) .
You also need to move where num is declared to the top of the for loop and move the part where you add to the sum to the inside of the conditional (The if statement).
I'm trying to find the sum from (1 to n) or given number.
using this code:
int n;
int counter = 0;
int sum = 0;
Console.Write("Please enter the sum limit number: ");
n = int.Parse(Console.ReadLine());
//around here is where code freezes and nothing else happens
while(counter <= n)
{
counter = +1;
sum = sum + counter;
}
Console.Write("The sum from 1 - " + n + " =" + sum);
I know I can use:
int n;
int counter = 0;
int sum = 0;
Console.Write("Please enter the sum limit number: ");
n = int.Parse(Console.ReadLine());
var sum = Enumerable.Range(1, n);
Console.Write("The sum from 1 - " + n + " =" + sum.Sum());
but my next challenge is to only add the numbers that are divisible by 3 or 5, so I'm planning on doing:
if (sum % 3 == 0 | sum % 5 == 0)
{
total = total + sum;
}
What is wrong with my method? Also, alternative ways to do this are more than appreciated!
To get out of while loop, condition needs to satisfy.First you need increment counter present in while loop.
To increment counter variable either you can try counter++/++counter i.e. post/pre increment operator or you can do counter += 1/ counter = counter + 1.
Something similar to
//around here is where code freezes and nothing else happens
while(counter <= n)
{
counter += 1; // not counter=+1;
sum = sum + counter;
}
Reference: Increment decrement in C#
if you want to increment the counter you should either use
counter = counter + 1;
or
counter++;
or
counter += 1;
I wrote I method which is suppose to recieve a nubmer from user and then check number from 0 to 1000. Then it should return all number which have digit sum equal to recieved number. So if I enter 6, it should return numbers like 6, 42, 51, 33, 123 etc. I'd really appreciate help since I've been dwelling on this for a while now.
public static double number() {
Console.WriteLine("Enter your number! ");
string enter = Console.ReadLine();
double x = Convert.ToDouble(enter);
for (int i = 0; i < 1000; i++ ) {
double r;
double sum = 0;
while (i != 0) {
r = i % 10;
i = i / 10;
sum = sum + r;
}
if (sum == x) {
Console.WriteLine(i + " ");
}
}
return(0);
}
I am aware of the fact that there is a problem with "return(0)", but I'm not completely sure what exactly it is that this should be returning.
I'd suggest trying to do something like this:
public static IEnumerable<int> number()
{
Console.WriteLine("Enter your number!");
string enter = Console.ReadLine();
int digitSum = int.Parse(enter);
foreach (var n in Enumerable.Range(0, 1000))
{
if (n.ToString().ToCharArray().Sum(c => c - '0') == digitSum)
{
yield return n;
}
}
}
When I run this and enter 6 then I get this result:
You are almost there: the only remaining problem is that you are modifying your loop counter i inside the nested while loop, which changes the workings of the outer loop.
You can fix this problem by saving a copy of i in another variable, say, in ii, and modifying it inside the while loop instead:
double r;
double sum = 0;
int ii = i;
while (ii != 0) {
r = iCopy % 10;
ii /= 10;
sum = sum + r;
}
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.