Tutorial - C# / Mono - Add two numbers


Coding Friends Tutorial Index - > C# / Mono

Author Ian - Tutorial Posts = 62
This tutorial will demonstrate how to read from the input console (console line) to answer the prompts. The prompts will need to be a integer value to add the two inputs together.

I am using the System.Console object to read from the console and then converting the string inputs into integers with the Convert.ToInt32 function (the System.Convert has many methods and ToInt32 is one of these).

The code
---
using System;       // for the console object

class addtwonumbers
{
       public static void Main()
       {
              try
              {
                     // output to the console
                     Console.Write("Please enter value 1 : ");
                     // readin the console input, and then convert to a integer value
                     int val1 = Convert.ToInt32(Console.ReadLine());
                     Console.Write("Please enter value 2 : ");
                     int val2 = Convert.ToInt32(Console.ReadLine());
                     // write out the answer
                     Console.WriteLine("Answer = " + (val1 + val2));
              }
              catch (Exception e)
              {
                     // any errors. Like converting a string to a integer value
                     Console.WriteLine("Error : " + e.ToString());
              }
       }
}
---
save that as addtwonumbers.cs.

Once compiled (mcp addtwonumbers.cs with mono) and executed (mono addtwonumbers.exe) the output will be
Please enter value 1 : 30
Please enter value 2: 23
Answer = 53
Creation of cool tutorials :)
User Name Password
Copyright@CodingFriends, 2005-2006. All Rights Reserved.
Home | Forums | Tutorials | Users
RSS Feeds - Global Global CodingFriends RSS Feed - Tutorials Tutorials CodingFriends RSS Feed - Forums Forums CodingFriends RSS Feed - News News CodingFriends RSS Feed
Users
Login|Password problem| Register here

Tutorials
Tutorials Home| C/C++| C#/Mono| Java| Javascript| PHP| Ruby| SQL| (X)HTML/CSS| VB| Linux| Windows

Forum
Forum Home

Projects
3D Game

Site
Home| About me| Links| FAQ

Search