0

Here is my code in C#: Once this program runs it easily terminates and I can't see its output, can someone tell me what's wrong with this code?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static int sum(int num1, int num2, int num3)
        {
            int total;
            total = num1 + num2 + num3;
            return total;
        }
        static void Main(string[] args)
        {
            Console.Write("\n\nFunction to calculate the sum of two numbers :\n");
            Console.Write("--------------------------------------------------\n");
            Console.Write("Enter a number1: ");
            int n1 = Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter a number2: ");
            int n2 = Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter a number3: ");
            int n3 = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("\nThe sum of three numbers is : {0} \n", sum(n1, n2, n3));
        }
    }
}

4 Answers4

8

You need something that would prevent console window close like Console.ReadKey() at the end of your program.

opewix
  • 4,993
  • 1
  • 20
  • 42
0

Main() method is required in a public class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        public static int sum(int num1, int num2, int num3)
        {
            int total;
            total = num1 + num2 + num3;
            return total;
        }
        public static void Main(string[] args)
        {
            Console.Write("\n\nFunction to calculate the sum of two numbers :\n");
            Console.Write("--------------------------------------------------\n");
            Console.Write("Enter a number1: ");
            int n1 = Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter a number2: ");
            int n2 = Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter a number3: ");
            int n3 = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("\nThe sum of three numbers is : {0} \n", sum(n1, n2, n3));
        }
    }
}

Check here : https://dotnetfiddle.net/p9E9Rw

Kunal Moharir
  • 55
  • 1
  • 7
0

Run the program using CTRL + F5

0

You need to add the console code Console.ReadKey(); after the Console.WriteLine code.

You can also use the Console.ReadLine(); code, after the Console.WriteLine code.

So it waits for you to press a key before shutting down the Console Window.

S. Dauda
  • 1
  • 1