C# Syntax and Output
description
Transcript of C# Syntax and Output
public class CompSci{
}
All C# programs start with a class.
public class CompSci{ public static void Main(String[] args) { Console.WriteLine("Comp Sci!"); }} OUTPUT
Comp Sci!
public class CompSci{ //open brace
public static void Main(String[] args) { Console.WriteLine ("Comp Sci!"); }} //close brace
Braces – You gotta have ‘em! Every classand every method must have a { and a } .
public class CompSci{ public static void main(String[] args) { Console.WriteLine("Comp Sci!"); }}You must put a semi-colon at the end of all C# program statements ( ; ).
Never put a ; before an open { brace
;{ //illegal}; //legal
public class CompSci{ public static void Main(String[] args) { Console.WriteLine("Comp Sci!"); }}
Indent all code 3 spaces to make it easier to read.
Console.frequently used methods
Name UseConsole.Write print x and stay on the current line
Console.WriteLine
print x and move to next line down
Console.Write("compsci");
reference command / method
OUTPUTcompsci
Console.Write("compsci");Console.Write("compsci");
OUTPUTcompscicompsci
Console.WriteLine("compsci");
OUTPUTcompsci
Console.WriteLine("compsci");Console.WriteLine("compsci");
OUTPUTcompscicompsci
Console.WriteLine("c\tompsci");
\n newline\t tab\r carriage return\b backspace
OUTPUTc ompsci
Console.WriteLine("com\tpsci");
OUTPUTcom psci
\n newline\t tab\r carriage return\b backspace
Console.WriteLine("comp\nsci");
OUTPUTcompsci
\n newline\t tab\r carriage return\b backspace
\\ outs \\" outs "\’ outs ’
Console.WriteLine("\\compsci\"/");
OUTPUT\compsci"/
\\ outs \\" outs "\’ outs ’
Console.WriteLine("\\'comp\'sci\'/");
OUTPUT\'comp'sci'/
Escape Sequencesfrequently used combinations
Name Use
\t tabs over five spaces
\n moves to front of next line
\b deletes previous character
\r moves to front of current line
\\ nets one backslash \
\" nets one double quote "
\’ nets one single quote ’
// single-line comments/* */ block comments
//this line prints stuff on the screenConsole.WriteLine("stuff");
// single-line comments/* */ block comments
/* this line prints stuff on the screen*/Console.WriteLine("stuff");
Syntax errors occur when you type something in wrong, causing the code to not compile.
//missing semicolon - ; expectedConsole.WriteLine("stuff")
//case problem – should be SystemConsole.WriteLine("stuff")
Runtime errors occur when something goes wrong while the program is running.
//an out of bounds exception is thrownString s = "runtime_error";Console.WriteLine( s[15] );