The COntrol of the program does not enter the for loop - c#

Here i am pasting the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace star1
{
class Program
{
static void Main(string[] args)
{
Myclass obj = new Myclass();
obj.getData();
obj.pattern();
}
}
class Myclass
{
int i, n, j;
public void getData()
{
Console.WriteLine("Program for displaying pattern of *.");
Console.Write("Enter the maximum number of *: ");
int n = Convert.ToInt32(Console.ReadLine());
}
public void pattern()
{
Console.WriteLine("\nPattern 1 - Left Aligned:\n");
for (i = 1; i <= n; i++) // The Control does not enter the for loop
{
for (j = 1; j <= i; j++)
Console.Write("*");
Console.WriteLine();
}
}
}
}

Looks like you're redeclaring n as a local variable in getData().
Try changing that line to:
n = Convert.ToInt32(Console.ReadLine());
i.e. remove the int.

well ...
as you are not using this...
class Myclass
{
int i, n, j;
public void getData()
{
Console.WriteLine("Program for displaying pattern of *.");
Console.Write("Enter the maximum number of *: ");
this.n = Convert.ToInt32(Console.ReadLine());
// OR
//n = Convert.ToInt32(Console.ReadLine());
}
public void pattern()
{
Console.WriteLine("\nPattern 1 - Left Aligned:\n");
for (i = 1; i <= n; i++) // The Control does not enter the for loop
{
for (j = 1; j <= i; j++)
Console.Write("*");
Console.WriteLine();
}
}
}
i would encourage you to use this to distinct between scope- and instance-variables!

If you try to assign n using Console.ReadLine() in getData(), you need to remove the "int" just before. Currently, you have 2 "n" variable in different scopes. That's why your loop doesn't work.

Related

Formatting Issue with for loop c#

I'm trying to create a game called 'NIM' (See code introduction if you aren't familiar). When I output the 'blocks' they aren't spaced out evenly. I may be missing the obvious, but can someone point out where I'm going wrong.
using System;
using System.Threading;
namespace NIM
{
class Program
{
static void Main(string[] args)
{
Introduction();
InitialBoardSetUp();
}
static void Introduction()
{
Console.WriteLine("\t\t\t\tWelcome to NIM!\n");
Console.WriteLine(" - Each player takes their turn to remove a certain number of 'blocks' from a stack, of which there are 7.");
Console.WriteLine(" - This happens until there is only 1 'block' remaining. With the winner being the one to remove the last 'block'.\n");
Console.WriteLine("Initialising the board:\n");
Thread.Sleep(2000);
}
static void InitialBoardSetUp()
{
for (int i = 1; i <= 7; i++)
{
Console.Write(" " + i + "\t");
}
Console.Write("\n\n");
for (int i = 1; i <= 7; i++)
{
Console.Write(" "+ i);
for (int j = 1; j <= 7; j++)
{
Console.Write(" ███\t");
}
Console.Write("\n");
}
}
}
}
The code below is your code with some minor modifications. \t has been removed and replaced with spaces. Spaces added before writing the column headers. Added comments.
Try the following:
using System;
using System.Threading;
namespace NIM
{
class Program
{
static void Main(string[] args)
{
Introduction();
InitialBoardSetUp();
}
static void Introduction()
{
Console.WriteLine("\t\t\t\tWelcome to NIM!\n");
Console.WriteLine(" - Each player takes their turn to remove a certain number of 'blocks' from a stack, of which there are 7.");
Console.WriteLine(" - This happens until there is only 1 'block' remaining. With the winner being the one to remove the last 'block'.\n");
Console.WriteLine("Initialising the board:\n");
//Thread.Sleep(2000);
}
static void InitialBoardSetUp()
{
//add space for row numbers
Console.Write(" ");
//print column headers
for (int i = 1; i <= 7; i++)
{
Console.Write(" " + i + " ");
}
Console.Write("\n\n");
for (int i = 1; i <= 7; i++)
{
//print row numbers
Console.Write(" " + i);
for (int j = 1; j <= 7; j++)
{
//print blocks
Console.Write(" ███ ");
}
Console.Write("\n");
}
}
}
}

Error with program that opens file, reads data, and calculates the average

I was given an assignment in my programming class with a prompt that directly reads,
"In this exercise exam scores for a class of students is stored in a file. You are to write a program that successfully opens the file, reads in the exam scores, and outputs them on the console."
Every time I run my program an error occurs showing that,
"An unhandled exception of type 'System.IndexOutOfRangeException' occurred in GradeCalculator.exe"
The error appears on the code, "gradesArray[i] = gradesArray[gradeData];
i++;"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace GradeCalculator
{
class Program
{
static void Main(string[] args)
{
string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\grades.txt";
int gradeData;
StreamReader grades = new StreamReader(folder);
int[] gradesArray = new int[50];
while (!grades.EndOfStream)
{
for (int i = 0; i != 50;)
{
gradeData = int.Parse(grades.ReadLine());
gradesArray[i] = gradesArray[gradeData];
i++;
}
}
Program calc = new Program();
for (int i = 0; i < 50; i++)
{
int average = calc.averageArr(gradesArray);
Console.WriteLine("{0}", average);
Console.ReadLine();
}
}
public int averageArr(int[] arr)
{
int avg = 0;
int numGrades = 0;
int sum = 0;
for (int i = 0; i < 50; i++)
{
do
{
sum += arr[i];
} while (arr[i] != 0);
}
avg = sum / numGrades;
return avg;
}
}
}
Any suggestions on how to fix this?
Data from file:
88
90
78
65
50
83
75
23
60
94
EDITED NEW CODE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace GradeCalculator
{
class Program
{
static void Main(string[] args)
{
string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\grades.txt";
int gradeData;
StreamReader grades = new StreamReader(folder);
int[] gradesArray = new int[50];
do
{
gradeData = int.Parse(grades.ReadLine());
for (int i = 0; i != gradesArray.Length;)
{
gradesArray[i] = gradeData;
i++;
}
}
while (!grades.EndOfStream);
Program calc = new Program();
int average = calc.averageArr(gradesArray);
Console.WriteLine("{0}", average);
Console.ReadLine();
}
public int averageArr(int[] arr)
{
int avg = 0;
int sum = 0;
for (int i = 0; i != arr.Length; )
{
sum += arr[i];
i++;
}
avg = sum / arr.Length;
return avg;
}
}
}
You have lot of redundant code, you simply could use Linq and get an array of int.
var intArray = File.ReadAllLines("filepath")
// Remove below line if you have only 1 number in each line, else specify delimiter and keep it.
.SelectMany(s=>s.Split(' '))
.Select(int.Parse);
Once you get the array, Array has function which returns Average
var average = intArray.Average();
Update:
Since you want to write function that calculates average, you could do this. Please note I modified few variable types to Decimal to avoid intdivision.
public decimal averageArr(int[] arr)
{
decimal avg = 0;
int numGrades = 0;
decimal sum = 0;
for (int i = 0; i < arr.Length; i++)
{
sum += arr[i];
}
avg = sum / arr.Length;
return avg;
}

How to print star like below in console application? I/p 5 O/p like = 1 212 32123 4321234 543212345 [duplicate]

My question is how to make a pyramid using * and 'space' in C#? The output will be like this.
*
* *
* * *
* * * *
* * * * *
We only need to use "for loop" for this program. I only know how to make this one.
*
**
***
****
*****
I made a program like this:
static void Main(string[]args)
{
int i=o;
int j=o;
for(i=5;1>=1;i--)
for(j=1;j<=5;j++)
{
Console.Write("*");
}
Console.WriteLine(" ");
}
I'm confused when it comes to pyramid because it includes spaces. Thanks for your help!
think about how you'd print the pyramid manually.
suppose 5 levels deep.
1st line: 4 spaces, 1 star,
2nd line: 3 spaces, star, space, star
3rd line: 2 spaces, star space star space star
etc.
doesn't matter whether you print spaces after the last star or not - won't make a difference to how it looks.
what do we see?
if we have a total of X levels
line 1: (x-1) spaces, (star space)
line 2: (x-2) spaces, (star space) twice
line 3: (x-3) spaces, (star space) three times
line 4: (x-4) spaces, (star space) four times
that's the pattern. I'll leave the coding to you.
using System;
class Program
{
static void Main(string[] args)
{
int num, i, j, k;
Console.Write("enter the level:");
num=Convert.ToInt32(Console.ReadLine());
for (i = 1; i <= num; i++)
{
for (j = 1; j < num-i+1; j++)
{
Console.Write(" ");
}
for (k = 1; k <= i; k++)
{
Console.Write(i);
Console.Write(" ");
}
Console.WriteLine();
}
}
}
Your problem is spaces, therefore I suggest you think about the spaces. Tell me this: how many spaces are on each row to the left of the first star? You'll likely be able to solve your own problem if you think about this.
Try to think of it as a grid or a matrix and see where you want the '*' in each row and how it relates to your loop index.
sorry I missed this was homework... will give a strategy ... instead
it helps if you do it in notepad and think about what you are doing... you will start to understand the relationship between the line you are on and the spaces and what not...
Post my answer after 3 hours. I think now you have almost finished it under #iluxa's advice?
int height = 20;
for (int level = 1; level <= height; level++)
{
string text = string.Join(" ", Enumerable.Repeat("*", level));
Console.WriteLine(text.PadLeft(height - level + text.Length));
}
I used some build-in methods e.g. Enumerable.Repeat and String.PadLeft, not the pure C-language way. The purpose is that I want to tell you since you have chosen C# as the programming language(not C/Java/etc), you should resolve problems in the C# way.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace pyramid_star
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("enter a number:");
int n = Convert.ToInt32(Console.ReadLine());
for (int i = 1; i <= n; i++)
{
for (int x = i; x <= n; x++)
{
Console.Write(" ");
}
for (int j = 1; j <= i; j++)
{
Console.Write("*"+" ");
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace Star_Pyramid
{
class Program
{
static void Main(string[] args)
{
Program o = new Program();
o.show();
Console.ReadKey();
}
void show()
{
for (int i = 1; i <= 12; i++)
{
for (int j = 1; j <= 9 - i / 2; j++)
{
Console.Write(" ");
}
for (int k = 1; k <= i; k++)
{
Console.Write(" * ");
Console.Write(" ");
}
Console.WriteLine();
}
}
}
}
class Program
{
static void Main(string[] args)
{
int num;
Console.WriteLine("enter level");
num = Int32.Parse(Console.ReadLine());
int count = 1;
for (int lines = num; lines >= 1; lines--)
{
for (int spaces = lines - 1; spaces >= 1; spaces--)
{
Console.Write(" ");
}
for (int star = 1; star <= count; star++)
{
Console.Write("*");
Console.Write(" ");
}
count++;
Console.WriteLine();
}
Console.ReadLine();
}
}
Try this and follow this same logic in c, c++, php, java
using System;
class pyramid {
static void Main() {
/** Pyramid stars Looking down
Comment this if u need only a upside pyramid **/
int row, i, j;
// Total number of rows
// You can get this as users input
//row = Int32.Parse(Console.ReadLine());
row = 5;
// To print odd number count stars use a temp variable
int temp;
temp = row;
// Number of rows to print
// The number of row here is 'row'
// You can change this as users input
for ( j = 1 ; j <= row ; j++ ) {
// Printing odd numbers of stars to get
// Number of stars that you want to print with respect to the value of "i"?
for ( i = 1 ; i <= 2*temp - 1 ; i++ )
Console.Write("*");
// New line after printing a row
Console.Write("\n");
for ( i = 1 ; i <= j ; i++ )
Console.Write(" ");
// Reduce temp value to reduce stars count
temp--;
}
/** Pyramid stars Looking up
Comment this if u need only a downside pyramid **/
int rowx, k, l;
// Total number of rows
// You can get this as users input
// rowx = Int32.Parse(Console.ReadLine());
rowx = 5;
// To print odd number count stars use a temp variable
int tempx;
tempx = rowx;
//Remove this if u use
Console.Write("\n");
// Number of rows to print
// The number of row here is 'rowx'
for ( l = 1 ; l <= rowx ; l++ ) {
// Leaving spaces with respect to row
for ( k = 1 ; k < tempx ; k++ )
Console.Write(" ");
// Reduce tempx value to reduce space(" ") count
tempx--;
// Printing stars
for ( k = 1 ; k <= 2*l - 1 ; k++ )
Console.Write("*");
// New line after printing a row
Console.Write("\n");
}
}
}
The following code might help:
public static void print(int no)
{
for (int i = 1; i <= no; i++)
{
for (int j = i; j <= no; j++)
{
Console.Write(" ");
}
for (int k = 1; k < i * 2; k++)
{
if(k % 2 != 0)
{
Console.Write("*");
}
else
{
Console.Write(" ");
}
}
Console.WriteLine();
}
Console.ReadLine();
}
Here I have created a number pyramid:
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("This is a number pyramid....");
var rows = 5;
for(int i = 1; i <= rows; i++)
{
for(int lsc = (-rows); lsc <= -2; lsc ++)
{
if(lsc < (-1)*i)
{
//write left sided blank spaces
Console.Write(" ");
}
else
{
//write left sided numbers
Console.Write(-1*(lsc));
}
}
for(int rsc = 1; rsc <= rows; rsc++)
{
//write right sided blank spaces
Console.Write(" ");
}
else
{
//Write sided numbers
Console.Write(rsc);
}
}
Console.WriteLine();
}
}
}
I have described here https://utpalkumardas.wordpress.com/2018/04/20/draw-number-pyramid
Out put is:
The is a number pyramid....
1
212
32123
4321234
543212345
I know it's javascript but might help
let n = 6;
for (let i = 1; i <= n; i++) {
let spaces = n-i;
let str = '';
for (let j=0; j < spaces; j++) {
str+=' ';
}
for (let j=0; j < i; j++) {
str+='* ';
}
console.log(str)
}
I have found two approaches:
//1st approach
int n = 6;
for (int i = 0; i < n; i++)
{
// need to print spaces
for (int j = 0; j < n - i - 1; j++)
{
Console.Write(" ");
}
// need to print * with one space
for (int k = 0; k <= i; k++)
{
Console.Write("* ");
}
Console.WriteLine();
}
// 2nd Approach
int rows = 6;
int temp = 0;
bool toggle = false;
for (int j = 0; j < rows; j++)
{
int counter = 0;
for (int i = 0; i < 2 * rows - 1; i++)
{
if (i < rows - temp - 1)
{
Console.Write(" ");
}
else
{
if (counter <= j + temp)
{
if (!toggle)
{
Console.Write("*");
toggle = true;
}
else
{
Console.Write(" ");
toggle = false;
}
}
counter++;
}
}
Console.WriteLine();
temp++;
toggle = false;
}

Array duplicate deletion in C#

This is my code so far I have display all items in the array as the user enters and create an error message for duplicate numbers that deletes the duplicate and continues the loop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace midterm
{
class Program
{
static void Main(string[] args)
{
int size;
Console.WriteLine("How many numbers will you enter?");
size = Convert.ToInt32(Console.ReadLine());
int[] numbers = new int[size];
int i;
for (i = 0; i < size; i++)
{
Console.WriteLine("Enter number: ");
numbers[i] = Convert.ToInt32(Console.ReadLine());
}
for (i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if (i != j)
{
if (numbers[j] == numbers[i])
{
int k = j;
while (k < size - 1)
{
numbers[k] = numbers[k + 1];
k++;
}
size--;
}
}
}
}
Console.WriteLine("Duplicate Removed:");
for (i = 0; i < size; i++)
{
Console.WriteLine(numbers[i]);
}
Console.ReadLine();
}
}
}
Every time I go to change the for loops around or add an error message then the program stops deleting the duplicates I am really stumped on this one can someone lend me a hand.
Have a look at LINQ, it has some great functions that can be used for collection manipulation. In your situation I would do the following:
Distinct() here filters the array to only unique values.
int[] initialArray = new int[] { 1, 1, 2, 3, 4, 5 };
int[] noDuplicates = initialArray.Distinct().ToArray(); // [1,2,3,4,5]
I would recommend using a List instead of array. A List will allow you to keep adding entries to it without having to specify the size.
With the list, you can check if entry exists already before adding it, so you wont have to remove or delete
Easy way, use a HashSet
HashSet<int> mySet = new HashSet<int>();
//...
for (i = 0; i < size; i++)
{
Console.WriteLine("Enter number: ");
int number = Convert.ToInt32(Console.ReadLine());
if (!mySet.Add(number))
{
Console.WriteLine("That was a duplicate. Try again");
i--;
}
}
If you must use arrays:
for (i = 0; i < size; i++)
{
Console.WriteLine("Enter number: ");
int numbers = Convert.ToInt32(Console.ReadLine());
if (ExistsInArray(number, numbers))
{
Console.WriteLine("That was a duplicate. Try again");
i--;
}
else
{
numbers[i] = number;
}
}
And then:
private static bool ExistsInArray(number, numbers)
{
// Your code to search numbers for number and return true if found
// Left as an exercise for the OP
}
One important note here is that it's a lot easier to check whether your array already contains the element you are trying to add than to remove it after the fact. If it already exists, just don't add it again.

Whats wrong with my C# program?

I need to create an application that fills an array with random numbers. I written the whole code and it works but the numbers are not displaying in the console window. What could be wrong with the code? Thanks
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Arrays
{
class Program
{
static void Main(string[] args)
{
int[] array = new int[10];
Random randomNumbers = new Random();
for (int i = 0; i < array.Length; i++)
{
int randomValue = randomNumbers.Next(0,500);
array[i] = randomValue;
}
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("The array value is: ", array[i]);
}
}
}
}
You can either use
Console.WriteLine("The array value is: {0}", array[i]);
or
Console.WriteLine("The array value is: " + array[i]);
but what you wrote,
Console.WriteLine("The array value is: ", array[i]);
entirely misses on telling the console where and how you use the array[i] variable.
Console.WriteLine("The array value is: {0}", array[i]);
You have to indicate in the format string that you want to print some value.
//Console.WriteLine("The array value is: ", array[i]);
Console.WriteLine("The array value is: {0}", array[i]);
Console.WriteLine("The array value is: {0}", array[i]);
You are missing
Console.ReadLine();
After Console.WriteLine();
As others have mentioned, to get this line to work with {0}, you'd need to format it as a string,
Console.WriteLine(string.Format("The array value is: {0}", array[i]));
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.Write("Coefficient Of x (Positive): ");
int coef = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Value Of c: ");
int c = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("From? (Positive)");
int from = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("To? (Positive)");
int to = Convert.ToInt32(Console.ReadLine());
Console.Clear();
int[] y_val = new int[(to - from) + 1];
int counter = 0;
for (int i = to; i >= from; i--)
{
y_val[counter] = ((coef * i) + c);
counter++;
}
int x = 0;
for (int i = to; i >= from; i--)
{
if (y_val[x] == ((coef * i) + c))
{
if (y_val[x] >= 10)
{
Console.WriteLine("{0}|", y_val[x]);
}
else
{
Console.WriteLine("0{0}|", y_val[x]);
}
for (int j = 0; j < i; j++)
{
Console.Write(" ");
}
Console.Write("*");
Console.WriteLine();
}
x++;
}
Console.WriteLine("______________________________________________________________");
Console.WriteLine("0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23");
Console.ReadKey();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication36
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("asd");
}
}
}

Categories