SlideShare a Scribd company logo
1 of 36
Console Input / OutputConsole Input / Output
Reading and Writing to the ConsoleReading and Writing to the Console
Svetlin NakovSvetlin Nakov
Telerik CorporationTelerik Corporation
www.telerik.comwww.telerik.com
Table of ContentsTable of Contents
 Printing to the ConsolePrinting to the Console
 Printing Strings and NumbersPrinting Strings and Numbers
 Reading from the ConsoleReading from the Console
 Reading CharactersReading Characters
 Reading StringsReading Strings
 Parsing Strings to Numeral TypesParsing Strings to Numeral Types
 Reading Numeral TypesReading Numeral Types
 Various ExamplesVarious Examples
2
Printing to the ConsolePrinting to the Console
Printing Strings, Numeral Types and ExpressionsPrinting Strings, Numeral Types and Expressions
3
Printing to the ConsolePrinting to the Console
 Console is used to display information in a textConsole is used to display information in a text
windowwindow
 Can display different values:Can display different values:
StringsStrings
Numeral typesNumeral types
All primitiveAll primitive datadata typestypes
 To print to the console use the classTo print to the console use the class ConsoleConsole
((System.ConsoleSystem.Console))
4
The Console ClassThe Console Class
 Provides methods for console input and outputProvides methods for console input and output
InputInput
 Read(…)Read(…) – reads a single character– reads a single character
 ReadKey(…)ReadKey(…) – reads a combination of keys– reads a combination of keys
 ReadLine(…)ReadLine(…) – reads a single line of characters– reads a single line of characters
OutputOutput
 Write(…)Write(…) – prints the specified– prints the specified
argument on the consoleargument on the console
 WriteLine(…WriteLine(…)) – prints specified data to the– prints specified data to the
console and moves to the next lineconsole and moves to the next line
5
Console.Write(…)Console.Write(…)
 Printing more than one variable using aPrinting more than one variable using a
formatting stringformatting string
int a = 15;int a = 15;
......
Console.Write(a); // 15Console.Write(a); // 15
 Printing an integer variablePrinting an integer variable
double a = 15.5;double a = 15.5;
int b = 14;int b = 14;
......
Console.Write("{0} + {1} = {2}", a, b, a + b);Console.Write("{0} + {1} = {2}", a, b, a + b);
// 15.5 + 14 = 29.5// 15.5 + 14 = 29.5
 Next print operation will start from the same lineNext print operation will start from the same line
6
Console.WriteLine(…)Console.WriteLine(…)
 Printing more than one variable using aPrinting more than one variable using a
formatting stringformatting string
string str = "Hello C#!";string str = "Hello C#!";
......
Console.WriteLine(str);Console.WriteLine(str);
 Printing a string variablePrinting a string variable
string name = "Marry";string name = "Marry";
int year = 1987;int year = 1987;
......
Console.Write("{0} was born in {1}.", name, year);Console.Write("{0} was born in {1}.", name, year);
// Marry was born in 1987.// Marry was born in 1987.
 Next printing will start from the next lineNext printing will start from the next line
7
Printing to the Console – ExamplePrinting to the Console – Example
static void Main()static void Main()
{{
string name = "Peter";string name = "Peter";
int age = 18;int age = 18;
string town = "Sofia";string town = "Sofia";
Console.Write("{0} is {1} years old from {2}.",Console.Write("{0} is {1} years old from {2}.",
name, age, town);name, age, town);
// Result: Peter is 18 years old from Sofia.// Result: Peter is 18 years old from Sofia.
Console.Write("This is on the same line!");Console.Write("This is on the same line!");
Console.WriteLine("Next sentence will be" +Console.WriteLine("Next sentence will be" +
" on a new line.");" on a new line.");
Console.WriteLine("Bye, bye, {0} from {1}.",Console.WriteLine("Bye, bye, {0} from {1}.",
name, town);name, town);
}}
8
Using Parameters – ExampleUsing Parameters – Example
9
static void Main()static void Main()
{{
int a=2, b=3;int a=2, b=3;
Console.Write("{0} + {1} =", a, b);Console.Write("{0} + {1} =", a, b);
Console.WriteLine(" {0}", a+b);Console.WriteLine(" {0}", a+b);
// 2 + 3 = 5// 2 + 3 = 5
Console.WriteLine("{0} * {1} = {2}",Console.WriteLine("{0} * {1} = {2}",
a, b, a*b);a, b, a*b);
// 2 * 3 = 6// 2 * 3 = 6
float pi = 3.14159206;float pi = 3.14159206;
Console.WriteLine("{0:F2}", pi); // 3,14Console.WriteLine("{0:F2}", pi); // 3,14
Console.WriteLine("Bye – Bye!");Console.WriteLine("Bye – Bye!");
}}
Printing a Menu – ExamplePrinting a Menu – Example
double colaPrice = 1.20;double colaPrice = 1.20;
string cola = "Coca Cola";string cola = "Coca Cola";
double fantaPrice = 1.20;double fantaPrice = 1.20;
string fanta = "Fanta Dizzy";string fanta = "Fanta Dizzy";
double zagorkaPrice = 1.50;double zagorkaPrice = 1.50;
string zagorka = "Zagorka";string zagorka = "Zagorka";
Console.WriteLine("Menu:");Console.WriteLine("Menu:");
Console.WriteLine("1. {0} – {1}",Console.WriteLine("1. {0} – {1}",
cola, colaPrice);cola, colaPrice);
Console.WriteLine("2. {0} – {1}",Console.WriteLine("2. {0} – {1}",
fanta, fantaPrice);fanta, fantaPrice);
Console.WriteLine("3. {0} – {1}",Console.WriteLine("3. {0} – {1}",
zagorka, zagorkaPrice);zagorka, zagorkaPrice);
Console.WriteLine("Have a nice day!");Console.WriteLine("Have a nice day!");
10
Printing toPrinting to
the Consolethe Console
Live DemoLive Demo
Reading from the ConsoleReading from the Console
Reading Strings and Numeral TypesReading Strings and Numeral Types
Reading from the ConsoleReading from the Console
 We use the console to read information fromWe use the console to read information from
the command linethe command line
 We can read:We can read:
CharactersCharacters
StringsStrings
Numeral types (after conversion)Numeral types (after conversion)
 To read from the console we use the methodsTo read from the console we use the methods
Console.Read()Console.Read() andand Console.ReadLine()Console.ReadLine()
13
Console.Read()Console.Read()
 Gets a single character from the console (afterGets a single character from the console (after
[Enter] is pressed)[Enter] is pressed)
 Returns a result of typeReturns a result of type intint
 ReturnsReturns -1-1 if there aren’t more symbolsif there aren’t more symbols
 To get the actually read character weTo get the actually read character we
need to cast it toneed to cast it to charchar
int i = Console.Read();int i = Console.Read();
char ch = (char) i; // Cast the int to charchar ch = (char) i; // Cast the int to char
// Gets the code of the entered symbol// Gets the code of the entered symbol
Console.WriteLine("The code of '{0}' is {1}.", ch, i);Console.WriteLine("The code of '{0}' is {1}.", ch, i);
14
Reading CharactersReading Characters
fromfrom the Consolethe Console
Live DemoLive Demo
Console.ReadKey()Console.ReadKey()
 Waits until a combination of keys is pressedWaits until a combination of keys is pressed
 Reads a single character from console or aReads a single character from console or a
combination of keyscombination of keys
 Returns a result of typeReturns a result of type ConsoleKeyInfoConsoleKeyInfo
 KeyCharKeyChar – holds the entered character– holds the entered character
 ModifiersModifiers – holds the state of [Ctrl], [Alt], …– holds the state of [Ctrl], [Alt], …
ConsoleKeyInfo key = Console.ReadKey();ConsoleKeyInfo key = Console.ReadKey();
Console.WriteLine();Console.WriteLine();
Console.WriteLine("Character entered: " + key.KeyChar);Console.WriteLine("Character entered: " + key.KeyChar);
Console.WriteLine("Special keys: " + key.Modifiers);Console.WriteLine("Special keys: " + key.Modifiers);
16
Reading KeysReading Keys
from the Consolefrom the Console
Live DemoLive Demo
Console.ReadLine()Console.ReadLine()
 Gets a line of charactersGets a line of characters
 Returns aReturns a stringstring valuevalue
 ReturnsReturns nullnull if the end of the input is reachedif the end of the input is reached
Console.Write("Please enter your first name: ");Console.Write("Please enter your first name: ");
string firstName = Console.ReadLine();string firstName = Console.ReadLine();
Console.Write("Please enter your last name: ");Console.Write("Please enter your last name: ");
string lastName = Console.ReadLine();string lastName = Console.ReadLine();
Console.WriteLine("Hello, {0} {1}!",Console.WriteLine("Hello, {0} {1}!",
firstName, lastName);firstName, lastName);
18
Reading StringsReading Strings
from the Consolefrom the Console
Live DemoLive Demo
Reading Numeral TypesReading Numeral Types
 Numeral types can not be read directly from theNumeral types can not be read directly from the
consoleconsole
 To read a numeral type do the following:To read a numeral type do the following:
1.1. RRead a string valueead a string value
2.2. Convert (parse) it to the required numeral typeConvert (parse) it to the required numeral type
 int.Parse(string)int.Parse(string) – parses a– parses a stringstring toto intint
string str = Console.ReadLine()string str = Console.ReadLine()
int number = int.Parse(str);int number = int.Parse(str);
Console.WriteLine("You entered: {0}", number);Console.WriteLine("You entered: {0}", number);
20
Converting Strings to NumbersConverting Strings to Numbers
 Numeral types have a methodNumeral types have a method Parse(…)Parse(…) forfor
extracting the numeral value from a stringextracting the numeral value from a string
int.Parse(string)int.Parse(string) –– stringstring  intint
longlong.Parse(string).Parse(string) –– stringstring  longlong
floatfloat.Parse(string).Parse(string) –– stringstring  floatfloat
CausesCauses FormatExceptionFormatException in case ofin case of errorerror
string s = "123";string s = "123";
int i = int.Parse(s); // i = 123int i = int.Parse(s); // i = 123
long l = long.Parse(s); // l = 123Llong l = long.Parse(s); // l = 123L
string invalid = "xxx1845";string invalid = "xxx1845";
int value = int.Parse(invalid); // FormatExceptionint value = int.Parse(invalid); // FormatException
21
Reading Numbers from theReading Numbers from the
Console – ExampleConsole – Example
22
static void Main()static void Main()
{{
int a = int.Parse(Console.ReadLine());int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());int b = int.Parse(Console.ReadLine());
Console.WriteLine("{0} + {1} = {2}",Console.WriteLine("{0} + {1} = {2}",
a, b, a+b);a, b, a+b);
Console.WriteLine("{0} * {1} = {2}",Console.WriteLine("{0} * {1} = {2}",
a, b, a*b);a, b, a*b);
float f = float.Parse(Console.ReadLine());float f = float.Parse(Console.ReadLine());
Console.WriteLine("{0} * {1} / {2} = {3}",Console.WriteLine("{0} * {1} / {2} = {3}",
a, b, f, a*b/f);a, b, f, a*b/f);
}}
Converting Strings toConverting Strings to
Numbers (2)Numbers (2)
 Converting can also be done using the methods ofConverting can also be done using the methods of
thethe ConvertConvert classclass
 Convert.ToInt32(string)Convert.ToInt32(string) –– stringstring  intint
 Convert.ToSingle(string)Convert.ToSingle(string)–– stringstring  floatfloat
 Convert.ToInt64(string)Convert.ToInt64(string)–– stringstring  longlong
 Internally uses the parse methods of the numeralInternally uses the parse methods of the numeral
typestypes
string s = "123";string s = "123";
int i = Convert.ToInt32(s); // i = 123int i = Convert.ToInt32(s); // i = 123
long l = Convert.ToInt64(s); // l = 123Llong l = Convert.ToInt64(s); // l = 123L
string invalid = "xxx1845";string invalid = "xxx1845";
int value = Convert.ToInt32(invalid); // FormatExceptionint value = Convert.ToInt32(invalid); // FormatException
23
Reading NumbersReading Numbers
from the Consolefrom the Console
Live DemoLive Demo
Error Handling when ParsingError Handling when Parsing
 Sometimes we want to handle the errors whenSometimes we want to handle the errors when
parsing a numberparsing a number
 Two options: useTwo options: use trytry--catchcatch block orblock or TryParse()TryParse()
 Parsing withParsing with TryParse()TryParse()::
string str = Console.ReadLine();string str = Console.ReadLine();
int number;int number;
if (int.TryParse(str, out number))if (int.TryParse(str, out number))
{{
Console.WriteLine("Valid number: {0}", number);Console.WriteLine("Valid number: {0}", number);
}}
elseelse
{{
Console.WriteLine("Invalid number: {0}", str);Console.WriteLine("Invalid number: {0}", str);
}}
25
Parsing withParsing with TryParseTryParse()()
Live DemoLive Demo
Reading and PrintingReading and Printing
to the Consoleto the Console
Various ExamplesVarious Examples
Printing a Letter – ExamplePrinting a Letter – Example
28
Console.Write("Enter person name: ");Console.Write("Enter person name: ");
string person = Console.ReadLine();string person = Console.ReadLine();
Console.Write("Enter company name: ");Console.Write("Enter company name: ");
string company = Console.ReadLine();string company = Console.ReadLine();
Console.WriteLine(" Dear {0},", person);Console.WriteLine(" Dear {0},", person);
Console.WriteLine("We are pleased to tell you " +Console.WriteLine("We are pleased to tell you " +
"that {1} has chosen you to take part " +"that {1} has chosen you to take part " +
"in the "Introduction To Programming" " +"in the "Introduction To Programming" " +
"course. {1} wishes you good luck!","course. {1} wishes you good luck!",
person, company);person, company);
Console.WriteLine(" Yours,");Console.WriteLine(" Yours,");
Console.WriteLine(" {0}", company);Console.WriteLine(" {0}", company);
Printing a LetterPrinting a Letter
Live DemoLive Demo
Calculating Area – ExampleCalculating Area – Example
Console.WriteLine("This program calculates " +Console.WriteLine("This program calculates " +
"the area of a rectangle or a triangle");"the area of a rectangle or a triangle");
Console.Write("Enter a and b (for rectangle) " +Console.Write("Enter a and b (for rectangle) " +
" or a and h (for triangle): ");" or a and h (for triangle): ");
int a = int.Parse(Console.ReadLine());int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());int b = int.Parse(Console.ReadLine());
Console.Write("Enter 1 for a rectangle or 2 " +Console.Write("Enter 1 for a rectangle or 2 " +
"for a triangle: ");"for a triangle: ");
int choice = int.Parse(Console.ReadLine());int choice = int.Parse(Console.ReadLine());
double area = (double) (a*b) / choice;double area = (double) (a*b) / choice;
Console.WriteLine("The area of your figure " +Console.WriteLine("The area of your figure " +
" is {0}", area);" is {0}", area);
30
Calculating AreaCalculating Area
Live DemoLive Demo
SummarySummary
 We have discussed the basic input and outputWe have discussed the basic input and output
methods of the classmethods of the class ConsoleConsole
 Write(…)Write(…) andand WriteLine(WriteLine(……))
 Used to write values to the consoleUsed to write values to the console
 Read(…)Read(…) andand ReadLine(ReadLine(……))
 Used to read values from the consoleUsed to read values from the console
 Parsing numbers to stringsParsing numbers to strings
 int.Parse(…)int.Parse(…),, double.Parse(…)double.Parse(…), …, …
32
Questions?Questions?
Console Input / OutputConsole Input / Output
http://academy.telerik.com
ExercisesExercises
1.1. Write a program that readsWrite a program that reads 33 integer numbers frominteger numbers from
the console and prints their sum.the console and prints their sum.
2.2. Write a program that reads the radiusWrite a program that reads the radius rr of a circleof a circle
and prints its perimeter and area.and prints its perimeter and area.
3.3. A company has name, address, phone number, faxA company has name, address, phone number, fax
number, web site and manager. The manager hasnumber, web site and manager. The manager has
first name, last name, age and a phone number.first name, last name, age and a phone number.
Write a program that reads the information about aWrite a program that reads the information about a
company and its manager and prints them on thecompany and its manager and prints them on the
console.console.
34
Exercises (2)Exercises (2)
4.4. Write a program that reads two positive integerWrite a program that reads two positive integer
numbers and prints how many numbersnumbers and prints how many numbers pp existexist
between them such that the reminder of the divisionbetween them such that the reminder of the division
byby 55 isis 00 (inclusive). Example:(inclusive). Example: p(17,25)p(17,25) == 22..
5.5. Write a program that gets two numbers from theWrite a program that gets two numbers from the
console and prints the greater of them. Don’t useconsole and prints the greater of them. Don’t use ifif
statements.statements.
6.6. Write a program that reads the coefficientsWrite a program that reads the coefficients aa,, bb andand cc
of a quadratic equationof a quadratic equation aaxx22
+b+bxx+c=0+c=0 and solves itand solves it
(prints its real roots).(prints its real roots).
35
Exercises (3)Exercises (3)
7.7. Write a program that gets a numberWrite a program that gets a number nn and after thatand after that
gets moregets more nn numbers and calculates and prints theirnumbers and calculates and prints their
sum.sum.
8.8. Write a program that reads an integer numberWrite a program that reads an integer number nn
from the console and prints all the numbers in thefrom the console and prints all the numbers in the
interval [interval [11....nn], each on a single line.], each on a single line.
9.9. Write a program to print the first 100 members ofWrite a program to print the first 100 members of
the sequence of Fibonaccithe sequence of Fibonacci: 0, 1, 1, 2, 3, 5, 8, 13, 21,: 0, 1, 1, 2, 3, 5, 8, 13, 21,
34, 55, 89, 144, 233, 377, …34, 55, 89, 144, 233, 377, …
10.10. Write a program to calculate the sum (with accuracyWrite a program to calculate the sum (with accuracy
of 0.001): 1 + 1/2 - 1/3 + 1/4 - 1/5 + ...of 0.001): 1 + 1/2 - 1/3 + 1/4 - 1/5 + ...
36

More Related Content

What's hot

What's hot (19)

C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
 
09. Methods
09. Methods09. Methods
09. Methods
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling
 
C++ Presentation
C++ PresentationC++ Presentation
C++ Presentation
 
Python basics
Python basicsPython basics
Python basics
 
14 strings
14 strings14 strings
14 strings
 
Unit ii ppt
Unit ii pptUnit ii ppt
Unit ii ppt
 
Cbasic
CbasicCbasic
Cbasic
 
COm1407: Character & Strings
COm1407: Character & StringsCOm1407: Character & Strings
COm1407: Character & Strings
 
Python programming workshop session 1
Python programming workshop session 1Python programming workshop session 1
Python programming workshop session 1
 
Fantom on the JVM Devoxx09 BOF
Fantom on the JVM Devoxx09 BOFFantom on the JVM Devoxx09 BOF
Fantom on the JVM Devoxx09 BOF
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
CSharp Language Overview Part 1
CSharp Language Overview Part 1CSharp Language Overview Part 1
CSharp Language Overview Part 1
 
C++
C++C++
C++
 
CS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 4 | Syntactic ServicesCS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 4 | Syntactic Services
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
streams and files
 streams and files streams and files
streams and files
 
C Programming Assignment
C Programming AssignmentC Programming Assignment
C Programming Assignment
 

Similar to 04 Console input output-

C# Language Overview Part I
C# Language Overview Part IC# Language Overview Part I
C# Language Overview Part I
Doncho Minkov
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02
Abdul Samee
 
(02) c sharp_tutorial
(02) c sharp_tutorial(02) c sharp_tutorial
(02) c sharp_tutorial
Satish Verma
 
434090527-C-Cheat-Sheet. pdf C# program
434090527-C-Cheat-Sheet. pdf  C# program434090527-C-Cheat-Sheet. pdf  C# program
434090527-C-Cheat-Sheet. pdf C# program
MAHESHV559910
 
The Morse code (see Table 6.10 in book) is a common code that is use.pdf
The Morse code (see Table 6.10 in book) is a common code that is use.pdfThe Morse code (see Table 6.10 in book) is a common code that is use.pdf
The Morse code (see Table 6.10 in book) is a common code that is use.pdf
bhim1213
 
INPUT AND OUTPUT PROCESSINGPlease note that the material o.docx
INPUT AND OUTPUT PROCESSINGPlease note that the material o.docxINPUT AND OUTPUT PROCESSINGPlease note that the material o.docx
INPUT AND OUTPUT PROCESSINGPlease note that the material o.docx
jaggernaoma
 

Similar to 04 Console input output- (20)

Wlkthru vb netconsole-inputoutput
Wlkthru vb netconsole-inputoutputWlkthru vb netconsole-inputoutput
Wlkthru vb netconsole-inputoutput
 
C#.net
C#.netC#.net
C#.net
 
Write and write line methods
Write and write line methodsWrite and write line methods
Write and write line methods
 
C# basics
 C# basics C# basics
C# basics
 
MongoDB World 2019: BSON Transpilers: Transpiling from Any Language to Any La...
MongoDB World 2019: BSON Transpilers: Transpiling from Any Language to Any La...MongoDB World 2019: BSON Transpilers: Transpiling from Any Language to Any La...
MongoDB World 2019: BSON Transpilers: Transpiling from Any Language to Any La...
 
C# Language Overview Part I
C# Language Overview Part IC# Language Overview Part I
C# Language Overview Part I
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
 
python-ch2.pptx
python-ch2.pptxpython-ch2.pptx
python-ch2.pptx
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02
 
Loops (1)
Loops (1)Loops (1)
Loops (1)
 
07-Basic-Input-Output.ppt
07-Basic-Input-Output.ppt07-Basic-Input-Output.ppt
07-Basic-Input-Output.ppt
 
(02) c sharp_tutorial
(02) c sharp_tutorial(02) c sharp_tutorial
(02) c sharp_tutorial
 
Fb cheatsheet12b
Fb cheatsheet12bFb cheatsheet12b
Fb cheatsheet12b
 
lecture 2.pptx
lecture 2.pptxlecture 2.pptx
lecture 2.pptx
 
434090527-C-Cheat-Sheet. pdf C# program
434090527-C-Cheat-Sheet. pdf  C# program434090527-C-Cheat-Sheet. pdf  C# program
434090527-C-Cheat-Sheet. pdf C# program
 
Kotlin: A pragmatic language by JetBrains
Kotlin: A pragmatic language by JetBrainsKotlin: A pragmatic language by JetBrains
Kotlin: A pragmatic language by JetBrains
 
Type script - advanced usage and practices
Type script  - advanced usage and practicesType script  - advanced usage and practices
Type script - advanced usage and practices
 
The Morse code (see Table 6.10 in book) is a common code that is use.pdf
The Morse code (see Table 6.10 in book) is a common code that is use.pdfThe Morse code (see Table 6.10 in book) is a common code that is use.pdf
The Morse code (see Table 6.10 in book) is a common code that is use.pdf
 
7512635.ppt
7512635.ppt7512635.ppt
7512635.ppt
 
INPUT AND OUTPUT PROCESSINGPlease note that the material o.docx
INPUT AND OUTPUT PROCESSINGPlease note that the material o.docxINPUT AND OUTPUT PROCESSINGPlease note that the material o.docx
INPUT AND OUTPUT PROCESSINGPlease note that the material o.docx
 

More from maznabili

More from maznabili (20)

22 Methodology of problem solving
22 Methodology of problem solving22 Methodology of problem solving
22 Methodology of problem solving
 
21 High-quality programming code construction part-ii
21 High-quality programming code construction part-ii21 High-quality programming code construction part-ii
21 High-quality programming code construction part-ii
 
21 high-quality programming code construction part-i
21 high-quality programming code construction part-i21 high-quality programming code construction part-i
21 high-quality programming code construction part-i
 
20 Object-oriented programming principles
20 Object-oriented programming principles20 Object-oriented programming principles
20 Object-oriented programming principles
 
19 Algorithms and complexity
19 Algorithms and complexity19 Algorithms and complexity
19 Algorithms and complexity
 
18 Hash tables and sets
18 Hash tables and sets18 Hash tables and sets
18 Hash tables and sets
 
17 Trees and graphs
17 Trees and graphs17 Trees and graphs
17 Trees and graphs
 
16 Linear data structures
16 Linear data structures16 Linear data structures
16 Linear data structures
 
15 Text files
15 Text files15 Text files
15 Text files
 
14 Defining classes
14 Defining classes14 Defining classes
14 Defining classes
 
13 Strings and text processing
13 Strings and text processing13 Strings and text processing
13 Strings and text processing
 
12 Exceptions handling
12 Exceptions handling12 Exceptions handling
12 Exceptions handling
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objects
 
10 Recursion
10 Recursion10 Recursion
10 Recursion
 
09 Methods
09 Methods09 Methods
09 Methods
 
08 Numeral systems
08 Numeral systems08 Numeral systems
08 Numeral systems
 
07 Arrays
07 Arrays07 Arrays
07 Arrays
 
06 Loops
06 Loops06 Loops
06 Loops
 
05 Conditional statements
05 Conditional statements05 Conditional statements
05 Conditional statements
 
03 Operators and expressions
03 Operators and expressions03 Operators and expressions
03 Operators and expressions
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Recently uploaded (20)

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Less Is More: Utilizing Ballerina to Architect a Cloud Data Platform
Less Is More: Utilizing Ballerina to Architect a Cloud Data PlatformLess Is More: Utilizing Ballerina to Architect a Cloud Data Platform
Less Is More: Utilizing Ballerina to Architect a Cloud Data Platform
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Navigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseNavigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern Enterprise
 

04 Console input output-

  • 1. Console Input / OutputConsole Input / Output Reading and Writing to the ConsoleReading and Writing to the Console Svetlin NakovSvetlin Nakov Telerik CorporationTelerik Corporation www.telerik.comwww.telerik.com
  • 2. Table of ContentsTable of Contents  Printing to the ConsolePrinting to the Console  Printing Strings and NumbersPrinting Strings and Numbers  Reading from the ConsoleReading from the Console  Reading CharactersReading Characters  Reading StringsReading Strings  Parsing Strings to Numeral TypesParsing Strings to Numeral Types  Reading Numeral TypesReading Numeral Types  Various ExamplesVarious Examples 2
  • 3. Printing to the ConsolePrinting to the Console Printing Strings, Numeral Types and ExpressionsPrinting Strings, Numeral Types and Expressions 3
  • 4. Printing to the ConsolePrinting to the Console  Console is used to display information in a textConsole is used to display information in a text windowwindow  Can display different values:Can display different values: StringsStrings Numeral typesNumeral types All primitiveAll primitive datadata typestypes  To print to the console use the classTo print to the console use the class ConsoleConsole ((System.ConsoleSystem.Console)) 4
  • 5. The Console ClassThe Console Class  Provides methods for console input and outputProvides methods for console input and output InputInput  Read(…)Read(…) – reads a single character– reads a single character  ReadKey(…)ReadKey(…) – reads a combination of keys– reads a combination of keys  ReadLine(…)ReadLine(…) – reads a single line of characters– reads a single line of characters OutputOutput  Write(…)Write(…) – prints the specified– prints the specified argument on the consoleargument on the console  WriteLine(…WriteLine(…)) – prints specified data to the– prints specified data to the console and moves to the next lineconsole and moves to the next line 5
  • 6. Console.Write(…)Console.Write(…)  Printing more than one variable using aPrinting more than one variable using a formatting stringformatting string int a = 15;int a = 15; ...... Console.Write(a); // 15Console.Write(a); // 15  Printing an integer variablePrinting an integer variable double a = 15.5;double a = 15.5; int b = 14;int b = 14; ...... Console.Write("{0} + {1} = {2}", a, b, a + b);Console.Write("{0} + {1} = {2}", a, b, a + b); // 15.5 + 14 = 29.5// 15.5 + 14 = 29.5  Next print operation will start from the same lineNext print operation will start from the same line 6
  • 7. Console.WriteLine(…)Console.WriteLine(…)  Printing more than one variable using aPrinting more than one variable using a formatting stringformatting string string str = "Hello C#!";string str = "Hello C#!"; ...... Console.WriteLine(str);Console.WriteLine(str);  Printing a string variablePrinting a string variable string name = "Marry";string name = "Marry"; int year = 1987;int year = 1987; ...... Console.Write("{0} was born in {1}.", name, year);Console.Write("{0} was born in {1}.", name, year); // Marry was born in 1987.// Marry was born in 1987.  Next printing will start from the next lineNext printing will start from the next line 7
  • 8. Printing to the Console – ExamplePrinting to the Console – Example static void Main()static void Main() {{ string name = "Peter";string name = "Peter"; int age = 18;int age = 18; string town = "Sofia";string town = "Sofia"; Console.Write("{0} is {1} years old from {2}.",Console.Write("{0} is {1} years old from {2}.", name, age, town);name, age, town); // Result: Peter is 18 years old from Sofia.// Result: Peter is 18 years old from Sofia. Console.Write("This is on the same line!");Console.Write("This is on the same line!"); Console.WriteLine("Next sentence will be" +Console.WriteLine("Next sentence will be" + " on a new line.");" on a new line."); Console.WriteLine("Bye, bye, {0} from {1}.",Console.WriteLine("Bye, bye, {0} from {1}.", name, town);name, town); }} 8
  • 9. Using Parameters – ExampleUsing Parameters – Example 9 static void Main()static void Main() {{ int a=2, b=3;int a=2, b=3; Console.Write("{0} + {1} =", a, b);Console.Write("{0} + {1} =", a, b); Console.WriteLine(" {0}", a+b);Console.WriteLine(" {0}", a+b); // 2 + 3 = 5// 2 + 3 = 5 Console.WriteLine("{0} * {1} = {2}",Console.WriteLine("{0} * {1} = {2}", a, b, a*b);a, b, a*b); // 2 * 3 = 6// 2 * 3 = 6 float pi = 3.14159206;float pi = 3.14159206; Console.WriteLine("{0:F2}", pi); // 3,14Console.WriteLine("{0:F2}", pi); // 3,14 Console.WriteLine("Bye – Bye!");Console.WriteLine("Bye – Bye!"); }}
  • 10. Printing a Menu – ExamplePrinting a Menu – Example double colaPrice = 1.20;double colaPrice = 1.20; string cola = "Coca Cola";string cola = "Coca Cola"; double fantaPrice = 1.20;double fantaPrice = 1.20; string fanta = "Fanta Dizzy";string fanta = "Fanta Dizzy"; double zagorkaPrice = 1.50;double zagorkaPrice = 1.50; string zagorka = "Zagorka";string zagorka = "Zagorka"; Console.WriteLine("Menu:");Console.WriteLine("Menu:"); Console.WriteLine("1. {0} – {1}",Console.WriteLine("1. {0} – {1}", cola, colaPrice);cola, colaPrice); Console.WriteLine("2. {0} – {1}",Console.WriteLine("2. {0} – {1}", fanta, fantaPrice);fanta, fantaPrice); Console.WriteLine("3. {0} – {1}",Console.WriteLine("3. {0} – {1}", zagorka, zagorkaPrice);zagorka, zagorkaPrice); Console.WriteLine("Have a nice day!");Console.WriteLine("Have a nice day!"); 10
  • 11. Printing toPrinting to the Consolethe Console Live DemoLive Demo
  • 12. Reading from the ConsoleReading from the Console Reading Strings and Numeral TypesReading Strings and Numeral Types
  • 13. Reading from the ConsoleReading from the Console  We use the console to read information fromWe use the console to read information from the command linethe command line  We can read:We can read: CharactersCharacters StringsStrings Numeral types (after conversion)Numeral types (after conversion)  To read from the console we use the methodsTo read from the console we use the methods Console.Read()Console.Read() andand Console.ReadLine()Console.ReadLine() 13
  • 14. Console.Read()Console.Read()  Gets a single character from the console (afterGets a single character from the console (after [Enter] is pressed)[Enter] is pressed)  Returns a result of typeReturns a result of type intint  ReturnsReturns -1-1 if there aren’t more symbolsif there aren’t more symbols  To get the actually read character weTo get the actually read character we need to cast it toneed to cast it to charchar int i = Console.Read();int i = Console.Read(); char ch = (char) i; // Cast the int to charchar ch = (char) i; // Cast the int to char // Gets the code of the entered symbol// Gets the code of the entered symbol Console.WriteLine("The code of '{0}' is {1}.", ch, i);Console.WriteLine("The code of '{0}' is {1}.", ch, i); 14
  • 15. Reading CharactersReading Characters fromfrom the Consolethe Console Live DemoLive Demo
  • 16. Console.ReadKey()Console.ReadKey()  Waits until a combination of keys is pressedWaits until a combination of keys is pressed  Reads a single character from console or aReads a single character from console or a combination of keyscombination of keys  Returns a result of typeReturns a result of type ConsoleKeyInfoConsoleKeyInfo  KeyCharKeyChar – holds the entered character– holds the entered character  ModifiersModifiers – holds the state of [Ctrl], [Alt], …– holds the state of [Ctrl], [Alt], … ConsoleKeyInfo key = Console.ReadKey();ConsoleKeyInfo key = Console.ReadKey(); Console.WriteLine();Console.WriteLine(); Console.WriteLine("Character entered: " + key.KeyChar);Console.WriteLine("Character entered: " + key.KeyChar); Console.WriteLine("Special keys: " + key.Modifiers);Console.WriteLine("Special keys: " + key.Modifiers); 16
  • 17. Reading KeysReading Keys from the Consolefrom the Console Live DemoLive Demo
  • 18. Console.ReadLine()Console.ReadLine()  Gets a line of charactersGets a line of characters  Returns aReturns a stringstring valuevalue  ReturnsReturns nullnull if the end of the input is reachedif the end of the input is reached Console.Write("Please enter your first name: ");Console.Write("Please enter your first name: "); string firstName = Console.ReadLine();string firstName = Console.ReadLine(); Console.Write("Please enter your last name: ");Console.Write("Please enter your last name: "); string lastName = Console.ReadLine();string lastName = Console.ReadLine(); Console.WriteLine("Hello, {0} {1}!",Console.WriteLine("Hello, {0} {1}!", firstName, lastName);firstName, lastName); 18
  • 19. Reading StringsReading Strings from the Consolefrom the Console Live DemoLive Demo
  • 20. Reading Numeral TypesReading Numeral Types  Numeral types can not be read directly from theNumeral types can not be read directly from the consoleconsole  To read a numeral type do the following:To read a numeral type do the following: 1.1. RRead a string valueead a string value 2.2. Convert (parse) it to the required numeral typeConvert (parse) it to the required numeral type  int.Parse(string)int.Parse(string) – parses a– parses a stringstring toto intint string str = Console.ReadLine()string str = Console.ReadLine() int number = int.Parse(str);int number = int.Parse(str); Console.WriteLine("You entered: {0}", number);Console.WriteLine("You entered: {0}", number); 20
  • 21. Converting Strings to NumbersConverting Strings to Numbers  Numeral types have a methodNumeral types have a method Parse(…)Parse(…) forfor extracting the numeral value from a stringextracting the numeral value from a string int.Parse(string)int.Parse(string) –– stringstring  intint longlong.Parse(string).Parse(string) –– stringstring  longlong floatfloat.Parse(string).Parse(string) –– stringstring  floatfloat CausesCauses FormatExceptionFormatException in case ofin case of errorerror string s = "123";string s = "123"; int i = int.Parse(s); // i = 123int i = int.Parse(s); // i = 123 long l = long.Parse(s); // l = 123Llong l = long.Parse(s); // l = 123L string invalid = "xxx1845";string invalid = "xxx1845"; int value = int.Parse(invalid); // FormatExceptionint value = int.Parse(invalid); // FormatException 21
  • 22. Reading Numbers from theReading Numbers from the Console – ExampleConsole – Example 22 static void Main()static void Main() {{ int a = int.Parse(Console.ReadLine());int a = int.Parse(Console.ReadLine()); int b = int.Parse(Console.ReadLine());int b = int.Parse(Console.ReadLine()); Console.WriteLine("{0} + {1} = {2}",Console.WriteLine("{0} + {1} = {2}", a, b, a+b);a, b, a+b); Console.WriteLine("{0} * {1} = {2}",Console.WriteLine("{0} * {1} = {2}", a, b, a*b);a, b, a*b); float f = float.Parse(Console.ReadLine());float f = float.Parse(Console.ReadLine()); Console.WriteLine("{0} * {1} / {2} = {3}",Console.WriteLine("{0} * {1} / {2} = {3}", a, b, f, a*b/f);a, b, f, a*b/f); }}
  • 23. Converting Strings toConverting Strings to Numbers (2)Numbers (2)  Converting can also be done using the methods ofConverting can also be done using the methods of thethe ConvertConvert classclass  Convert.ToInt32(string)Convert.ToInt32(string) –– stringstring  intint  Convert.ToSingle(string)Convert.ToSingle(string)–– stringstring  floatfloat  Convert.ToInt64(string)Convert.ToInt64(string)–– stringstring  longlong  Internally uses the parse methods of the numeralInternally uses the parse methods of the numeral typestypes string s = "123";string s = "123"; int i = Convert.ToInt32(s); // i = 123int i = Convert.ToInt32(s); // i = 123 long l = Convert.ToInt64(s); // l = 123Llong l = Convert.ToInt64(s); // l = 123L string invalid = "xxx1845";string invalid = "xxx1845"; int value = Convert.ToInt32(invalid); // FormatExceptionint value = Convert.ToInt32(invalid); // FormatException 23
  • 24. Reading NumbersReading Numbers from the Consolefrom the Console Live DemoLive Demo
  • 25. Error Handling when ParsingError Handling when Parsing  Sometimes we want to handle the errors whenSometimes we want to handle the errors when parsing a numberparsing a number  Two options: useTwo options: use trytry--catchcatch block orblock or TryParse()TryParse()  Parsing withParsing with TryParse()TryParse():: string str = Console.ReadLine();string str = Console.ReadLine(); int number;int number; if (int.TryParse(str, out number))if (int.TryParse(str, out number)) {{ Console.WriteLine("Valid number: {0}", number);Console.WriteLine("Valid number: {0}", number); }} elseelse {{ Console.WriteLine("Invalid number: {0}", str);Console.WriteLine("Invalid number: {0}", str); }} 25
  • 26. Parsing withParsing with TryParseTryParse()() Live DemoLive Demo
  • 27. Reading and PrintingReading and Printing to the Consoleto the Console Various ExamplesVarious Examples
  • 28. Printing a Letter – ExamplePrinting a Letter – Example 28 Console.Write("Enter person name: ");Console.Write("Enter person name: "); string person = Console.ReadLine();string person = Console.ReadLine(); Console.Write("Enter company name: ");Console.Write("Enter company name: "); string company = Console.ReadLine();string company = Console.ReadLine(); Console.WriteLine(" Dear {0},", person);Console.WriteLine(" Dear {0},", person); Console.WriteLine("We are pleased to tell you " +Console.WriteLine("We are pleased to tell you " + "that {1} has chosen you to take part " +"that {1} has chosen you to take part " + "in the "Introduction To Programming" " +"in the "Introduction To Programming" " + "course. {1} wishes you good luck!","course. {1} wishes you good luck!", person, company);person, company); Console.WriteLine(" Yours,");Console.WriteLine(" Yours,"); Console.WriteLine(" {0}", company);Console.WriteLine(" {0}", company);
  • 29. Printing a LetterPrinting a Letter Live DemoLive Demo
  • 30. Calculating Area – ExampleCalculating Area – Example Console.WriteLine("This program calculates " +Console.WriteLine("This program calculates " + "the area of a rectangle or a triangle");"the area of a rectangle or a triangle"); Console.Write("Enter a and b (for rectangle) " +Console.Write("Enter a and b (for rectangle) " + " or a and h (for triangle): ");" or a and h (for triangle): "); int a = int.Parse(Console.ReadLine());int a = int.Parse(Console.ReadLine()); int b = int.Parse(Console.ReadLine());int b = int.Parse(Console.ReadLine()); Console.Write("Enter 1 for a rectangle or 2 " +Console.Write("Enter 1 for a rectangle or 2 " + "for a triangle: ");"for a triangle: "); int choice = int.Parse(Console.ReadLine());int choice = int.Parse(Console.ReadLine()); double area = (double) (a*b) / choice;double area = (double) (a*b) / choice; Console.WriteLine("The area of your figure " +Console.WriteLine("The area of your figure " + " is {0}", area);" is {0}", area); 30
  • 32. SummarySummary  We have discussed the basic input and outputWe have discussed the basic input and output methods of the classmethods of the class ConsoleConsole  Write(…)Write(…) andand WriteLine(WriteLine(……))  Used to write values to the consoleUsed to write values to the console  Read(…)Read(…) andand ReadLine(ReadLine(……))  Used to read values from the consoleUsed to read values from the console  Parsing numbers to stringsParsing numbers to strings  int.Parse(…)int.Parse(…),, double.Parse(…)double.Parse(…), …, … 32
  • 33. Questions?Questions? Console Input / OutputConsole Input / Output http://academy.telerik.com
  • 34. ExercisesExercises 1.1. Write a program that readsWrite a program that reads 33 integer numbers frominteger numbers from the console and prints their sum.the console and prints their sum. 2.2. Write a program that reads the radiusWrite a program that reads the radius rr of a circleof a circle and prints its perimeter and area.and prints its perimeter and area. 3.3. A company has name, address, phone number, faxA company has name, address, phone number, fax number, web site and manager. The manager hasnumber, web site and manager. The manager has first name, last name, age and a phone number.first name, last name, age and a phone number. Write a program that reads the information about aWrite a program that reads the information about a company and its manager and prints them on thecompany and its manager and prints them on the console.console. 34
  • 35. Exercises (2)Exercises (2) 4.4. Write a program that reads two positive integerWrite a program that reads two positive integer numbers and prints how many numbersnumbers and prints how many numbers pp existexist between them such that the reminder of the divisionbetween them such that the reminder of the division byby 55 isis 00 (inclusive). Example:(inclusive). Example: p(17,25)p(17,25) == 22.. 5.5. Write a program that gets two numbers from theWrite a program that gets two numbers from the console and prints the greater of them. Don’t useconsole and prints the greater of them. Don’t use ifif statements.statements. 6.6. Write a program that reads the coefficientsWrite a program that reads the coefficients aa,, bb andand cc of a quadratic equationof a quadratic equation aaxx22 +b+bxx+c=0+c=0 and solves itand solves it (prints its real roots).(prints its real roots). 35
  • 36. Exercises (3)Exercises (3) 7.7. Write a program that gets a numberWrite a program that gets a number nn and after thatand after that gets moregets more nn numbers and calculates and prints theirnumbers and calculates and prints their sum.sum. 8.8. Write a program that reads an integer numberWrite a program that reads an integer number nn from the console and prints all the numbers in thefrom the console and prints all the numbers in the interval [interval [11....nn], each on a single line.], each on a single line. 9.9. Write a program to print the first 100 members ofWrite a program to print the first 100 members of the sequence of Fibonaccithe sequence of Fibonacci: 0, 1, 1, 2, 3, 5, 8, 13, 21,: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, …34, 55, 89, 144, 233, 377, … 10.10. Write a program to calculate the sum (with accuracyWrite a program to calculate the sum (with accuracy of 0.001): 1 + 1/2 - 1/3 + 1/4 - 1/5 + ...of 0.001): 1 + 1/2 - 1/3 + 1/4 - 1/5 + ... 36