Home
Aptitude
Categories


Home » C# programs » C# basic programs

C# | Input and print an integer number



C# program to input and print an integer number: Here, we are writing a C# program that will read an integer value and print it.
Submitted by IncludeHelp, on December 05, 2018

Since, to read a string value or to print a line, we use Console.ReadLine() - but, we can convert it into an integer value.

Syntax to convert string formatted value to integer:

    integer_variable = Convert.ToInt32(Console.ReadLine());

Here, Convert is a class in C# and ToInt32() is a static member of it – which is used to convert a string value to the 4 bytes integer.

Program:

/*C# program to input and print an integer number*/
using System;
class ReadIntExample {
    static void Main() {
        //declare an integer variable
        int num = 0;
        //prompt message to take input
        Console.Write("Input an integer value: ");
        num = Convert.ToInt32(Console.ReadLine());
        //print the value
        Console.WriteLine("num = " + num);
    }
}

Output

Input an integer value: 200
num = 200



How to handle the exception – if value is not an integer?

If you going to input an integer value using integer_variable = Convert.ToInt32(Console.ReadLine()) and input value is not an integer, then program returns an exception.

In the below program, we are handling the exception.

Program:

using System;
class ReadIntExample {
    static void Main() {
        try{
            //declare an integer variable
            int num = 0;
            //prompt message to take input
            Console.Write("Input an integer value: ");
            num = Convert.ToInt32(Console.ReadLine());
            //print the value
            Console.WriteLine("num = " + num);
        }
        catch(Exception ex){
            Console.WriteLine("Error: " + ex.ToString());
        }
    }
}

Output (when input value is an integer)

Input an integer value: 200
num = 200

Output (when input value is a string)

Input an integer value: Hello
Error: System.FormatException: Input string was not in the correct format
  at System.Int32.Parse (System.String s) [0x00000] in 
  <filename unknown>:0
  at System.Convert.ToInt32 (System.String value) [0x00000] 
  in <filename unknown>:0
  at ReadIntExample.Main () [0x00000] 
  in <filename unknown>:0





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.