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. By IncludeHelp Last updated : April 15, 2023

Reading/Printing an Integer Value

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

Converting 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.

C# code to read and print an integer value

// 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

C# Basic Programs »


Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.