Variables and Assignments - Example

This section provides a tutorial example on how to use variables, variable declaration statements, and assignment statements.

Now let's review what have learned in this section with a sample program:

// Variables.cs
// Copyright (c) All Rights Reserved.

class Variables {
   public static void Main() {
      bool is_ok;
      int n;
      int num_of_sec;
      long number_of_sec_in_a_year;
      float sqrt_s;
      double sqrt_d;
      char c1, c2, c3;
      char cr, cn;

      is_ok = true;
      num_of_sec = 86400;
      number_of_sec_in_a_year = 30458700;
      sqrt_s = 1.4142F;
      sqrt_d = 1.4142135623730950488016887242097;
      c1 = 'a';
      c2 = 'A';
      c3 = '0';
      cr = '\r';
      cn = '\n';

      n = 1;
      System.Console.WriteLine("Value of is_ok = {0}.", is_ok);
      System.Console.WriteLine("1 day = {0} seconds.", num_of_sec);
      System.Console.WriteLine("1 year = {0} seconds.",
         "Square root of 2 (float) = {0}.", sqrt_s);
         "Square root of 2 (double) = {0}.", sqrt_d);
         "Some regular characters: {0}, {1}, {2}.", c1, c2, c3);
      System.Console.WriteLine("The return character: {0}.", cr);
      System.Console.WriteLine("The new line character: {0}.", cn);
      n = 9;
      System.Console.WriteLine("WriteLine() is used {0} times.", n);

Output of the program will be:

Value of is_ok = True.
1 day = 86400 seconds.
1 year = 30458700 seconds.
Square root of 2 (float) = 1.4142.
Square root of 2 (double) = 1.4142135623731.
Some regular characters: a, A, 0.
.he return character:
The new line character:
WriteLine() is used 9 times.

Observations from this program:

Advice: Avoid using "int" and "float". Use "long" and "double" instead. In the old days, 32-bit data requires less memory to store and computer time to process than 64-bit data. This is not totally true now, because today's computers are designed to store and process data 64 bits at a time, not 32 bits at a time.

Table of Contents

 About This Book

 Introduction of C# (C Sharp)

Data Type and Variables

 Data Literals

 Data Literals - Example

 Variables and Assignment Statements

Variables and Assignments - Example

 Arithmetic Operations

 Arithmetic Operations - Example

 Logical Expressions and Conditional Statements

 Arrays and Loop Statements

 Data Type Features

 Floating-Point Data Types

 Passing Parameters to Methods

 Execution Environment Class

 Visual C# 2010 Express Edition

 Class Features

 C# Compiler and Intermediate Language

 Compiling C# Source Code Files

 MSBuild - Microsoft Build Engine

 Memory Usages of Processes

 Multithreading in C#

 Async Feature from C# 5

 System.IO.FileInfo Class

 System.Diagnostics.FileVersionInfo Class

 WPF - Windows Presentation Foundation

 Partial Classes and Partial Methods

 Outdated Tutorials


 Full Version in PDF/ePUB