100% found this document useful (1 vote)
397 views

Week2a BasicElementsinC#

The document discusses the basic elements of C# including classes, the Main method, variables, data types, operators, input/output, and type conversions. It provides examples and explanations of each element. Key points include: - The class is the basic unit of a C# program and contains methods and data. The Main method is the entry point. - Variables are declared with a data type and assigned values. Basic data types include integers, floats, decimals, booleans, chars, and strings. - Input is handled with Read and ReadLine methods from the Console class. Output uses Write and WriteLine. - Operators perform math functions. Type conversions may be implicit or require a cast
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
397 views

Week2a BasicElementsinC#

The document discusses the basic elements of C# including classes, the Main method, variables, data types, operators, input/output, and type conversions. It provides examples and explanations of each element. Key points include: - The class is the basic unit of a C# program and contains methods and data. The Main method is the entry point. - Variables are declared with a data type and assigned values. Basic data types include integers, floats, decimals, booleans, chars, and strings. - Input is handled with Read and ReadLine methods from the Console class. Output uses Write and WriteLine. - Operators perform math functions. Type conversions may be implicit or require a cast
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

BASIC ELEMENTS OF C#

– class

– Main

– basic input and output

– types

– variables

– operators

Class

• Keyword class used to define new type

– specify name

– enclose body in { }

• Most C# code placed inside a class

– no global variables allowed

– no global methods allowed

Main

• Main method is the application entry point

– must be static method of some class

– any access level such as public or private is allowed

• Main can perform environment interaction

– can receive command line arguments as array of strings

– can return int to indicate success/failure

Basic Output

• Write output using Write and WriteLine

– from Console class in System namespace

– WriteLine adds line terminator in output

– overloaded versions allow printing of all types

– some versions take format string and data

– variable argument list version allows printing multiple values


See sample program below:

To run the program, click :

To stop the program, click:

Let us look at the various parts of the given program:

 The first line of the program using System; - the using keyword is used to include the System
namespace in the program. A program generally has multiple using statements.

 The next line has the namespace declaration. A namespace is a collection of classes. The HelloWorld
namespace contains the class HelloWorld.

 The next line has a class declaration, the class HelloWorld contains the data and method definitions
that your program uses. Classes generally contain multiple methods. Methods define the behavior of the
class. However, the HelloWorld class has only one method Main.

 The next line defines the Main method, which is the entry point for all C# programs. The Main
method states what the class does when executed.

 The next line /*...*/ is ignored by the compiler and it is put to add comments in the program.  The
Main method specifies its behavior with the statement Console.WriteLine("Hello World");  WriteLine is
a method of the Console class defined in the System namespace. This statement causes the message
"Hello, World!" to be displayed on the screen.

 The last line Console.ReadKey(); is for the VS.NET Users. This makes the program wait for a key press
and it prevents the screen from running and closing quickly when the program is launched from Visual
Studio .NET.
NOTES:

 C# is case sensitive.

 All statements and expression must end with a semicolon (;).

 The program execution starts at the Main method.

 Unlike Java, program file name could be different from the class name.

Variables Declarations

• Declare variables by specifying data type and name

– names are case sensitive

– comma separated list for multiple variables

– end with semicolon

Data types – specify the type and range of data assign to a variable

Basic data types in C# are distributed into the following types:

- Integer types – sbyte, byte, short, ushort, int, uint, long, ulong;

- Real floating-point types – float, double;

- Real type with decimal precision – decimal;

- Boolean type – bool;

- Character type – char;

- String – string;

- Object type – object.

These data types are called primitive (built-in types), because they are embedded in C# language at the
lowest level. The table below represents the above mentioned data types, their range and their default
values:
Example variable declarations:

Syntax:

Data type variable_list;

area is a variable with a double data type.

x ,y and z variables are all integers

type is a variable with a character data type

name is a variable with a string data type.

Sample value of variable:

area = 3.2;

x = 2;

y = 0;

z = 10;

type = ‘C’;

name = “Jane Doe”;

Naming Conventions of variables

1. Names are made up of letters and digits.

2. The first character must be a letter.

3. C # is case-sensitive, example ‘s’ is not the same with ‘S’.

4. The underscore symbol (_) is considered as a letter in C. It is not recommended to be used, however,
as the first character in a name.

5. At least the first 3 characters of a name are significant.


Names... Example

CANNOT start with a number 2i

CAN contain a number elsewhere h2o

CANNOT contain any arithmetic operators... r*s+t

CANNOT contain any other punctuation marks... #@x%£!!a

CAN contain or begin with an underscore height_

CANNOT be a C# keyword using

CANNOT contain a space im stupid

CAN be of mixed cases XSquared

Basic Input

• Read input using Read or ReadLine

– from Console class in System namespace

– returns entire input line as a string

NOTE: all inputs are string, conversion of data is needed using the convert class

Let’s examine the above program per line:

-lines encircle in red are variable declarations of input_value and name for string data type and

num for int data type.

-lines encircle in blue ask the user to input a number assign to input_value variable,
input_value = Console.ReadLine();

since all inputs are string we need to convert it into an integer before we assign it to num

conversion:

num = Convert.ToInt32(input_value);

-lines encircle in yellow ask the user to input a string assign to name variable, no conversion
needed since our data type is a string.
Some conversion using Convert class:

Type conversion

• Some automatic type conversions available


– from smaller to larger types

• Conversions which may lose information require cast


– syntax is type name inside parentheses

Implicit Conversion – from larger type (base on range of the data type) to smaller type (base on range of
the data type)

Let examine the example:


- d is a variable with a double data type
- i is a variable with an integer data type
- when d is assign to i , it must have the same data type so type cast is done otherwise it will
prompt an error.
- now variable i has the value of 3.
Operators

Example:

To return a remainder
z = x % y;
z has a value of 2 since 5/3 is 1 remainder 2

Now, let’s have an example problem using basic elements of C#

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

namespace ComputeTravel
{
class Program
{
static void Main(string[] args)
{
//Computes and outputs travel time
//for a given speed and distance
// variable declaration
int speed; //rate of travel
double distance; //miles to travel
double time; //time needed for this travel
string input_value;
// ask input for speed
Console.Write("Enter your speed in mph: ");
input_value = Console.ReadLine();
speed = Convert.ToInt32(input_value);

// ask input for distance


Console.Write("Enter your distance in miles: ");
// one line ask input with conversion
// also,you can use this format to ask input
distance = Convert.ToDouble(Console.ReadLine());
// formula to solve the time
time = distance / speed;
// display output
Console.Write("At " + speed + " mph, ");
Console.WriteLine("it will take ");
Console.Write(time + " hours to travel ");
Console.WriteLine(distance + " miles.");

Console.ReadKey();

}
}
}

Practice Exercises

1. Write a program that would accept the number of bottles and cans then compute
the amount of soda (Liters) in the refrigerator. The bottle has two liter while
the can is 12oz.

Conversion between Metric and English Units:

1 (fluid) oz = 29.586mL
1 gallon = 3.785L

2. Write a program that will input a 5 digit integer and print the place value for each digit.
Sample output:
Enter a 5 digit no.: 12345

12 Thousands
3 Hundreds
4 Tens
5 Ones
Hint: Use the Modulo operator % to get the remainder and / to divide
Exercises (Graded)

Create one folder to save all the following exercise below.

1. Write a program that accept an integer representing the total number of seconds and
output the equivalent time in hours, minutes, and seconds.

Example: if the input is 26643 the output is


"26643 seconds is 7 hours 24 minutes and 3 seconds."

2 .Write a program that will solve the problem below:


Chififay was promised by her employer a 10% raise for the month. If her salary is P700 per month, how
much will she receive the next month if she gets cash advance of P500 and promise to pay it the next
month?

3. Write a program that extracts and prints the second rightmost digit of the integral portion of a float.
Example:
input: 723.56
output: 2

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy