Im trying to learn c# by reading Herbert Schildt "c# 4.0 the complete reference" and in one of examples I have this warning CS0162 Unreachable code detected and underlined Console. How to fix that and why it happened?
using System;
class ProdSum
{
static void Main()
{
int prod;
int sum;
int i;
sum = 0;
prod = 1;
for (i = 1; 1 <= 10; i++)
{
sum = sum + i;
prod = prod * i;
}
Console.WriteLine("Summ = " + sum);
Console.WriteLine("Prod = " + prod);
Console.ReadKey();
}
}
1 <= 10 is always true, so the code that follow the for loop is never reached. You meant i <= 10
for (i = 1; i <= 10; i++)
Your condition is comparing digit 1 with number 10
1 <= 10
This expression will always be true and control will never flow out of the loop.
You probably need i <= 10
Related
Hello my currenct code is doing sum on numbers after + including 10 I need it only after, now is doing like 10 + 10 = 20 then 20 +11 = 31 and etc which is wrong, when I change my i with 11 it adds 1 more interaction to the correct and makes the number more than 1000.
`` `
int i = 10;
int a = 10;
while (a < 1000)
{
a += i++;
}
Console.WriteLine(a);
Console.WriteLine(i);
Tried to change the numbers to 11 which is correct but gives me 1 more interaction which I want to remove!
sorry, do you mean to increment only by 10 ?, you can change a += i++; to a += i;
Solution:
int i = 11;
int a = 10;
while (a < 1000)
{
a += i++;
}
i -= 1;
a -= i;
Console.WriteLine(a);
Console.WriteLine(i);
So you want to termionate the loop before a gets > 1000.
The easiest way is to calculate the new value but not yet assign it to a:
int i = 10;
int a = 10;
while (a < 1000)
{
int newValue = a + i;
if (newValue > 1000) break;
i++;
a = newValue;
}
Console.WriteLine(a);
Console.WriteLine(i);
Alternative: you could also modify the while condition. As you know you are going to add i, check if the result would be still <= 1000:
while (a + i <= 1000)
{
a += i++;
}
Alternative 2: Another strategy proposed in #Slepcho's comment is to undo the last addition after the loop:
while (a <= 1000)
{
a += i++;
}
a -= --i;
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.
I have a project which involves simulating a horse race and reporting who comes first, second and third. I have gone all of the way up to making a random number for each measure of distance and whichever horse has the highest total number wins. I am having trouble putting the first, second and third place down right. I have the total in an array and I'm not quite sure where to go with it now.
Console.Write ("Type 'Begin' to start the race. ");
string startRace = Console.ReadLine ();
if (startRace == "Begin")
{
Console.Clear ();
Console.WriteLine ("You may now begin the race.");
Console.Clear ();
int[] tot = new int[numberOfHorses];
for (int i = 0; i < numberOfHorses; i++)
{
Console.Write (string.Format("{0, 10}: ", horseName[i]));
int total = 0;
for (int n = 1; n <= furlongs; n++)
{
int randomNum = rnd.Next (0, 10);
Console.Write (" " + randomNum + " ");
total = total + randomNum;
}
tot[i] = total;
Console.Write (" | " + total);
Console.WriteLine (" ");
} //This is where I start to get unsure of myself.
int firstPlace = Int32.MinValue
for (int place = 0; place < numberOfHorses; place++)
{
if (tot[place] > firstPlace)
{
firstPlace = tot[place];
}
}
}
'numberOfHorses' is how many horses the user has decided to race and 'horseName' is what the user has named each horse. Thanks. :)
You need a sorting function. Instead of:
int firstPlace = Int32.MinValue
for (int place = 0; place < numberOfHorses; place++)
{
if (tot[place] > firstPlace)
{
firstPlace = tot[place];
}
}
try this:
int[] horseIndexes = new int[numberOfHorses];
for (int place = 0; place < numberOfHorses; place++)
{
horseIndexes[place] = place ;
}
// this is the sorting function here
// (a,b) => tot[b] - tot[a]
// it will sort in descending order
Array.Sort(horseIndexes, (a,b) => tot[b] - tot[a]);
for (int place = 0; place < horseIndexes.Length && place < 3; place++)
{
Console.WriteLine("place: " + (place+1));
Console.WriteLine("horse: " + horseName[horseIndexes[place]);
Console.WriteLine("total: " + tot[horseIndexes[place]);
}
There are better ways of doing this using LINQ expressions, but hopefully this example is the most understandable.
Emerald King should already know how to find the highest number in a list. Take the top number out (set it to 0) then repeat the process to find second, and again to find third.
I'm trying to store an unknown amount of data into an array, while using a forloop to get data! My task is to find and sum all the numbers form 1 to 1000 that can be divided be 3 and 5.
for (int i = 1; i < 1001; i++)
if (i%3==0)
{
if (i%5==0)
{
//this doesn't work, have tried to convert it to string, didn't work either
int[] array = { i };
//trying to loop the values
for (int j = 0; j < array.Length; i++)
{
//how can I loop this so I dont have to write it all out?
int sum1 = array[j]
}
}
}
Console.ReadKey();
Just because computers can perform repetitive task well doesn't mean you ignore Mathematics. If I got it right, you are trying to find the sum of all the numbers less than 1000 which are divisible by both 3 and 5. So that boils down to all the multiples of 15. Now if you take the floor of 1000/15, you get the the last multiple, which in this case is 66. So, you have to sum the series:
15, 15*2, 15*3,...15*66
=15*(1+2+3+..+66) [15*sum of first 66 positive natural numbers]
=15*66*67/2
So generalizing, finding sum of all numbers less than a and divisible by b is given by:
limit = floor(a/b);
sum = b*limit*(limit+1)/2;
Something like this:
var ListOfInts=new List<int>();
for (int i = 1; i < 1001; i++) {
if (i % 3 == 0 && i % 5 == 0)
ListOfInts.Add(i);
}
var result = ListOfInts.Sum();
Perhaps this code does what you want:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<int> li = new List<int>();
for (int i = 1; i <= 1000; i++)
{
if (i%3 == 0 && i%5 == 0)
{
li.Add(i);
}
}
Console.Write("sum is " + li.Sum());
Console.ReadLine();
}
}
}
The number devides by 3 and 5 means it devides by 15. So you can start iterating from 15 and incrementing by 15 to skip some iterations:
int sum = 0;
for (int i = 15; i <= 1000; i += 15)
sum += i;
Thanks guys! Alot of good answers, i'm still trying to understand some of them but thanks :)
How come that
List<int> li = new List<int>();
for (int i = 1; i <= 1000; i++)
{
if (i%3 == 0 && i%5 == 0)
{
li.Add(i);
}
}
Console.Write("sum is " + li.Sum());
Console.ReadLine();
give me this
while the code down under
var ListofInts = new List<int>();
for (int i = 0; i < 1001; i++)
{
if (i%3==0 && i%5==0)
{
ListofInts.Add(i);
var result = ListofInts.Sum();
Console.Write(result + ", ");
}
}
gives me this?
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);