Printing Your Birth Year??

Started by
3 comments, last by violentcrayon 16 years, 8 months ago
Hi there, I have just started to learn C# (my first programming language ever!). At the moment, I am reading Microsoft Visual C# .NET Programming by Barbara Doyle. I have read 2 chapters -- which gives me enough knowledge on how to create very simple C# programs (e.g. Enter Name:... Hello World programs, etc). I am working through the end of chapter exercises to see if I have learnt things correctly. I can do every question except for the following: ----------------- Question 8: Print your birth year in one column. E.g: if you were born in 1982, your output should look like the following: 1 9 8 2 ------------------ Would you please be able to give me some tips on how to go about this -- as all the other questions are simple... is this one really that 'difficult' for a beginner such as myself? PS: This is not a question that has been set for homework, etc. It is just me being a geek and wanting to learn --- but there are no answers in this book!! :(
Advertisement
If I'm not mistaken, you can access the characters of a string by using the [] operator. For example:

String birthday = "1980";
char first = birthday[0];

You can get the number of characters that a string contains from it's Length property. With that information, it shouldn't be hard anymore to loop through all characters and print them.

EDIT: You may want to check out the C# Workshop on these forums. Good luck! :)
Create-ivity - a game development blog Mouseover for more information.
Well, you can convert a number (such as int Year = 1982;) to a string using its .ToString() method.

A string is made up of a sequence of chars. You can run over these using foreach, or directly indexing them using the above method.

I, personally, would do something like this:

int Year = 1982;foreach (char c in Year.ToString())     Console.WriteLine(c);

[Website] [+++ Divide By Cucumber Error. Please Reinstall Universe And Reboot +++]

Thank you.
This has really helped!

I will check out those workshops.
Thanks again! :)
Benryves has an excellent solution. Another good idea would be writing the program so that the birth year does not need to be static. Kind of an obvious point, but as a beginner myself, I know that sometimes the obvious isn't that obvious.

[edit]
I like curly braces. Although the way he wrote his code is 100% acceptable and normal, I find that I prefer even 1-line statements to be enclosed in braces.
[/edit]
http://neolithic.exofire.net

This topic is closed to new replies.

Advertisement