Download presentation
Presentation is loading. Please wait.
1
Operators and Expressions
Chapter 2 Operators and Expressions
2
Save program on floppy Select all (highlight whole program from edit)
Copy Open word Paste save
3
Loading from floppy into C#
Start C#, new project Start Word, load program text Select all Copy Go to C# paste
4
Operators Operation Operator Rank Addition + 2 Subtraction - 2
Multiplication * 1 Division / 1
5
More on operators Unary – one operand Binary – two operands
Ternary – one of two possible results
6
Addition When you want to add 5 and 10 5+10 using variables: num1 = 5;
total = num1 + num2;
7
Addition How to use: int student1 = 100; int student2 = 95;
int sum; sum = student1+student2+student3; Console.WriteLine(“s1 = {0}, s2 = {1}, s3 = {2}”, student1, student2, student3); Console.Writeline(“sum = “ + sum);
8
Program style // declare section int student1; int student2;
int sum; // input section student1=100; student2=95; student3=96; // calculate section sum = student1+student2+student3; // results section Console.WriteLine(“s1 = {0}, s2 = {1}, s3 = {2}”, student1, student2, student3); Console.Writeline(“sum = “ + sum);
9
Subtraction double salary = 255.32; double benefits = 26.66;
double netsal; netsal = salary – benefits; Console.WriteLine(“Sal={0}, Ben={1}, Net={2}”, salary, benefits, netsal);
10
Multiplication double grade=4.0; double credits=3.0; double qualpts;
Console.WriteLine(“With a grade of {0}, and {1} credits, you earned {2} QP”, grade, credits, grade * credits);
11
Division As with the other operators, merely place it between two numeric variables int hrsofsleep; int hrsofstudy; double grade = hrsofstudy / hrsofsleep;
12
Allowing User Input double grade;
grade = double.Parse(Console.ReadLine()); (Or int or decimal ) Console.Write(“Please enter numeric Grade ”);
13
Formatting Output When you want to print money without $:
netsal = Console.WriteLine(“Net Salary {0:N2}”, netsal) Result: Net Salary 2,600.45 Console.WriteLine(“Net Salary {0:C}”, netsal) Result: Net Salary $2,600.45
14
Increment and Decrement
int age = 2; age = age + 2; what is the value of age? old = age++; (called postfix) same as old=age; and then age=age+1 old=++age; Same as age=age+1; and then old=age;
15
Ternary Operator exp1 ? exp2 : exp3 If exp1 is true, do exp2
If exp1 is false, do exp3
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.