Advertisement
sergezhu

Untitled

Apr 30th, 2023
645
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.33 KB | None | 0 0
  1. namespace ConsoleApp1;
  2.  
  3. using System.Text;
  4.  
  5. public class Task23
  6. {
  7.     public void Run()
  8.     {
  9.         Console.InputEncoding = Encoding.Unicode;
  10.         Console.OutputEncoding = Encoding.Unicode;
  11.  
  12.         string sumCommand = "sum";
  13.         string exitCommand = "exit";
  14.  
  15.         int[] numbers = {};
  16.         int emptyArrayLength = 0;
  17.  
  18.         bool canExit = false;
  19.  
  20.         while ( canExit == false )
  21.         {
  22.             Console.WriteLine( "\nEnter commands 'sum' or 'exit' or numbers:" );
  23.            
  24.             string command = Console.ReadLine().Trim();
  25.  
  26.             if ( string.Equals( command, exitCommand ) )
  27.             {
  28.                 canExit = true;
  29.             }
  30.             else if ( string.Equals( command, sumCommand ) )
  31.             {
  32.                 if ( numbers.Length == emptyArrayLength )
  33.                 {
  34.                     Console.WriteLine("Array is empty, you can not calculate sum");
  35.                 }
  36.                 else
  37.                 {
  38.                     var arraySum = 0;
  39.                    
  40.                     foreach ( int number in numbers )
  41.                         arraySum += number;
  42.  
  43.                     Console.WriteLine( $"Sum of array numbers is {arraySum}" );
  44.                 }
  45.             }
  46.             else
  47.             {
  48.                 int number = int.Parse( command );
  49.  
  50.                 int newNumbersArrayLength = numbers.Length + 1;
  51.                 int[] newNumbers = new int[newNumbersArrayLength];
  52.  
  53.                 for ( int i = 0; i < numbers.Length; i++ )
  54.                     newNumbers[i] = numbers[i];
  55.  
  56.                 newNumbers[newNumbers.Length - 1] = number;
  57.                 numbers = newNumbers;
  58.  
  59.                 Console.WriteLine( $"Number {number} added" );
  60.             }
  61.         }
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement