The second number in his size - c#

Well its not hard and i did it but i dont know how to find it position.
I know to find the position in CASE1 and CASE2 but not in CASE3.
Any help?
int serial = 1, num, max, max2, i = 2,n;
Console.WriteLine("Enter number of numbers");
n = int.Parse(Console.ReadLine());
Console.WriteLine("Enter number");
num = int.Parse(Console.ReadLine());
/*case 1 */
max = num;
max2 = num;
for (; i <= n; i++)
{
Console.WriteLine("enter num");
num = int.Parse(Console.ReadLine());
/* case 3 */
if (num > max)
{
max2 = max;
max = num;
serial = i;
}
/* case 2 */
else if (num > max2)
{
max2 = num;
serial = i;
}
}

Let use one more variable to store the position of the maximum number also. In the below serial2 is the result of your problem.
int serial = 1, serial2 = 1, num, max, max2, i = 2,n;
Console.WriteLine("Enter number of numbers");
n = int.Parse(Console.ReadLine());
Console.WriteLine("Enter number");
num = int.Parse(Console.ReadLine());
/*case 1 */
max = num;
max2 = num;
for (; i <= n; i++)
{
Console.WriteLine("enter num");
num = int.Parse(Console.ReadLine());
/* case 3 */
if (num > max)
{
max2 = max;
max = num;
serial2 = serial;
serial = i;
}
/* case 2 */
else if (num > max2)
{
max2 = num;
serial2 = i;
}
}

I think this is what you're after - you just weren't updating your second largest index when your entered number replaced the largest number:
Console.WriteLine("Enter number of numbers");
int numberOfNumbers = int.Parse(Console.ReadLine());
int? largestNumber = null;
int? secondLargestNumber = null;
int? indexOfLargestNumber = null;
int? indexOfSecondLargestNumber = null;
for (int i = 0; i < numberOfNumbers; i++)
{
Console.WriteLine("Enter number");
int inputNumber = int.Parse(Console.ReadLine());
if (largestNumber == null || inputNumber > largestNumber)
{
secondLargestNumber = largestNumber;
largestNumber = inputNumber;
indexOfSecondLargestNumber = indexOfLargestNumber;
indexOfLargestNumber = i;
}
else if (secondLargestNumber == null || inputNumber > secondLargestNumber)
{
secondLargestNumber = inputNumber;
indexOfSecondLargestNumber = i;
}
}
/*because you started i=1 rather than i=0 as I've done, incrememting the indexes by 1*/
indexOfSecondLargestNumber++;
indexOfLargestNumber++;
Console.WriteLine("The {0} number entered ({1}) was the second largest.",indexOfSecondLargestNumber,secondLargestNumber);

Related

C# :Adapt a program to count the number of marks greater than or equal to 50

my code is where the user needs to enter a mark between and then if the mark is not between 0 and 100, it must ask again, i got that to work , but now the question states : Adapt the above program to also count the number of marks greater than or equal to 50.
How do I do this , I have tried declaring count an integer 0 but I am unsure how
to implement this.
Here is my code:
static void Main(string[] args)
{
int total = 0;
for (int x = 1; x <= 5; x++)
{
Console.WriteLine("Enter your mark");
int mark = int.Parse(Console.ReadLine());
if (mark > 100 || mark < 0)
{
Console.WriteLine("Invalid mark,Enter your mark again");
int newmark = int.Parse(Console.ReadLine());
mark = newmark;
}
total += mark;
}
Console.WriteLine("sum = " + total);
double average = (total / 5) * 1.00;
Console.WriteLine("average = " + average);
Console.ReadLine();
}
First of all, I suggest extracting a method: do not cram everything into a single Main:
private static int readMark() {
Console.WriteLine("Enter your mark");
int result = 0;
while (true)
if (!int.TryParse(Console.ReadLine(), out result))
Console.WriteLine("Incorrect syntax, enter your mark again");
else if (result < 0 || result > 100)
Console.WriteLine("Mark should be in [0..100] range, enter your mark again");
else
return result;
}
Then let's read all the marks into a collection, say, an array:
static void Main(string[] args) {
int[] marks = new int[5];
for (int i = 0; i < marks.Length; ++i)
marks[i] = readMark();
}
Now it's time for the statistics. Usually we use Linq for this:
static void Main(string[] args) {
...
double average = marks.Average();
int sum = marks.Sum();
int countGreaterThan50 = marks.Count(item => item > 50);
But we can put a good old for / foreach loop for this:
static void Main(string[] args) {
...
int total = 0;
countGreaterThan50 = 0;
for (int i = 0; i < marks.Length; ++i) {
total += marks[i];
if (marks[i] > 50)
countGreaterThan50 += 1;
}
// (double) total - be careful with integer division:
// 91 / 5 == 18 when 91.0 / 5 == 18.2
double average = ((double) total) / marks.Length;
static void Main(string[] args)
{
int total = 0;
int gt50Count = 0;
for (int x = 1; x <= 5; x++)
{
Console.WriteLine("Enter your mark");
int mark = int.Parse(Console.ReadLine());
if (mark > 100 || mark < 0)
{
Console.WriteLine("Invalid mark,Enter your mark again");
int newmark = int.Parse(Console.ReadLine());
mark = newmark;
}
total += mark;
if (mark >= 50)
{
gt50Count++;
}
}
Console.WriteLine("sum = " + total);
double average = (total / 5) * 1.00;
Console.WriteLine("average = " + average);
Console.WriteLine("Greater or equal to 50 count = " + gt50Count);
Console.ReadLine();
}
I would change the way you check if your mark is invalid to a while loop. With just that if check, if the user inserts invalid values consecutively, your code will accept it.
static void Main(string[] args)
{
int total = 0;
int marksAbove50Count = 0;
for (int x = 1; x <= 5; x++)
{
Console.WriteLine("Enter your mark");
int mark = int.Parse(Console.ReadLine());
while (mark > 100 || mark < 0)
{
Console.WriteLine("Invalid mark,Enter your mark again");
int newmark = int.Parse(Console.ReadLine());
mark = newmark;
}
total += mark;
if(mark >= 50) marksAbove50Count++;
}
Console.WriteLine("sum = " + total);
double average = (total / 5) * 1.00;
Console.WriteLine("average = " + average);
Console.WriteLine("Marks above 50 count: " + marksAbove50Count);
Console.ReadLine();
}

do/while and if/else problems

I have to put in an extra "test score" to get an answer.
(i.e i have to enter six 5' to get 25)
I can't get the do/while & if statements to loop if there is more than one number outside the "while" range. I haven't been coding for very long, a couple weeks so try and break down the answers. Thanks for the help!
Here is my code
Console.Write("Enter the number of tests: ");
int n = int.Parse(Console.ReadLine());
int[] scores = new int[n];
Console.WriteLine("----------------------------------------");
Console.WriteLine("Please enter the test scores");
int i;
do
{
i = Convert.ToInt32(Console.ReadLine());
if (i < 0)
{
Console.WriteLine("Please enter a value greater than 0");
}
if (i > 100)
{
Console.WriteLine("Please enter a value less than 100");
}
} while (i < 0 || i > 100);
for (i = 0; i < n; i++)
{
scores[i] = int.Parse(Console.ReadLine());
}
int sum = 0;
foreach (int d in scores)
{
sum += d;
}
Console.WriteLine("The sum of all the scores is {0}",sum);
Console.ReadLine();
Put the do block that does the input validation inside the for loop:
Console.Write("Enter the number of tests: ");
int n = int.Parse(Console.ReadLine());
int[] scores = new int[n];
Console.WriteLine("----------------------------------------");
Console.WriteLine("Please enter the test scores");
for (int i = 0; i < n; i++)
{
int input = -1;
do
{
input = Convert.ToInt32(Console.ReadLine());
if (input < 0)
{
Console.WriteLine("Please enter a value greater than 0");
}
else if (input > 100)
{
Console.WriteLine("Please enter a value less than 100");
}
} while (input < 0 || input > 100);
scores[i] = input;
}
int sum = 0;
foreach (int d in scores)
{
sum += d;
}
Console.WriteLine("The sum of all the scores is {0}", sum);
Console.ReadLine();
n is the number of tests, meaning the amount of scores counter i should be the same as the amount of tests. Also prefer Convert.ToInt32 to int.Parse since it throws exceptions in case it isn't able to make the conversion.
Console.Write("Enter the number of tests: ");
int n = Convert.ToInt32(Console.ReadLine());
int sum = 0, i = 0, score = 0;
int[] scores = new int[n];
Console.WriteLine("----------------------------------------");
do {
Console.WriteLine("Please enter the test score #" + (i + 1));
score = Convert.ToInt32(Console.ReadLine());
if (score < 0) {
Console.WriteLine("Please enter a value greater or equal to 0");
}
else if (score > 100)
{
Console.WriteLine("Please enter a value less or equal to 100");
}
else {
scores[i] = score;
i++;
}
} while (i < n);
foreach (int d in scores) {
sum += d;
}
Console.WriteLine("The sum of all the scores is {0}", sum);
Console.ReadLine();
Just for the potential learning opportunity, and and not as a direct answer to your question, here is the way I would do this exercise:
Console.Write("Enter the number of tests: ");
int n = int.Parse(Console.ReadLine());
Console.WriteLine("----------------------------------------");
Console.WriteLine("Please enter the test scores");
int AskForInteger()
{
while (true)
{
if (int.TryParse(Console.ReadLine(), out int i) && i >= 0 && i <= 100)
{
return i;
}
Console.WriteLine("Please enter a value between 0 and 100 inclusive");
}
}
int[] scores =
Enumerable
.Range(0, n)
.Select(x => AskForInteger())
.ToArray();
Console.WriteLine("The sum of all the scores is {0}", scores.Sum());
Console.ReadLine();
There are two options:
a. Start at 1 rather than 0 --> for (i = 1; i < n; i++)
b. Lower the value of n by 1 --> for (i = 1; i < n-1; i++)
Good luck

Getting an error about variable not existing in current context

I have written out a program that declares an array of 10 integers, takes input from the user and puts them in the array and then accepts out parameters for the highest value, lowest value, sum of all values, and the average.
The main method displays all the stats. I don't know why, but I get the error
k does not exist in the current context - line 51 column 5
when I have previously declared it before that given line. Any help would be appreciated.
using System;
namespace IntegerStatistics
{
class Program
{
static void Main()
{
Console.Clear();
// Declaring variables
int[] userArray = FillArray();
int ArrayHighest = 0;
int ArrayLowest = 0;
int ArraySum = 0;
int ArrayAverage = 0;
Calculations(userArray, out ArrayHighest, out ArrayLowest, out ArraySum, out ArrayAverage);
Console.WriteLine("The lowest value in the array is {0}, while the highest is {1}.", ArrayLowest, ArrayHighest);
Console.WriteLine("The array has a sum of {0} and averages out to {1}.", ArraySum, ArrayAverage);
Console.ReadLine();
}
private static int[] FillArray()
{
int[] intArray = new int[10];
int numbersEntered = 0;
int intTemp = 0;
string strTemp = "";
for(int k = 0; k < 10; ++k)
{
Console.WriteLine("Enter a whole number or 999 to quit: ");
strTemp = Console.ReadLine();
while(!int.TryParse(strTemp, out intTemp))
{
Console.WriteLine("Input was not in the correct format");
Console.Write("Please enter a valid number: ");
strTemp = Console.ReadLine();
}
}
if(intTemp != 999)
{
intArray[k] = intTemp;
++numbersEntered;
}
else
{
k = 10;
}
Array.Resize(ref intArray, numbersEntered);
return intArray;
}
private static void Calculations(int[] intArray, out int Highest, out int Lowest, out int intSum, out int average)
{
intSum = 0;
Array.Sort(intArray);
Lowest = intArray[0];
Array.Reverse(intArray);
Highest = intArray[0];
Array.Reverse(intArray);
for(int k = 0; k < intArray.Length; ++k)
{
intSum += intArray[k];
}
average = intSum / intArray.Length;
}
}
}
The line I'm specifically having issues with is:
if (intTemp != 999)
{
intArray[k] = intTemp;
++numbersEntered;
}
else
{
k = 10;
}
I think you meant to place the if-else block inside the for-loop.
Since you want to check if the input number is 999 for each iteration, you could write your for-loop like this:
for(int k = 0; k < 10; ++k)
{
Console.WriteLine("Enter a whole number or 999 to quit: ");
strTemp = Console.ReadLine();
while(!int.TryParse(strTemp, out intTemp))
{
Console.WriteLine("Input was not in the correct format");
Console.Write("Please enter a valid number: ");
strTemp = Console.ReadLine();
}
if(intTemp != 999)
{
intArray[k] = intTemp;
++numbersEntered;
}
else
{
k = 10;
}
}
The loop variable k goes out of scope when the code leaves the for loop. So, you can use variable k only within the loop.
So, you need to move your if-else inside your for loop. Change your FillArray() method to
private static int[] FillArray()
{
int[] intArray = new int[10];
int numbersEntered = 0;
int intTemp = 0;
string strTemp = "";
for (int k = 0; k < 10; ++k)
{
Console.WriteLine("Enter a whole number or 999 to quit: ");
strTemp = Console.ReadLine();
while (!int.TryParse(strTemp, out intTemp))
{
Console.WriteLine("Input was not in the correct format");
Console.Write("Please enter a valid number: ");
strTemp = Console.ReadLine();
}
if (intTemp != 999)
{
intArray[k] = intTemp;
++numbersEntered;
}
else
break;
}
Array.Resize(ref intArray, numbersEntered);
return intArray;
}
Also, I'd suggest changing ArrayAverage to double type. e.g. 2, 3 => average 2.5
double ArrayAverage = 0; //average need not be whole number
Additionally, with Linq you can shorten your Calculations method as
//using System.Linq;
private static void Calculations(int[] intArray, out int Highest, out int Lowest, out int intSum, out double average)
{
Lowest = intArray.Min();
Highest = intArray.Max();
intSum = intArray.Sum();
average = intArray.Average();
}

sequence with min & max numbers

I'm trying to get this program to let me enter a desired number(entries), then enter a desired value to this entries. It should write out the biggest value(green), smallest(red) then the rest of the sequence. And in the next row, biggest and smallest should change places(didn't even type code for this). What am I doing wrong(especially in the last 'for loop' )
int max = int.MinValue;
int min = int.MaxValue;
Console.WriteLine("How many numbers do you want to enter ? ");
int kolicinaBrojeva = int.Parse(Console.ReadLine());
int[] niz = new int[kolicinaBrojeva];
for (int i = 0; i < kolicinaBrojeva; i++)
{
Console.WriteLine("Enter {0}. a number:", i + 1);
niz[i] = int.Parse(Console.ReadLine());
if (niz[i] > max)
{
max = niz[i];
}
if (niz[i] < min)
{
min = niz[i];
}
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(max + ", ");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(min + ", ");
Console.ResetColor();
for (int i = 1; i >= 0; i--)
{
if (niz[i] < max && niz[i] > min)
{
Console.Write(niz[i] + ", ");
}
}
The last for loop should be like below:
for (int i = kolicinaBrojeva - 1; i >= 0; i--)
{
if (niz[i] < max && niz[i] > min)
{
Console.Write(niz[i] + ", ");
}
}
Your current code will read in kolicinaBrojeva numbers correctly, but min and max will not be set correctly. No other int is greater than int.MaxValue and similarly, no other int is less than int.MinValue. You could do the following instead:
int max = int.MinValue;
int min = int.MaxValue;
With this, you'll get the correct min and max, however, I'm not sure of what you're trying to do in the last loop.
Try this.
using System;
class Test
{
static void Main()
{
string[] temp = Console.ReadLine().Split();
int[] numbers = new int[temp.Length];
for (var i = 0; i < numbers.Length; i++)
numbers[i] = int.Parse(temp[i]);
int minIndex = 0;
int maxIndex = 0;
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] < numbers[minIndex])
minIndex = i;
if (numbers[i] > numbers[maxIndex])
maxIndex = i;
}
Swap(ref numbers[maxIndex], ref numbers[0]);
Swap(ref numbers[minIndex], ref numbers[numbers.Length - 1]);
Print(numbers, ConsoleColor.Green, ConsoleColor.Red);
Swap(ref numbers[0], ref numbers[numbers.Length - 1]);
Print(numbers, ConsoleColor.Red, ConsoleColor.Green);
}
static void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
static void Print(int[] array, ConsoleColor a, ConsoleColor b)
{
Console.ForegroundColor = a;
Console.Write(array[0] + " ");
Console.ResetColor();
for (int i = 1; i < array.Length - 1; i++)
Console.Write(array[i] + " ");
Console.ForegroundColor = b;
Console.WriteLine(array[array.Length - 1]);
Console.ResetColor();
}
}

Error : Index was outside of the bounds of the array

When I run this code:
Console.Write("How many numbers do you wish to enter? ");
int n = int.Parse(Console.ReadLine());
int[] arrayOfNumbers = new int[n];
for (int i = 0; i < n; i++)
{
Console.Write("Enter number [{0}]: ", i + 1);
arrayOfNumbers[i] = int.Parse(Console.ReadLine());
}
int minNumber = arrayOfNumbers[0];
int maxNumber = arrayOfNumbers[0];
int sumOfNumbers = 0;
for (int i = 0; i < n; i++)
{
if (arrayOfNumbers[n] < minNumber)
{
minNumber = arrayOfNumbers[n];
}
else if (arrayOfNumbers[n] > maxNumber)
{
maxNumber = arrayOfNumbers[n];
}
sumOfNumbers += arrayOfNumbers[n];
}
double sumDouble = (double)sumOfNumbers;
double average = sumDouble / n;
Console.Write("The min number is : {0}", minNumber);
Console.Write("The max number is : {0}", maxNumber);
Console.Write("The sum of the numbers is : {0}", sumOfNumbers);
Console.Write("The average sum of the numbers is : {0:f2}", average);
It gives me an error : Index was outside of the bounds of the array.
The error is at line 28.
I have a task to find min and max number + sum and average of 'n' numbers.
Inside the for, you must replace the variable 'n' by 'i'.
Like this:
(...)
for (int i = 0; i < n; i++)
{
if (arrayOfNumbers[i] < minNumber)
{
minNumber = arrayOfNumbers[i];
}
else if (arrayOfNumbers[i] > maxNumber)
{
maxNumber = arrayOfNumbers[i];
}
sumOfNumbers += arrayOfNumbers[i];
}
(...)

Categories

Resources