I want to be able to find date based on input number(between 1-365). For e.g., if number entered as 40 then my program should output - Date:9 Month:2
I have tried the below code and was able to find dates for all months except January -
static void Main(string[] args)
{
int[] arryofdays = new int[] {31,28,31,30,31,30,31,31,30,31,30,31};
int num = Int32.Parse(Console.ReadLine());
int temp = num;
string date, month;
for (int i = 0; i < arryofdays.Length; i++)
{
temp = temp - arryofdays[i];
if (temp < arryofdays[i + 1])
{
Console.WriteLine("Date:" + temp.ToString());
Console.WriteLine("Month:" + (i+2).ToString());
break;
}
}
Console.ReadLine();
}
Please help!
Why don't you just try like this;
var datetime = new DateTime(2017, 1, 1).AddDays(40 - 1);
var month = datetime.Month; //2
var day = datetime.Day; //9
The reason why your code is not working for JAN month is, because on temp = temp - arryofdays[i]; statement you are getting negative values if your inout is less than 31.
You can modify your code like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
//Your code goes here
Console.WriteLine("Hello, world!");
int[] arryofdays = new int[] {31,28,31,30,31,30,31,31,30,31,30,31};
int num = Int32.Parse(Console.ReadLine());
int temp = num;
string date, month;
for (int i = 0; i < arryofdays.Length; i++)
{
temp =(temp - arryofdays[i]);
if (temp < arryofdays[i + 1] && temp >0)
{
Console.WriteLine("Date:" + temp.ToString());
Console.WriteLine("Month:" + (i+2).ToString());
break;
}else{//for handling first month
Console.WriteLine("Date:" +num);
Console.WriteLine("Month:" + 1);
break;
}
}
Console.ReadLine();
}
}
}
Working code : http://rextester.com/PAJQ64015
Hope that helps.
try like this ,take arugment and also check it you can able to convert in int form or not, make your program type safe
and also check validation that days value will be between 1 and 365
public static void Main(string[] args)
{
int days = 0;
if (args.Length > 0 && int.TryParse(args[0], out days))
{
if (!(days < 1 || days > 366))
{
DateTime date = new DateTime(DateTime.Now.Year, 1, 1).AddDays(days - 1);
Console.WriteLine("Date: {0}", date.Day);
Console.WriteLine("Date: {0}", date.Month);
}
}
else
{
Console.WriteLine("input vlaue is not correct or not present");
}
}
You can try it like this
static void Main(string[] args)
{
int[] arryofdays = new int[] {31,28,31,30,31,30,31,31,30,31,30,31};
int num = Int32.Parse(Console.ReadLine());
int days = 0;
int months = 0;
for (int i = 0; i < arryofdays.Length; i++) {
if (num > arryofdays[i]) {
num -= arryofdays[i];
months++;
} else {
days = num;
break;
}
}
Console.WriteLine("Date:" + days.ToString());
Console.WriteLine("Month:" + (months+1).ToString());
Console.ReadLine();
}
Assuming num = 40, on the first iteration of the for loop, it'll check if num > arryofdays[0] which is if 40 > 31. That'll return true, so 31 will be decremented from num making the value of num to be 9. months will be incremented. On the next iteration (i = 1), it'll check if num > arryofdays[1] which is if 9 > 28 which means there are only 9 days and we break because we don't need to go any further.
Your output will be
Date:9
Month:2
Related
For my C# programming homework, we had to write a program that allows the user to input an integer and use a loop to print out the factors of that integer.
I got the program to output the integers.
The problem is, for example, when I enter in the integer "24", I want the output to be
1 and 2 and 3 and 4 and 6 and 8 and 12 and 24
but the output that comes out is
1 and 2 and 3 and 4 and 6 and 8 and 12 and 24 and
I don't want the extra "and" at the end of my Factors List
Here is what my code looks like:
using System;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
int a, b;
Console.WriteLine("Please enter your integer: ");
a = int.Parse(Console.ReadLine());
for (b = 1; b <= a; b++)
{
if (a % b == 0)
{
Console.Write(b + " ");
}
}
Console.ReadLine();
}
}
}
EDIT: The output has to be formatted as
1 and 2 and 3 and 4 and 6 and 8 and 12 and 24
or else I won't get credit for the assignment
You can enumerate factors, and then Join them with " and "
private static IEnumerable<int> Factors(int value) {
// Simplest, not that efficient
for (int i = 1; i <= value; ++i)
if (value % i == 0)
yield return i;
}
...
Console.Write(string.Join(" and ", Factors(24)));
Or you can add " and " before, not after printing factors (i)
int value = 24;
bool firstTime = true;
// Simplest, not that efficient
for (int i = 1; i <= value; ++i) {
if (value % i == 0) {
// print "and" before printing i
if (!firstTime)
Console.Write(" and ");
firstTime = false;
Console.Write(i);
}
}
How about adding the numbers to a List and printing after the loop:
int a, b;
a = int.Parse(Console.ReadLine());
var result = new List<int>();
for (b = 1; b <= a; b++)
{
if (a % b == 0)
{
result.Add(b);
}
}
Console.Write(string.Join(" and ", result));
static void Main(string[] args)
{
//get input from user
Console.WriteLine("Please enter your integer: ");
int a = int.Parse(Console.ReadLine());
//enumerate factors
var factors = Enumerable.Range(1, a)
.Where(i => a % i == 0).ToArray();
//join for nicely printed output
Console.Write(string.Join(" and ", factors));
Console.ReadLine();
}
I would recommend you to create a string and output that string becouse it allows you to do more things with it, then do something like this:
int a, b;
string x="";
Console.WriteLine("Please enter your integer: ");
a = int.Parse(Console.ReadLine());
for (b = 1; b <= a; b++)
{
if (a % b == 0)
{
x=x + b.toString() +" and";
}
}
if you know that always will be an "and" at the end you can simply do this
string x = x.Substring(0, x.Length - 3);
and then
Console.Write(x);
Console.ReadLine();
So was looking to see how to code a calendar in C# which is easy if your using asp.net. However, I'm using console application because i'm required to do so. Now coding for a one month was not to bad but I can't figure out how to code a whole year (January-December).
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
int current = 0;
int skip = 0;
int day = 1;
int endDay = 31;
string line = " Sun Mon Tue Wed Thu Fri Sat";
Console.WriteLine(line);
line = "";
while (skip < current)
{
line += " ";
skip++;
}
while (day <= endDay)
{
while (current < 7 && day <= endDay)
{
line += String.Format("{0,4}", day);
current++;
day++;
}
Console.WriteLine(line);
line = "";
current = 0;
}
Console.ReadLine();
}
}
}
after doing so this will display a one month calendar so the question is how could I display a full year calendar while still using console application and from the codes I already have?
You could do something like this. I tried to add comments for explanation:
static void Main(string[] args)
{
// Loop 12 times (once for each month)
for (int i = 1; i < 13; i++)
{
// Get the first day of the current month
var month = new DateTime(2017, i, 1);
// Print out the month, year, and the days of the week
// headingSpaces is calculated to align the year to the right side
var headingSpaces = new string(' ', 16 - month.ToString("MMMM").Length);
Console.WriteLine($"{month.ToString("MMMM")}{headingSpaces}{month.Year}");
Console.WriteLine(new string('-', 20));
Console.WriteLine("Su Mo Tu We Th Fr Sa");
// Get the number of days we need to leave blank at the
// start of the week.
var padLeftDays = (int)month.DayOfWeek;
var currentDay = month;
// Print out the day portion of each day of the month
// iterations is the number of times we loop, which is the number
// of days in the month plus the number of days we pad at the beginning
var iterations = DateTime.DaysInMonth(month.Year, month.Month) + padLeftDays;
for (int j = 0; j < iterations; j++)
{
// Pad the first week with empty spaces if needed
if (j < padLeftDays)
{
Console.Write(" ");
}
else
{
// Write the day - pad left adds a space before single digit days
Console.Write($"{currentDay.Day.ToString().PadLeft(2, ' ')} ");
// If we've reached the end of a week, start a new line
if ((j + 1) % 7 == 0)
{
Console.WriteLine();
}
// Increment our 'currentDay' to the next day
currentDay = currentDay.AddDays(1);
}
}
// Put a blank space between months
Console.WriteLine("\n");
}
Console.Write("\nDone!\nPress and key to exit...");
Console.ReadKey();
}
Output:
I have an assingment and I'm a bit lost. In an array of 10 (or less) numbers which the user enters (I have this part done), I need to find the second smallest number. My friend sent me this code, but I'm having a hard time understanding it and writing it in c#:
Solved it!!! :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int vnesena;
int? min1 = null;
int? min2 = null;
for(int i=1; i<11; i=i+1)
{
Console.WriteLine("Vpiši " + i +"." + " število: ");
vnesena = Convert.ToInt32(Console.ReadLine());
if (vnesena == 0)
{
break;
}
if (min1 == null || vnesena < min1)
{
min2 = min1;
min1 = vnesena;
}
else if (vnesena != min1 && (min2==null || vnesena<min2))
{
min2 = vnesena;
}
}
if (min1 == null || min2 == null)
{
Console.WriteLine("Opozorilo o napaki");
}
else
{
Console.WriteLine("Izhod: " + min2);
}
Console.ReadKey();
}
}
}
That code is too complicated, so try something like this.
int[] numbers = new int[10];
for (int i = 0; i < 10; i++)
{
numbers[i] = int.Parse(Console.ReadLine());
}
Array.Sort(numbers);
Console.WriteLine("Second smallest number: " + numbers[1]);
If the code isn't too obvious, let me explain:
Declare an array of 10 integers
Loop 10 ten times and each time, ask for user input & place input as an integer to the array
Sort the array so each number is in the number order (smallest first, biggest last).
The first integer is smallest (input at index 0, so numbers[0]) and the second smallest is obviously numbers[1].
Of course, for this piece of code to work, you have to use this code in console program.
As you didn't mention if you are allowed to use built in sorting functions etc, I assume that Array.Sort() is valid.
EDIT: You updated your topic so I'll change my code to match criterias.
int[] numbers = new int[10];
bool tooShortInput = false;
for (int i = 0; i < 10; i++)
{
int input = int.Parse(Console.ReadLine());
if (input != 0)
{
numbers[i] = input;
}
else
{
if (i == 2)
{
Console.WriteLine("You only entered two numbers!");
tooShortInput = true;
break;
}
else
{
for (int j = 0; j < 10; j++)
{
if (numbers[j] == 0)
{
numbers[j] = 2147483647;
}
}
break;
}
}
}
// Sort the array
int temp = 0;
for (int write = 0; write < numbers.Length; write++) {
for (int sort = 0; sort < numbers.Length - 1; sort++) {
if (numbers[sort] > numbers[sort + 1]) {
temp = numbers[sort + 1];
numbers[sort + 1] = numbers[sort];
numbers[sort] = temp;
}
}
}
if (!tooShortInput)
{
Console.WriteLine("Second smallest number: " + numbers[1]);
}
If you don't understand the updated code, let me know, I will explain.
NOTE: This is fastly coded and tested with android phone so obviously this code isn't 5 star quality, not even close, but it qualifies :-).
Regards, TuukkaX.
To paraphrase the code given:
Set 2 variables to nothing. (This is so that there can be checks done later. int? could be used if you want to use null for one idea here.
Start loop through values.
Get next value.
If the minimum isn't set or the new value is lower than the minimum, replace the second lowest with the former lowest and lowest with the new value that was entered.
Otherwise, check if the new value isn't the same as the minimum and if the minimum isn't set or the entered value is lower than the second lowest then replace the second lowest with this new value.
Once the loop is done, if either minimum value isn't filled in then output there isn't such a value otherwise output the second lowest value.
Imagine if you had to do this manually. You'd likely keep track of the lowest value and second lowest value as you went through the array and the program is merely automating this process. What is the problem?
This is a rough translation of what your friend gave you that isn't that hard to translate to my mind.
int enteredValue;
int? smallest = null, secondSmallest = null;
for (int i = 0; i < 10; i = i + 1)
{
Console.WriteLine("Vpiši " + i+1 + " število: ");
enteredValue = Convert.ToInt32(Console.ReadLine());
if (smallest==null || enteredValue<smallest) {
secondSmallest=smallest;
smallest = enteredValue;
} else if (enteredValue!=smallest && enteredValue<secondSmallest) {
secondSmallest= enteredValue;
}
}
Why use a loop and not take advantage of the Array.Sort method?
int[] numbers = new int[4] { 4, 2, 6, 8 };
Array.Sort(numbers);
int secondSmallestNumber = numbers[1];
I am trying to get previous, current and next 3 quarters base on current quarter and year.
Example : Current Quarter = 3 & Year = 2014
I want Output,
Q2-2014
Q3-2014
Q4-2014
Q1-2015
Q2-2015
I am trying as under but output is NOT correct and also how to club previous quarter?
static void Main(string[] args)
{
int generateQuater = 5;
int currentQuater = 3;
int currentYear = DateTime.Now.Year;
List<string> lstQuaterYear = new List<string>();
for (int i = generateQuater; i > 0; i--)
{
lstQuaterYear.Add(string.Format("Q{0}-{1}", currentQuater, currentYear));
if (--currentQuater == 0)
{
currentQuater = 4;
currentYear++;
}
}
Console.ReadLine();
}
Change your loop as follows:
for (int i = 0; i < generateQuater; i++)
{
if(currentQuater%5 ==0)
{
currentQuater = 1;
currentYear++;
}
lstQuaterYear.Add(string.Format("Q{0}-{1}", currentQuater%5, currentYear));
currentQuater++;
}
Modulo 5 will return values in the range [0,4]. Quarter 0 can be interpreted as quarter 1 of the next year. Therefore, we handle that case by setting currentQuater to 1 and incrementing currentYear. This will go through the 4 quarters of each year, and on the 5th one, it will move to next year and restart counting from 1.
Demo
Finally this code with help of Tieson.
Question : Any other/linq approach for subjected problem also welcome.
int generateQuater = 4;
int currentQuater = 3;
int currentYear = DateTime.Now.Year;
List<string> lstQuaterYear = new List<string>();
//previous Quater
lstQuaterYear.Add(String.Format("Q{0}-{1}", (currentQuater - 1) + (((1) / 4) * 4), currentYear - ((1) / 4)));
for (int i = 0; i < generateQuater; i++)
{
if (currentQuater % 5 == 0)
{
currentQuater = 1;
currentYear++;
}
//current and next 3 Quater
lstQuaterYear.Add(string.Format("Q{0}-{1}", currentQuater % 5, currentYear));
currentQuater++;
}
The user must provide the starting point and indicate whether the sequence should be ascending or descending. Thus far it starts counting and never stops. How do I make it stop after increment it by 10. Would I use an if statement to let the user choose to make it ascending or descending?
class Program
{
static void Main(string[] args)
{
int val;
Console.WriteLine("Please enter a number!");
val = Int32.Parse(Console.ReadLine());
for (int i = val; i <= (val + 10); val++)
Console.WriteLine(val);
Console.ReadLine();
}
}
It never stops because you increase val, and i will always be less than val + 10 (you never increase i). You should increase i instead, and use i inside the loop.
static void Main(string[] args)
{
int val;
Console.WriteLine("Please enter a number!");
val = Int32.Parse(Console.ReadLine());
for (int i = val; i <= (val + 10); i++)
Console.WriteLine(i);
Console.ReadLine();
}
For the ascending vs. descending part, you also need to take a second input from the user and if he choose descending, make a loop that checks if i >= (val - 10), and that goes i-- each iteration instead.
using System;
using System.Linq;
class Sample {
static void Main(){
const char down = '-';
Console.Write("Please enter a number! n[{0}]:", down);
string input = Console.ReadLine();
char ch = input.Last();
int diff = (ch == down) ? -1 : 1;
int val = Int32.Parse(input.TrimEnd(down));
for(var i = 1; i <= 10; i++, val += diff)
Console.WriteLine(val);
}
}
DEMO
Please enter a number! n[-]:10-
10
9
8
7
6
5
4
3
2
1
Please enter a number! n[-]:5
5
6
7
8
9
10
11
12
13
14
Change to:
static void Main(string[] args)
{
int val;
Console.WriteLine("Please enter a number!");
val = Int32.Parse(Console.ReadLine());
for (int i = val; i <= (val + 10); i++)
Console.WriteLine(i);
Console.ReadLine();
}
static void Main(string[] args)
{
int val, isDecrement;
Console.WriteLine("Please enter a number!");
val = Int32.Parse(Console.ReadLine());
Console.WriteLine("Please enter 1 to go Descending order!");
isDecrement = Int32.Parse(Console.ReadLine());
if(isDecrement ==1)
{
for (int i = val; i >= (val - 10); i--)
Console.WriteLine(i);
}
else
{
for (int i = val; i <= (val + 10); i++)
Console.WriteLine(i);
}
Console.ReadLine();
}