C# / C# Basics

Basic Input and Output in C#

This tutorial will teach you the basics of input and output in C#. You'll learn how to read data from the user and display output to the console.

Tutorial 5 of 5 5 resources in this section

Section overview

5 resources

Introduces the fundamental concepts of C#, including syntax, data types, and control structures.

Basic Input and Output in C

1. Introduction

In this tutorial, we aim to familiarize you with the core concepts of input and output (I/O) in C#. The ability to interact with users by reading input and displaying output is fundamental to almost all programming tasks. By the end of this tutorial, you will learn how to:

  • Read data from the user using the console.
  • Display information to the console.
  • Understand and implement basic I/O operations in C#.

Prerequisites: Basic knowledge of C# syntax and programming concepts.

2. Step-by-Step Guide

In C#, we use the Console class within the System namespace for basic input and output operations.

Reading Input:

To read input from the user, we use the Console.ReadLine() method. It reads the next line of characters from the standard input stream.

Console.WriteLine("Enter your name:");
string name = Console.ReadLine(); // Reads input from the user

Writing Output:

To write output to the console, we use the Console.WriteLine() method. It writes the specified data, followed by the current line terminator, to the standard output stream.

string name = "John Doe";
Console.WriteLine("Hello, " + name); // Writes output to the console

Best Practices:

  • Always validate user input to avoid runtime errors and security vulnerabilities.
  • Use meaningful variable names to make your code more readable.

3. Code Examples

Example 1: Basic Input/Output

// Ask the user for their name
Console.WriteLine("Enter your name:");
string name = Console.ReadLine(); // Reads input from the user

// Display a greeting message
Console.WriteLine("Hello, " + name); // Writes output to the console

In the above code, we first prompt the user to enter their name with Console.WriteLine(). We then read the user's input using Console.ReadLine(), and finally display a greeting message with their name.

Expected output:

Enter your name:
John Doe
Hello, John Doe

Example 2: Simple Addition Program

// Ask the user for two numbers
Console.WriteLine("Enter the first number:");
int num1 = Convert.ToInt32(Console.ReadLine()); // Convert string input to integer

Console.WriteLine("Enter the second number:");
int num2 = Convert.ToInt32(Console.ReadLine()); // Convert string input to integer

// Calculate the sum of the two numbers
int sum = num1 + num2;

// Display the result
Console.WriteLine("The sum is " + sum);

In this code, we read two numbers from the user, convert them to integers, calculate their sum, and display the result.

Expected output:

Enter the first number:
5
Enter the second number:
10
The sum is 15

4. Summary

In this tutorial, you learned how to read input from the user and write output to the console in C#. You also saw practical examples of these operations.

Next steps would be to explore more complex I/O operations, such as file I/O. Check out the official Microsoft documentation for more information.

5. Practice Exercises

  1. Write a program that asks the user for their name and age, then displays this information.

  2. Write a program that reads two integers from the user, multiplies them, and displays the result.

  3. Write a program that reads a line of text from the user, then displays the number of characters in that line.

Solutions:

  1. User Name and Age
Console.WriteLine("Enter your name:");
string name = Console.ReadLine();

Console.WriteLine("Enter your age:");
string age = Console.ReadLine();

Console.WriteLine("Your name is " + name + " and you are " + age + " years old.");
  1. Multiplication Program
Console.WriteLine("Enter the first number:");
int num1 = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter the second number:");
int num2 = Convert.ToInt32(Console.ReadLine());

int product = num1 * num2;

Console.WriteLine("The product is " + product);
  1. Character Count Program
Console.WriteLine("Enter a line of text:");
string text = Console.ReadLine();

int count = text.Length;

Console.WriteLine("The line contains " + count + " characters.");

Remember, the key to mastering programming is consistent practice. Keep coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

WHOIS Lookup Tool

Get domain and IP details with WHOIS lookup.

Use tool

Image Converter

Convert between different image formats.

Use tool

Word to PDF Converter

Easily convert Word documents to PDFs.

Use tool

Random Number Generator

Generate random numbers between specified ranges.

Use tool

Random Password Generator

Create secure, complex passwords with custom length and character options.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help