Find sum of elements of an array - c#

What calculations do I need to find the total?
else if (a =2) {
TotalCredit = new int[15];
Console.WriteLine("please enter the credits");
int i = 0;
for (i = 0; i < 15; i++) {
int Credit = Convert.ToInt32(Console.ReadLine());
Total + Credit;
}
Console.WriteLine(Total);
}

You need to declare the variable Total ahead it use and it should be before loop to keep its scope available after loop. More than that your sum operation should be corrected using += operator
Correct it as follows:
int Total=0;
for (i = 0; i < 15; i++)
{
int Credit = Convert.ToInt32(Console.ReadLine());
Total += Credit;
}
Console.WriteLine(Total);

Try this.
else if (a ==2)
{
int[] TotalCredit = new int[15];
Console.WriteLine("please enter the credits");
int i = 0;
int Total = 0;
for (i = 0; i < 15; i++)
{
int Credit = Convert.ToInt32(Console.ReadLine());
Total += Credit;
}
Console.WriteLine(Total);
}
I've added this line int Total = 0; to declare a variable Total with the value 0, to store the total there.
Then I've changed a line in the for to be Total += Credit; which is the same as Total = Total + Credit; so every new value will be added and store into the variable Total.
This is a C# I guess, as convention https://msdn.microsoft.com/en-us/library/ff926074.aspx you'd better declare the variables to be lowercase.

As you have declared an array of ints I'm going to assume you want to keep the actual values the user has entered and not just the total. Make sure you add System.Linq in your using clauses.
else if (a==2)
{
var totalCredit = new int[15];
Console.WriteLine("please enter the credits");
for (int i = 0; i < 15; i++)
totalCredit[i] = Convert.ToInt32(Console.ReadLine());
var total = totalCredit.Sum();
Console.WriteLine (total);
}

A good idea would be to validate input gracefully, and minimize duplication of the magic constant 15—even better would be to assign it a meaningful name (the same goes for the a variable). Also, if you intend to store each input into the array for later usage outside of the else if block, you'll need to declare it outside of said block. However, if you do not need the individual credit values, the array is unnecessary.
const int numberOfCredits = 15;
int[] credits = new int[numberOfCredits];
...
else if (a == 2)
{
int total = 0;
int count = 0;
while (count < numberOfCredits)
{
Console.WriteLine("Enter credit #" + (count + 1).ToString() + ":");
int input;
if (int.TryParse(Console.ReadLine(), out input))
{
credits[count] = input;
total += input;
count += 1;
}
}
Console.WriteLine(total);
}

Related

Making a program that sums up only even numbers entered from console

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).

how to write a console application that calculates the sum of a given number of integers

Write a console application that calculates the sum of a given number of integers.
The numbers are entered one per line, and the application will read one by one until the user writes the character instead of a number. When the user has typed x, the application knows that all the numbers in the string have been entered and displays their amount.
If the first thing the user enters is the x character, the application will return 0.
Example:
For input:
2
5
-3
1
X
The console will display:
5
and this is my code
string[] answer = new string[10];
int sum = 0
for (int i = 0; i < answer.Length; i++)
{
sum += Int32.Parse(answer[i]);
if (answer[i] == "x")
{
Console.WriteLine(sum);
}
answer[i] = Console.ReadLine();
}
Console.Read();
Can anyone tell me why is not working?
First of all, the working code (I didn't focus on X but on any char that isn't a number):
int n;
int sum = 0;
while (int.TryParse(Console.ReadLine(), out n))
{
sum += n;
}
Console.Write(sum );
Console.ReadKey();
Secondly, your code doesn't work because your array is full of 'null'-s when you try to parse the content of its first cell in 'answer[i]'
Here's a dumb (a bit) fix for your code:
string[] answer = new string[10];
//HERE
for (int i = 0; i < answer.Length; i++)
{
answer[i] = "0";
}
int sum = 0;
for (int i = 0; i < answer.Length; i++)
{
sum += Int32.Parse(answer[i]);
if (answer[i] == "x")
{
Console.WriteLine(sum);
}
answer[i] = Console.ReadLine();
}
Console.Read();
Another problem with your code is you don't stop the iteration once "x" is entered, but continue until the end of the array (until it's been 10 times).
Here's kind of a complete fix for your code:
string[] answer = new string[10];
for (int i = 0; i < answer.Length; i++)
{
answer[i] = "0";
}
int sum = 0;
for (int i = 0; i < answer.Length; i++)
{
answer[i] = Console.ReadLine();
if (answer[i] == "x")
{
break;
}
sum += Int32.Parse(answer[i]);
}
Console.WriteLine(sum);
Console.Read();
Few issues:
I think order of your code instructions is not correct. First time when you parse your array element, its not yet initialized.
int sum = 0 is missing ; at the end.
You should always use TryParse instead of Parse
Try the following code:
string[] answer = new string[10];
int sum = 0, number;
for (int i = 0; i < answer.Length; i++)
{
answer[i] = Console.ReadLine();
if (answer[i] == "x")
{
Console.WriteLine(sum);
break;
}
if(Int32.TryParse(answer[i], out number))
sum += number;
}
I gave you your terminating 'x'
var answer = Console.ReadLine();
var sum = 0;
while (answer != "x")
{
if (Int32.TryParse(answer, out var value))
{
sum += value;
}
answer = Console.ReadLine();
}
Console.WriteLine(sum);
You should check for "x" first since int.Parse("x") throws exception:
Wrong order (current code):
sum += Int32.Parse(answer[i]); // <- this will throw exception on "x" input
if (answer[i] == "x") {
...
}
...
Right order:
if (answer[i] == "x") {
...
}
else
sum += Int32.Parse(answer[i]);
...
in order to check for syntax errors (e.g. when user inputs "bla-bla-bla") I suggest int.TryParse instead of int.Parse and let's get rid of the array why should we collect the items (esp. with unwanted restriction of 10 items)?
// long: we don't want overflow, e.g. 2000000000, 1000000000
long sum = 0;
while (true) {
// Trim() - let's be nice and allow user put leading/trailing spaces
string input = Console.ReadLine().Trim();
if (string.Equals("x", input, StringComparison.OrdinalIgnoreCase))
break;
if (int.TryParse(input, out var item))
sum += item;
else {
//TODO: Incorrect input, neither integer nor "x" (e.g. "abracadabra")
}
}
Console.WriteLine(sum);
Console.Read();

converting for loop to while loop c#

I'm curious to know how you would convert the following into a while loop. I know it doesn't make the most sense in this situation but I am working out of a student workbook and would like to see another example. Thanks in advance, any help is much appreciated.
int sides = 0;
int number = 0;
int total = 0;
Random random = new Random();
Console.WriteLine("Choose the number of sides.");
sides = int.Parse(Console.ReadLine());
Console.WriteLine("Choose number of dice.");
number = int.Parse(Console.ReadLine());
for (int i = 0; i < number; i++)
{
int die = random.Next(1, sides);
Console.WriteLine("You Rolled {0}", die.ToString());d
total += die;
}
Console.WriteLine("Your total is {0}", total);
Console.ReadLine();
int i = 0;
while(i < number)
{
int die = random.Next(1, sides);
Console.WriteLine("You Rolled {0}", die.ToString());
total += die;
i++
}
You want to convert a for-loop to a while-loop if I understand correctly.
int currentNum = 0;
while (currentNum < number)
{
int die = random.Next(1, sides);
Console.WriteLine("You Rolled {0}", die.ToString());
total += die;
currentNum++;
}

Extra zero in final out put where does it come from?

I wrote this code to order any set of numbers from biggest to smallest, but for whatever reason, the output always has a zero at the end. My question is, where did it come from? (new to coding)
Console.WriteLine("Please enter set of numbers");
int input = Convert.ToInt16(Console.ReadLine());
int counter= 1;
int temp1;
int temp2;
int[] array = new int[input+1];
for (int i = 0; i <=input-1; i++)
{
Console.WriteLine("Please enter entry number " + counter);
int number = Convert.ToInt16(Console.ReadLine());
array[i] = number;
counter++;
}
for (int x = 0; x <= input; x++)
{
for (int i = 1; i <=input; i++)
{
if (array[i - 1] <= array[i])
{
temp1 = array[i - 1];
temp2 = array[i];
array[i - 1] = temp2;
array[i] = temp1;
}
}
}
Console.WriteLine();
for (int i = 0; i<=input; i++)
{
Console.Write(array[i] + " ");
}
Console.ReadLine();
You're inconsistent between whether you're trying to handle input + 1 or input elements. For example:
int[] array = new int[input+1];
for (int i = 0; i <=input-1; i++)
{
Console.WriteLine("Please enter entry number " + counter);
int number = Convert.ToInt16(Console.ReadLine());
array[i] = number;
counter++;
}
You're creating an array with input + 1 elements, but only populating input of them.
In general, it's much more common to use exclusive upper boundaries for loops. For example:
int[] array = new int[input];
for (int i = 0; i < input; i++)
{
// No need for the counter variable at all
Console.WriteLine("Please enter entry number " + (i + 1));
int number = Convert.ToInt16(Console.ReadLine());
array[i] = number;
}

How to call function to enter multiple integers into an array?

So the code for the function (Named InsertMark) is below. How would you call this function to enter the marks for say 10 people into an array called iMarks?
static void InsertMark(int [] piMarkArray, int piStuNum)
{
int iMark;
Console.Write("Enter mark for student " + piStuNum + ": ");
iMark = Convert.ToInt32(Console.ReadLine());
while (iMark < 0 || iMark > 100)
{
Console.Write("Not a percentage. Enter again: ");
iMark = Convert.ToInt32(Console.ReadLine());
}
//update array element with this mark
piMarkArray[piStuNum] = iMark;
}
Thanks.
Just move the line piMarkArray[piStuNum] = iMark; inside while loop, use index, and exit the loop if index is not less than array length.
int index=0;
while ((iMark < 0 || iMark > 100) && index < piMarkArray.Length) // exit the loop array is full
{
Console.Write("Not a percentage. Enter again: ");
iMark = Convert.ToInt32(Console.ReadLine());
piMarkArray[index++] = iMark; // Here marks are set
}
//update array element with this mark
Here you create array which will hold 10 marks and fill it with your method in a loop:
int[] marks = new int[10];
for(int i = 0; i < marks.Length; i++)
InsertMark(marks, i);
In main function you could have a code:
int iMarks[10];
for(int i = 0; i <10; i++ )
InsertMark(iMarks, i)
are you looking for something like this?
for(int i=0; i<10; i++)
{
InsertMark(iMarks, i);
}
You need to declare an array of size 10: int[] iMarks = new int[10], then in a for loop pass the array and the counter value through to the function.
int[] iMarks = new int[10];
for(int x = 0; x < 10; x++)
InsertMark(iMarks, x);
Here is the full class/ working example:
static void Main(string[] args)
{
int[] iMarks = new int[10];
for(int x = 0; x < 10; x++)
InsertMark(iMarks, x);
Console.Read();
}
static void InsertMark(int[] piMarkArray, int piStuNum)
{
int iMark;
Console.Write("Enter mark for student " + piStuNum + ": ");
iMark = Convert.ToInt32(Console.ReadLine());
while(iMark < 0 || iMark > 100)
{
Console.Write("Not a percentage. Enter again: ");
iMark = Convert.ToInt32(Console.ReadLine());
}
//update array element with this mark
piMarkArray[piStuNum] = iMark;
}
}
There are always multiple ways to code anything, and this is no exception. What I'm putting here is one example of idiomatic C# to do this. There are at least two variants I can think of which would be better, but this keeps the closest to the original idea.
First, a basic Student class:
class Student
{
public int ID;
public int Mark;
}
Then, a function to prompt for the mark
int GetMark(int studentID)
{
Console.Write("Enter mark for student " + studentID + ": ");
int mark = Convert.ToInt32(Console.ReadLine());
while (iMark < 0 || iMark > 100)
{
Console.Write("Not a percentage. Enter again: ");
iMark = Convert.ToInt32(Console.ReadLine());
}
return mark;
}
Finally, from your main program, you have a list or array of Student objects called AllStudents and you do:
foreach (Student student in AllStudents)
{
student.Mark = GetMark(student.ID);
}
Alternatively, if you aren't using classes, your loop could be:
int[] marks = new int[10]; // Or whatever size it needs to be.
for (int i = 0; i < marks.Length; i++)
{
marks[i] = GetMark(i);
}

Categories