I need to print mathematical table without using any loop (for, while, do while, etc.). Can anyone help me out, the easiest example I could find was writing console.writeline 10times for each line.
This is my code!
using System;
using System.Linq;
class Question4
{
int product, i=1;
public static void Main(string[] args)
{
int num;
Console.Write("Enter the Number to Print its Multiplication Table: ");
num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\nMultiplication Table For {0}: ",num);
TableFunctionName (num);
}
public void TableFunctionName(int n)
{
if(i<=10)
{
table=n*i;
Console.WriteLine("{0} x {1} = {2}",n,i,table);
i++;
}
return;
}
}
Using recursion
static void Multiply(int a, int b) {
if (a > 1)
Multiply(a - 1, b);
Console.WriteLine($"{a} * { b} = {a * b}");
}
static void Main(string[] args) {
Multiply(10, 5);
}
}
You could use recursion
public static void Main()
{
Console.Write("Enter the Number to Print its Multiplication Table: ");
var input = Console.ReadLine();
var number = Convert.ToInt32(input);
CalculateAndPrint(number, 1);
}
static void CalculateAndPrint(int number, int factor)
{
if (factor > 9) return;
Console.WriteLine("{0} x {1} = {2}", number, factor, number * factor);
CalculateAndPrint(number, ++factor);
}
Related
I'm a new to C#, please give me some advice on my program. How to pass a value from a method to another method? I am trying to do a calculation by using the value n from part_number in another method.
class Program
{
static void Main(string[] args)
{
int n;
part_number(out n);
Athlete myobj = new Athlete();
int n1 = 0;
for (n1 = 0; n1 < n; ++n1)
{
Write("Enter your participant name >> ");
myobj.participant_Name = ReadLine();
WriteLine("Event codes are:");
WriteLine("T Tennis");
WriteLine("B Badminton");
WriteLine("S Swimming");
WriteLine("R Running");
WriteLine("O Other");
Write("Enter event code>> ");
myobj.event_Code0 = ReadLine();
}
double totalCost;
const double cost = 30.00;
totalCost = cost * n1;
WriteLine("The total cost is {0}", totalCost);
static void part_number(out int n)
{
n = 0;
WriteLine("Enter the number the participant this year>> ");
n = System.Convert.ToInt32(ReadLine());
while (n >= 40)
{
WriteLine("Please enter number between 0 to 40");
n = System.Convert.ToInt32(ReadLine());
}
}
}
How to pass the value of n from part_number method and another method? I need to the use that value to do a calculation in another method. Should I build a class for it?
Thank you!
You would simply add an argument to the method such as:
void MyOtherMethod(int number)
{
// do something with number
}
If you wanted, you could pass multiple things by commad delimiting them:
void MyOtherMethod(int number, string name)
{
}
You can also have a method returning a value:
int MyReturningMethod(int number)
{
return number + 2;
}
The possibilities are endless.
You will have to call your other method and pass it in.
public static Main(string[] args)
{
PartNumer(out var partNumber);
OtherMethod(partNumber);
}
static void PartNumber(out int pn)
{
pn =1;
}
static void OtherMehtod(int partNumber)
{
Console.WriteLine($"Your part number is {partNumber}");
}
I must create a console application. Write a LepsiStudent method that performs the following parameters on your input:
the name of the first student
field of first student marks
the name of the second student
field of second student marks
The method calculates the arithmetic means of the marks of these students and lists which student has a better average.
In the main method, prepare two fields of marks and student names. Then call the LepsiStudent method.
I code this and I don't know how to continue average grade can someone help me please?
{
class Program
{
static void Main(string[] args)
{
double[] znamkyjan = { 2, 4 };
double[] znamkydan = { 1, 5 };
LepsiStudent(znamkyjan,znamkydan);
}
static void LepsiStudent (double [] znamky, double[] znamky2)
{
Console.WriteLine("Jan Novák");
foreach (var znam in znamky)
{
//Console.WriteLine(znam);
Console.WriteLine(znam / 2);
}
Console.WriteLine("Daniel Havlík");
foreach (var znam2 in znamky2)
{
Console.WriteLine(znam2);
}
}
}
}
The Linq library has a built-in Average method:
using System;
using System.Linq;
public class Program
{
public static void Main(string[] args)
{
double[] znamkyjan = { 2, 4, 5, 7 };
double[] znamkydan = { 1, 5, 5, 9 };
LepsiStudent(znamkyjan,znamkydan);
}
static void LepsiStudent (double [] znamky, double[] znamky2)
{
double m1 = znamky.Average();
double m2 = znamky2.Average();
Console.WriteLine("Jan Novák: " + m1);
Console.WriteLine("Daniel Havlík: " + m2);
}
}
Output
Jan Novák: 4.5
Daniel Havlík: 5
To calculate an average you need to sum the values and then divide by the number of grades,
and you want to do that for each student.
We could do this with less variables, but this is a little more readable for someone new to programming.
we go over all the first student grades- sum them and divide, and the same for 2nd student- then we compare and print the result..
static void LepsiStudent(double[] znamky, double[] znamky2)
{
double student1Sum = 0;
double student1Avg = 0;
double student2Sum = 0;
double student2Avg = 0;
foreach (var znam in znamky)
{
student1Sum += znam;
}
student1Avg = student1Sum / znamky.Length;
foreach (var znam2 in znamky2)
{
student2Sum += znam2;
}
student2Avg = student2Sum / znamky2.Length;
if (student1Avg > student2Avg)
{
Console.WriteLine("first student has the higher average");
}
else if (student1Avg == student2Avg)
{
Console.WriteLine("neither student has the higher average");
}
else
{
Console.WriteLine("second student has the higher average");
}
}
Just for fun, this does the same thing with linq:
static void LepsiStudent(double[] znamky, double[] znamky2)
{
double student1Avg = znamky.Sum() / znamky.Length; ;
double student2Avg = znamky2.Sum() / znamky2.Length;
string name = (student1Avg == student2Avg) ? "neither" :
Math.Max(student1Avg, student2Avg) == student1Avg ? "first" : "second";
Console.WriteLine($"{name} student has the higher average");
}
I'm trying to make program to sort tabs but I can't make working table. Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SorotwanieTablic
{
class Program
{
static int NumberOfObjectInTab;
static void Numb(int NumberOfObjectInTab)
{
do
{
Console.WriteLine("Wprowadź liczbę elementów do posortowania <1 .. 10>: ");
Program.NumberOfObjectInTab = int.Parse(Console.ReadLine());
}
while (NumberOfObjectInTab < 0 || NumberOfObjectInTab > 10);
}
static int[] tab = new int[NumberOfObjectInTab];
static void InsertValuesToTab(int[] tab)
{
for (int i=0; i < tab.Length; i++)
{
Console.WriteLine("Wprowadź liczbę [{0}] ", i);
tab[i] = int.Parse(Console.ReadLine());
}
}
static void Main(string[] args)
{
Numb(NumberOfObjectInTab);
InsertValuesToTab(tab);
Console.WriteLine("\nprzed sortowaniem ");
foreach (int i in tab) Console.Write(+i + " ");
Array.Sort(tab);
Console.WriteLine("\nPO Posortowaniu ");
foreach (int i in tab) Console.Write( + i + " ");
Console.Read();
}
}
}
How user can enter the size of tab from keyboard?
I dunno what to do. I tried return NumberOfObjectInTab but nothing changes. With void and with int there is still same value to tab.
It sort if I change to static int[] tab = new int[5]; (for example) but... I must have size of tab defined by user, not by code.
Break your application down into the functions it needs to perform the desired work. Maybe start with non-implementation first. The create the implementations.
static int sizeOfTab;
static int[] tab;
static void Main(string[] args)
{
CollectSizeOfTab(args);
CreateTab();
InsertValuesToTab(tab);
Sort(tab);
}
static void CollectSizeOfTab(string[] args)
{
do
{
Console.WriteLine("Wprowadź liczbę elementów do posortowania <1 .. 10>: ");
sizeOfTab = int.Parse(Console.ReadLine());
}while (sizeOfTab < 0 || sizeOfTab > 10);
}
static void CreateTab(){tab = new int[sizeOfTab];}
static void InsertValuesToTab(int[] tab){...}
static void Sort(int[] tab){...}
How user can enter the size of tab from keyboard?
Console.Write("Enter size of tab:");
var response = Console.ReadLine();
I'm learning C# by myself by book and would appreciate some help. I want to create a simple console program to allow the user to enter a number to be doubled. It says that the variable result in the Main method is unassigned, however, what am I doing wrong?
using System;
class Program
{
private static void Double(ref int num, ref int result)
{
result = num * 2;
}
private static int readNumber(string question)
{
Console.Write(question);
string ans = Console.ReadLine();
int number = int.Parse(ans);
return number;
}
public static void Main()
{
int num, result;
num = readNumber("Enter an integer to be doubled: ");
Double(ref num, ref result);
Console.WriteLine("The double of {0} is {1}", num, result);
Console.WriteLine("Press enter to exit...");
Console.ReadLine();
}
}
The compiler is yelling at you because it wants to force you to initialize the variables before passing them to the method call.
Meaning:
int num, result;
Should be:
int num = 0;
int result = 0;
There may be a better way of doing what you're trying to do, without any ref parameters at all, by simply using the return value of the method:
private static int Double(int num)
{
return num * 2;
}
And consume it like this:
public static void Main()
{
int num = readNumber("Enter an integer to be doubled: ");
int result = Double(num);
Console.WriteLine("The double of {0} is {1}", num, result);
Console.WriteLine("Press enter to exit...");
Console.ReadLine();
}
This may even (IMO) enhance the readability of your code and convey your intentions better.
´Why don´t you simply change the methods signatur to return a double instead of using a ref?
private static double Double(int num)
{
return num * 2;
}
Now you can simply call result = Double(num).
I am facing a problem in creating a console application in Visual Studio c# 2005
I created the following program in which a method (to sum 2 predefined values) is called in the program
here is the code of it
class program
{
static void Main()
{
program a;
a = new program();
Console.WriteLine(a.am1(1,2));
Console.ReadLine();
}
int sum;
public int am1(int num1, int num2)
{
sum = num1 + num2;
return sum;
}
}
Now here is the main problem I am facing, well in this program two integers (num1 and num2) are predefined, I wanted those 2 numbers to be taken from user, means user input the two numbers and then the same program goes on like above. How it should be done?
P.S remember everything should be done in methods
i hope i got your requirements ... if not, please elaborate!
public sealed class Program
{
private readonly int _number1;
private readonly int _number2;
public Program(int number1, int number2)
{
this._number1 = number1;
this._number2 = number2;
}
public int Sum()
{
return this._number1 + this._number2;
}
public static void Main(string[] args)
{
// this one here is really brutal, but you can adapt it
int number1 = int.Parse(args[0]);
int number2 = int.Parse(args[1]);
Program program = new Program(number1, number2);
int sum = program.Sum();
Console.WriteLine(sum);
Console.ReadLine();
}
}
sry, this is not my main coding style ... pfuh ... really ugly!
edit:
don't give blind trust in int.Parse(). the params are coming from the user, you better double check them!
you better triple check them, as you are doing a sum ... thankfully c# compiles with unchecked - this code may fail with an OverflowException if compiled in vb - remember ranges of int
why do you want to do a simple addition in an extra class?
you should elaborate your style (regarding your comment): separate ui-code from business-layer code!
you do not need to create an instance variable for each task - you can do that with scope variables too...!
...
Use console application command line arguments. If it suites you. Below is an example from MSDN.
public class Functions
{
public static long Factorial(int n)
{
// Test for invalid input
if ((n < 0) || (n > 20))
{
return -1;
}
// Calculate the factorial iteratively rather than recursively:
long tempResult = 1;
for (int i = 1; i <= n; i++)
{
tempResult *= i;
}
return tempResult;
}
}
class MainClass
{
static int Main(string[] args)
{
// Test if input arguments were supplied:
if (args.Length == 0)
{
System.Console.WriteLine("Please enter a numeric argument.");
System.Console.WriteLine("Usage: Factorial <num>");
return 1;
}
// Try to convert the input arguments to numbers. This will throw
// an exception if the argument is not a number.
// num = int.Parse(args[0]);
int num;
bool test = int.TryParse(args[0], out num);
if (test == false)
{
System.Console.WriteLine("Please enter a numeric argument.");
System.Console.WriteLine("Usage: Factorial <num>");
return 1;
}
// Calculate factorial.
long result = Functions.Factorial(num);
// Print result.
if (result == -1)
System.Console.WriteLine("Input must be >= 0 and <= 20.");
else
System.Console.WriteLine("The Factorial of {0} is {1}.", num, result);
return 0;
}
}
// If 3 is entered on command line, the
// output reads: The factorial of 3 is 6.