150 likes | 226 Views
Chapter 2. Operators and Expressions. Save program on floppy. Select all (highlight whole program from edit) Copy Open word Paste save. Loading from floppy into C#. Start C#, new project Start Word, load program text Select all Copy Go to C# paste. Operators. More on operators.
E N D
Chapter 2 Operators and Expressions
Save program on floppy • Select all (highlight whole program from edit) • Copy • Open word • Paste • save
Loading from floppy into C# • Start C#, new project • Start Word, load program text • Select all • Copy • Go to C# • paste
More on operators • Unary – one operand • Binary – two operands • Ternary – one of two possible results
Addition • When you want to add 5 and 10 5+10 using variables: num1 = 5; num2 = 10; total = num1 + num2;
Addition How to use: int student1 = 100; int student2 = 95; int student3 = 96; int sum; sum = student1+student2+student3; Console.WriteLine(“s1 = {0}, s2 = {1}, s3 = {2}”, student1, student2, student3); Console.Writeline(“sum = “ + sum);
// declare section int student1; int student2; int student3; 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); Program style
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);
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);
Division • As with the other operators, merely place it between two numeric variables • int hrsofsleep; • int hrsofstudy; • double grade = hrsofstudy / hrsofsleep;
Allowing User Input double grade; grade = double.Parse(Console.ReadLine()); (Or int or decimal ) Console.Write(“Please enter numeric Grade ”); grade = double.Parse(Console.ReadLine());
Formatting Output When you want to print money without $: netsal = 2600.4566666 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
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;
Ternary Operator • exp1 ? exp2 : exp3 • If exp1 is true, do exp2 • If exp1 is false, do exp3