Sei sulla pagina 1di 48

Pakistan Navy Engineering College /

National University of Sciences


& Technology

Computer Systems and Programming


CS-102
Lab Manual
(August 2012)
Prepared by
Engr. Sajid Saleem
Assistant Professor
EPE Department

UNIFIED CURRICULA 2012

Computer Systems and Programming


CS-102
(August 2012)

List Of Practicals
S
No
1.

Practicals

Week

Introduction and identification of components of a computer system.


Assembling and disassembling of computer hardware

2.

Exploration of MS Office (MS-Word, MS-Excel and MS-PowerPoint).

3.

Demonstration of Visual Studio 2005 Environment. Use of program editor,


compiler, linker and debugger. Sample program run and debug.

4.

Classes and Objects

5.

Methods and Instance Variables

6.

Control Statements (if-else)

7.

Control Statements (switch)

8.

Loops (for)

9.

Loops (while, do-while)

10.

Recursion

10,11

11.

Arrays

12,13

12.

Filing

14

13.

GUI

15

LAB 1
INTRODUCTION TO COMPUTER SYSTEM COMPONENTS
LAB OBJECTIVE
Introduction and identification of components of a computer system. Assemble and
disassembling of computer hardware.

OVERVIEW

Familiarization with the hardware components and ports commonly found in a real
PC system.
Familiarization with the often required operations like replacement and addition of
RAM or expansion cards.
Familiarization with the extraction of hardware resource information through window
system information.

TASK(S)
Number 1
Component
Power button
Reset button
Floppy drive
CD/DVD drive
Port for keyboard
Port for mouse
Serial port
Parallel port
LAN port
Power socket
USB port
Modem Port
Game Port
Processor socket
Memory slots
PCI slots
ISA slots
Battery for CMOS
BIOS chip
Motherboard chipset
AGP slot
Power supply
IDE Controller connectors

Found
(Yes/No)

How many Items

Manufacturer
Information

No. of
Pins/Holes

Number 2

Restart the PC using Windows Restart option, and when it restarts press F2 key to
enter BIOS setup.
Find out the details of Hard Disk, processor, available RAM from that screen.
Find out the menu on which you can set the Boot priorities so that you can manage
things in case of running a bootable floppy / CD-ROM.
There is a series of quick test performed at the boot startup that is called POST. Find
out the menu through which you can enable or disable that option.
When you are logged in to your PC, go to
Start Programs Accessories System Tools System Information
When you are logged in to your PC, go to
startcontrol paneladministrative toolscomputer management device
manager.
Compile the details from System Summary group and the Components group about
the hardware that is installed and recognized by your Operating System.

LAB # 02
EXPLORING MS-OFFICE
LAB OBJECTIVE
To explore Microsoft Word, PowerPoint, Excel.

OVERVIEW

The basic knowledge of Microsoft Word, PowerPoint, Excel.


The extensions of Microsoft Word, PowerPoint, Excel.
How to save the files made on Microsoft Word, PowerPoint, Excel.
The short-cut keys used in Microsoft Word, PowerPoint, Excel.
How to change the font, color of the font, size of the font, styles of the font etc in
Microsoft Office
About the rows & columns used in Microsoft-Excel.
About the different types of slides pattern used in Microsoft PowerPoint.
To make different kinds of official documents, such as CV, resumes etc.

TASK(S)
To find the functions of the given short-cut keys in Microsoft Word, PowerPoint, Excel.
SHORT-CUT KEYS

Ctrl + A

Ctrl + B

Ctrl + C

Ctrl + D

Ctrl + E

Ctrl + F

Ctrl + G

Ctrl + H

Ctrl + I

Ctrl + J

FUNCTION IN MSWORD

FUNCTION IN MSPOWERPOINT

FUNCTION IN MSEXCEL

Ctrl + K

Ctrl + L

Ctrl + M

Ctrl + N

Ctrl + O

Ctrl + P

Ctrl + Q

Ctrl + R

Ctrl + S

Ctrl + T

Ctrl + U

Ctrl + V

Ctrl + W

Ctrl + X

Ctrl + Y

Ctrl + Z

How To Add Printer

StartRun

Enter the text \\<server name / IP >

Double click the printer name to install

How To Open Faculty Share Folder

StartRun

Enter the text \\<server name / IP >

Open faculty share folder

Open the folder of the concerned teacher / faculty member.

LAB # 3
DEMONSTRATION OF VISUAL STUDIO 2005 ENVIROMENT
LAB OBJECTIVE
Demonstration of Visual Studio 2005 Environment .Use of program editor, compiler, linker and
debugger. Sample program run and debug

OVERVIEW
Overview of the Visual Studio 2005 IDE
There are many versions of Visual Studio available .We used the Microsoft Visual C# 2005
Express Edition, which supports only the Visual C# programming language. Microsoft also
offers a full version of Visual Studio 2005, which includes support for other languages in
addition to Visual C#, such as Visual Basic and Visual C++. Our screen captures and discussions
focus on the IDE of the Visual C# 2005 Express Edition. We assume that you have some
familiarity with Windows.
Again, we use fonts to distinguish between IDE features (such as menu names and menu items)
and other elements that appear in the IDE. We emphasize IDE features in a sans-serif bold
Helvetica font (e.g., File menu) and emphasize other elements, such as file names (e.g.,
Form1.cs) and property names, in a sans-serif Lucida font.
Introduction to Microsoft Visual C# 2005 Express Edition
To start Microsoft Visual C# 2005 Express Edition in Windows XP, select Start > All Programs
> Visual C# 2005 Express Edition. For Windows 2000 users, select Start > Programs > Visual
C# 2005 Express Edition. Once the Express Edition begins execution, the Start Page displays.
Depending on your version of Visual Studio, your Start Page may look different. For new
programmers unfamiliar with Visual C#, the Start Page contains a list of links to resources in the
Visual Studio 2005 IDE and on the Internet. From this point forward, we will refer to the Visual
Studio 2005 IDE simply as "Visual Studio" or "the IDE." For experienced developers, this page
provides links to the latest developments in Visual C# (such as updates and bug fixes) and to
information on advanced programming topics. Once you start exploring the IDE, you can return
to the Start Page by selecting the page from the location bar drop-down menu, by selecting View
> Other Windows > Start Page or by clicking the Start Page icon from the IDE's Toolbar. We use
the > character to indicate the selection of a menu command from a menu. For example, we use
the notation File > Open File to indicate that you should select the Open File command from the
File menu.

Creating the Console Application


After opening Visual C# 2005 Express, select File > New Project... to display the New Project
dialog, then select the Console Application template. In the dialog's Name field, type Welcome1.
Click OK to create the project. The IDE now contains the open console application. Note that the
editor window already contains some code provided by the IDE. The IDE inserts this extra code
to help organize the application and to provide access to some common classes in the .NET
Framework Class Library at this point in the book, this code is neither required nor relevant to
the discussion of this application; delete all of it.

Fig3.1

Fig3.2

The code coloring scheme used by the IDE is called syntax-color highlighting and helps you
visually differentiate application elements. Keywords appear in blue, and other text is black.

Fig3.3

Modifying the Editor Settings to Display Line Numbers


Visual C# Express provides many ways to personalize your coding experience. In this step, you
will change the settings so that your code matches that of this book. To have the IDE display line
numbers, select Tools > Options.... In the dialog that appears, click the Show all settings
checkbox on the lower left of the dialog, then click the plus sign next to Text Editor in the left
pane and select All Languages. On the right, check the Line Numbers check box. Keep the
Options dialog open.
Setting Code Indentation to Three Spaces per Indent
In the Options dialog that you opened in the previous step, click on the plus sign next to C# in
the left pane and select Tabs. Enter 3 for both the Tab Size and Indent Size fields. Any new code
you add will now use three spaces for each level of indentation. Click OK to save your settings,
close the dialog and return to the editor window.
Changing the Name of the Application File
For applications we create in this book, we change the default name of the application file (i.e.,
Program.cs) to a more descriptive name. To rename the file, click Program.cs in the Solution

Explorer window. This displays the application files properties in the Properties window .
Change the File Name property to Welcome1.cs.

Fig3.4

Writing Code
In the editor window (Fig 3.2), type the code from Fig 3.9. After you type (in line 10) the class
name and a dot (i.e., Console.), a window containing a scrollbar is displayed (Fig 3.5). This IDE
feature, called IntelliSense, lists a class's members, which include method names. As you type
characters, Visual C# Express highlights the first member that matches all the characters typed,
then displays a tool tip containing a description of that member. You can either type the
complete member name (e.g., WriteLine), double click the member name in the member list or
press the Tab key to complete the name. Once the complete name is provided, the IntelliSense
window closes.


Fig3.5

When you type the open parenthesis character, (, after Console.WriteLine, the Parameter Info
window is displayed (Fig. 3.6). This window contains information about the methods
parameters. There can be several versions of a method that is, a class can define several methods
that have the same name as long as they have different numbers and/or types of parameters.
These methods normally all perform similar tasks. The Parameter Info window indicates how
many versions of the selected method are available and provides up and down arrows for
scrolling through the different versions. For example, there are 19 versions of the WriteLine
method we use one of these 19 versions in our application. The Parameter Info window is one of
the many features provided by the IDE to facilitate application development. In the next several
chapters, you will learn more about the information displayed in these windows. The Parameter
Info window is especially helpful when you want to see the different ways in which a method
can be used. From the code in Fig 3.9, we already know that we intend to display one string with
WriteLine, so because you know exactly which version of WriteLine you want to use, you can
simply close the Parameter Info window by pressing the Esc key.

fig3.6

Saving the Application


Select File > Save All to display the Save Project dialog (Fig. 3.7). In the Location text box,
specify the directory where you want to save this project. We choose to save the project in the
MyProjects directory on the C: drive. Select the Create directory for solution checkbox (to
enable Visual Studio to create the directory if it does not already exist), and click Save.

fig3.7

Compiling and Running the Application


You are now ready to compile and execute your application. Depending on the type of
application, the compiler may compile the code into files with a .exe (executable) extension, a
.dll (dynamic link library) extension or one of several other extensions. Such files are called
assemblies and are the packaging units for compiled C# code. These assemblies contain the
Microsoft Intermediate Language (MSIL) code for the application.
To compile the application, select Build > Build Solution. If the application contains no syntax
errors, your console application will compile into an executable file (named Welcome1.exe, in
the project's directory). To execute this console application (i.e., Welcome1.exe), select Debug >
Start Without Debugging (or type <Ctrl> F5), which invokes the Main method (Fig 3.9). The
statement in line 10 of Main displays Welcome to C# Programming!. Figure 3.8 shows the
results of executing this application. Note that the results are displayed in a console window.
Leave the application open in Visual C# Express; we will go back to it later in this section.

Fig3.8

A Simple C# Application: Displaying a Line of Text


Every time you use a computer, you execute various applications that perform tasks for you. For
example, your e-mail application helps you send and receive e-mail, and your Web browser lets
you view Web pages from Web sites around the world. Computer programmers create these
applications.
Let us consider a simple application that displays a line of text. (Later in this section, we discuss
how to compile and run an application.) The application and its output are shown in Fig 3.9. The
application illustrates several important C# language features. C# uses notations that may look
strange to nonprogrammers. We now consider each line of the application this is called a code
walkthrough.
1 // Fig. 3.9: Welcome1.cs
2 // Text-printing application.
3 using System;
4
5 public class Welcome1
6 {
7
// Main method begins execution of C# application
8
public static void Main( string[] args )
9
{
10
Console.WriteLine( Welcome to C# Programming! );
11
} // end method Main
12 } // end class Welcome1

Fig 3.9
Line 1
// Fig 3.9: Welcome1.cs

begins with //, indicating that the remainder of the line is a comment. Programmers insert
comments to document applications and improve their readability. This helps people to read and
understand applications. The C# compiler ignores comments, so they do not cause the computer
to perform any action when the application is run. We begin every application with a comment
indicating the figure number and the name of the file in which the application is stored.
A comment that begins with // is called a single-line comment, because it terminates at the end
of the line on which it appears. A // comment also can begin in the middle of a line and continue
until the end of that line (as in lines 7, 11 and 12).
Delimited comments such as
/* This is a delimited
comment. It can be
split over many lines */

can be spread over several lines. This type of comment begins with the delimiter /* and ends
with the delimiter */. All text between the delimiters is ignored by the compiler. C# incorporated
delimited comments and single-line comments from the C and C++ programming languages,
respectively. In this book, we use only single-line comments in our programs.
Line 2
// Text-printing application.

is a single-line comment that describes the purpose of the application.


Line 3
using System;

is a using directive that helps the compiler locate a class that is used in this application. A great
strength of C# is its rich set of predefined classes that you can reuse rather than "reinventing the
wheel." These classes are organized under namespacesnamed collections of related classes.
Collectively, .NET's namespaces are referred to as the .NET Framework Class Library (FCL).
Each using directive identifies predefined classes that a C# application should be able to use.
The using directive in line 3 indicates that this example uses classes from the System
namespace, which contains the predefined Console class (discussed shortly) used in Line 10,
and many other useful classes.
Line 4 is simply a blank line. Programmers use blank lines and space characters to make
applications easier to read. Together, blank lines, space characters and tab characters are known
as whitespace. (Space characters and tabs are known specifically as whitespace characters.)
Whitespace is ignored by the compiler. In this and the next several chapters, we discuss
conventions for using whitespace to enhance application readability.
Line 5
public class Welcome1

begins a class declaration for the class Welcome1. Every application consists of at least one class
declaration that is defined by you the programmer. These are known as user-defined classes. The
class keyword introduces a class declaration and is immediately followed by the class name
(Welcome1). Keywords (sometimes called reserved words) are reserved for use by C# and are
always spelled with all lowercase letters.

TASK(S)
Create a new empty console project by your name. That prints your name, class and roll no.

LAB 4 & 5
CLASSES, OBJECTS, METHODS AND INSTANCE
VARIABLES
LAB OBJECTIVE
To learn, how to make classes, objects, methods and instant variable and how to use them in
programming.

OVERVIEW
In this lab, a student will be
1.
2.
3.
4.

Learning basic concepts of classes, objects, methods and instance variable.


Learning, how to make classes, objects, methods and instance variable.
Learning, how to use classes, objects, methods and instance variable.
Doing different tasks using classes, objects, methods and instance variable.

First Program in C#
1 //A Simple Welcome Program: Welcome.cs
2 // Namespace Declaration
3 using System;
4
5 // Program start class
6 class WelcomeCSS
7 {
8
// Main begins program execution.
9
static void Main()
10
{
11
// Write to console
12
Console.WriteLine("Welcome to the C# Station
Tutorial!");
13
}
14 }
The screen will run and close quickly when launching this program from Visual Studio .NET.
To prevent this, add the following code as the last line in the Main method:
// keep screen from going away
// when run from VS.NET
Console.ReadLine();
The above program has 4 primary elements:
1. a namespace declaration: A namespace declaration identifies and assigns a unique
name to a user-declared namespace.
2. a class: A class is a construct that enables you to create your own custom types by
grouping together variables of other types, methods and events. A class is like a
blueprint. It defines the data and behavior of a type.

3. a Main method: The one method within the WelcomeCSS class tells what
this class will do when executed. The method name, Main, is reserved for the starting
point of a program. Main is often called the "entry point" and if you ever receive a
compiler error message saying that it can't find the entry point, it means that you tried
to compile an executable program without a Main method.
4. a program statement: The Main method specifies its behavior with
the Console.WriteLine(...) statement. Console is a class in the System namespace.
WriteLine(...) is a method in the Console class. We use the ".", dot, operator to
separate subordinate program elements. Note that we could also write this statement
as System.Console.WriteLine(...). This follows the pattern "namespace.class.method"
as a fully qualified statement. Had we left out the using System declaration at the top
of the program, it would have been mandatory for us to use the fully qualified
formSystem.Console.WriteLine(...). This statement is what causes the string,
"Welcome to the C# Station Tutorial!" to print on the console screen. All statements
end with a ";", semi-colon. Classes and methods begin with "{", left curly brace, and
end with a "}", right curly brace. Any statements within and including "{" and "}"
define a block. Blocks define scope (or lifetime and visibility) of program elements.
Some common methods of console class are:
Console.Read()

Reads the next character from the standard input stream.

Console.ReadLine()

Reads the next line of characters from the standard input


stream.

Console.Write( TEXT )

Writes the text representation of the specified TEXT to the


standard output stream. TEXT can be int, double,
string,object .

Console.Writeline( TEXT )

Writes the text representation of the specified TEXT to the


standard output stream. TEXT can be int, double,
string,object .

Console.Writeline()

Writes the current line terminator to the standard output


stream.

Class declaration with one method.


1 // Example04_a1: GradeBook.cs
2 // Class declaration with one method.
3 using System;
4
5 public class GradeBook
6 {
7
// display a welcome message to the GradeBook user
8
public void DisplayMessage()
9
{
10
Console.WriteLine( "Welcome to the Grade
Book!");
11
} // end method DisplayMessage
12 } // end class GradeBook

Create a GradeBook object and call its DisplayMessage method.


1 // Example04_a2: GradeBookTest.cs
2 // Create a GradeBook object and call its
DisplayMessage method.
3
4 public class GradeBookTest
5 {
6
// Main method begins program execution
7
public static void Main( string[] args )
8
{
9
// create a GradeBook object and assign it to
myGradeBook
10
GradeBook myGradeBook = new GradeBook();
11
12
// call myGradeBook's DisplayMessage method
13
myGradeBook.DisplayMessage();
14
} // end Main
15 } // end class GradeBookTest

TheGradeBookclass declaration (Example04_a1) contains aDisplayMessagemethod


that displays a message on the screen. The keyword public is an access modifier. Every
class declaration contains keyword class followed by the class's name. Every class's body
is enclosed in a pair of left and right braces ({ and }), as in lines 6 and 12 of class
GradeBook. Keyword void known as the method's return typeindicates that this method
will not return (i.e., give back) any information to its calling method when it completes its
task. When a method that specifies a return type other than void is called and completes its
task, the method returns a result to its calling method. The body of a method contains
statement(s) that perform the method's task. In this case, the method contains one statement
(line 10) that displays the message "Welcome to the Grade Book!", followed by a
newline in the console window. After this statement executes, the method has completed its
task.
To add a class to your console application, right click the project name in the Solution
Explorer and select Add > New Item... from the pop-up menu. In the Add New Item dialog
that appears, select Code File and enter the name of your new filein this case,
GradeBookTest.cs. A new, blank file will be added to your project.
Declaring a Method with a Parameter
Class declaration with a method that has a parameter.
1 // Example04_b1: GradeBook.cs
2 // Class declaration with a method that has a
parameter.
3 using System;
4
5 public class GradeBook

6 {
7
// display a welcome message to the GradeBook user
8
public void DisplayMessage( string courseName )
9
{
10
Console.WriteLine( "Welcome to the grade book
for\n{0}!",
11
courseName );
12
} // end method DisplayMessage
13 } // end class GradeBook

Create GradeBook object and pass a string to its DisplayMessage method.


1 // Example04_b2: GradeBookTest.cs
2 // Create GradeBook object and pass a string to
3 // its DisplayMessage method.
4 using System;
5
6 public class GradeBookTest
7 {
8
// Main method begins program execution
9
public static void Main( string[] args )
10
{
11
// create a GradeBook object and assign it to
myGradeBook
12
GradeBook myGradeBook = new GradeBook();
13
14
// prompt for and input course name
15
Console.WriteLine( "Please enter the course
name:" );
16
string nameOfCourse = Console.ReadLine(); //
read a line of text
17
Console.WriteLine(); // output a blank line
18
19
// call myGradeBook's DisplayMessage method
20
// and pass nameOfCourse as an argument
21
myGradeBook.DisplayMessage( nameOfCourse );
22
} // end Main
23 } // end class GradeBookTest

In the above program the user have to enter a string which will be printed on a console screen
as a course name. The variable nameOfCourse in parentheses is the argument that is
passed to method DisplayMessage so that the method can perform its task. Variable
nameOfCourse's value in Main becomes the value of method DisplayMessage's
parameter courseName in line 8 of Example04_b1. When you execute this application,
notice that method DisplayMessage outputs the name you type as part of the welcome
message
Instance Variables and Properties
GradeBook class that contains a private instance variable, courseName and a public
property to get and set its value.
1 // Example04_c1: GradeBook.cs
2 // GradeBook class that contains a courseName instance
variable,
3 // and a property to get and set its value.
4 using System;
5
6 public class GradeBook
7 {

8
private string courseName; // course name for this
GradeBook
9
10
// property to get and set the course name
11
public string CourseName
12
{
13
get
14
{
15
return courseName;
16
} // end get
17
set
18
{
19
courseName = value;
20
} // end set
21
} // end property CourseName
22
23
// display a welcome message to the GradeBook user
24
public void DisplayMessage()
25
{
26
// use property CourseName to get the
27
// name of the course that this GradeBook represents
28
Console.WriteLine( "Welcome to the grade book
for\n{0}!",
29
CourseName ); // display property CourseName
30
} // end method DisplayMessage
31 } // end class GradeBook

Create and manipulate a GradeBook object.


1 // Example04_c2: GradeBookTest.cs
2 // Create and manipulate a GradeBook object.
3 using System;
4
5 public class GradeBookTest
6 {
7
// Main method begins program execution
8
public static void Main( string[] args )
9
{
10
// create a GradeBook object and assign it to
myGradeBook
11
GradeBook myGradeBook = new GradeBook();
12
13
// display initial value of CourseName
14
Console.WriteLine( "Initial course name is:
'{0}'\n",
15
myGradeBook.CourseName );
16
17
// prompt for and read course name
18
Console.WriteLine( "Please enter the course
name:" );
19
string theName = Console.ReadLine(); // read a

line of text
20
myGradeBook.CourseName = theName; // set name
using a property
21
Console.WriteLine(); // output a blank line
22
23
// display welcome message after specifying
course name
24
myGradeBook.DisplayMessage();
25
} // end Main
26 } // end class GradeBookTest

Class GradeBook (Example04_c1) maintains the course name as an instance variable so


that it can be used or modified at any time during an application's execution. The class also
contains one method DisplayMessage (lines 24-30) and one property CourseName
(line 11-21). Properties contain accessors that handle the details of returning and modifying
data. A property declaration can contain a get accessor, a set accessor or both. The get
accessor (lines 1316) enables a client to read the value of private instance variable
courseName; the set accessor (lines 1720) enables a client to modify courseName.

TASKS
1. Take input of 5 subject names and print them using classes & objects as shown in
Example04_b1 and Example04_b2.
2. Recode task 1 using constructors.
3. Recode task 2 separating interface from implementation. Also create your own header
files containing a class.
4. Create a class called Date that includes three pieces of information as data members a
month(type int), a day(type int) and a year(type integer). Your class should have a
constructor with three parameters to initialize the three data members. Provide a set
and a get function for each data member. Provide a member function displayDate that
displays a month, day and year separated by forward slash(/). Write a test program
that demonstrates class Dates capabilities.

LAB 6 & 7
CONTROL STATEMENTS (IF-ELSE, SWITCH)
OBJECT
To learn the use of if-else & switch statement.

OVERVIEW
In this lab, a student will be learning about:
1.
2.
3.
4.

The concept of conditional statement.


The difference between if and if-else statement.
The advantages of using switch.
The use of different conditional statement in C# coding.

1 //Example05_a.cs
2 #include <iostream>
3 #include<conio.h>
4 #include <string>
5
6 class Number
7 {
8 public:
9
Number( string no )
10
{
11
setIntegers( no );
12
}
13
14
void setIntegers( string no )
15
{
16
number = no;
17
}
18
string getIntegers()
19
{
20
return number;
21
}
22
void displayMessage()
23
{
24
Console.Writeline (Enter a numberget
integer !);
25
}
26 private:
27
string number;
28 };

29
30 int main ()
31
{
32
Number even( "number is even" );
33
Number odd( "number is odd" );
34
35
int a,b;
36
Console.Writeline ("Enter a number:"endl);
37
Console.Readline()a;
38
b=a%2;
39
if ( b==0 )
40 {Console.Writeline (a even.getIntegers())};
41
if ( b!=0 )
42
{Console.Writeline (a odd.getIntegers());}
43
getch();
44
return 0;
45}

We make a program to check the number is even or odd. To do this we use if control statements,
classes and constructors. This program tell us that we can use if control statements without using
else statements. The program checks whether the entered value is even or odd and print the
output stream which defined by user in a program.
1 // Example05_b.cs
2 #include<iostream>
3 #include<conio.h>
4 #include<string>
5
6 class Alphabets
7 {
8 public:
9
10
Alphabets( string name )
11
{
12
setAlphabet( name );
13 }
14
15
16
void setAlphabet( string name )
17
{
18
wordAlphabet = name;
19
}
20
string getAlphabet()
21
{
22
return wordAlphabet;

23
}
24 void displayMessage()
25
{
26
Console.Writeline ("Welcome to the grade book for\n"
getAlphabet() "!");
27
}
28 private:
29
string wordAlphabet;
30
};
31
32 int main ()
33
{
34
Alphabets vowel( "alphabet is vowel" );
35
Alphabets consonent( "alphabet is consonent" );
36
char p;
37
Console.Writeline ("enter an alphabet ");
38
Console.Readline()p;
39
if(p == 'a')
40
Console.Writeline (vowel.getAlphabet());
41
else
42
if( p == 'e' )
43
Console.Writeline (vowel.getAlphabet());
44
else
45
if( p == 'i' )
46
Console.Writeline (vowel.getAlphabet());
47
else
48
if( p == 'o' )
49
Console.Writeline (vowel.getAlphabet());
50
else
51
if ( p == 'u' )
52
Console.Writeline (vowel.getAlphabet());
53
else
54
Console.Writeline (consonent.getAlphabet());
55
_getch();
56
return 0;
To check the entered word is vowel or consonant we use if else control statements. We cannot
use else alone. Whenever a program contains else in it, it must contains if. Classes, Objects and
Constructors have also been used in the above program.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

// Example05_c.cs
#include<iostream>
#include<conio.h>
#include<string>
class Number
{
public:
Number( string no )
{
setIntegers( no );
}
void setIntegers( string no )
{
number = no;
}
string getIntegers()
{
return number;
}
void displayMessage()
{
Console.Writeline ("enter a number\n"
);
}
private:
string number;
};
int main()
{
Number even( "number is even" );
Number odd( "number is odd" );

getIntegers() "!"

int a,b;
Console.Writeline ("enter a number");
Console.Readline (a);
b=a%2;
switch ( b )
{
case 0:
Console.Writeline (even.getIntegers());
break;
default:
Console.Writeline (a odd.getIntegers());
}
_getch();

48
49}

return 0;

In the above program, a number will be taken input by a user and a program will tell whether a
number is even or odd number. Switch statement, constructors, classes and objects has been used
in this program.

TASKS
1. To make a calculator (5 functions) using if-else statement.
2. Take marks of 3 subjects input from user and display their grades using if-else
statement.
3. Recode task 1 using switch statement.
4. Recode task 2 using switch statement.
5. A palindrome is a number or a text phrase that reads the same backwards as forwards.
For example, each of the following five-digit integers is a palindrome: 12321, 55555,
45554 and 11611. Write a program using if else statements that reads in a five-digit
integer and determines whether it is a palindrome.
6. Write a code, that takes a 5-digit integer as an input from user and then prints the sum
of those 5 digits.

LAB 8 & 9
LOOPS (FOR, WHILE, DO-WHILE)
OBJECT
To learn how to repeat a particular task in C# programming.

OVERVIEW
In this lab, a student will be learning:
1. The basic concepts of loops.
2. The use of control statements in programming.
3. The way to repeat a particular task.
Consider these examples which will guide you in more better way:
Example 06-a
1 // Example06_a.cs
2
// Counter-controlled repetition with the for repetition
statement.
3 using System;
4
5 public class ForCounter
6 {
7
public static void Main( string[] args )
8
{
9
// for statement header includes initialization,
10
// loop-continuation condition and increment
11
for ( int counter = 1; counter <= 10; counter++ )
12
Console.Write( "{0} ", counter );
13
14
Console.WriteLine(); // output a newline
15
} // end Main
16 } // end class ForCounter
The above coding is representing an example of FOR LOOP. In the above coding, we have
declared a variable named counter and initializes it to 1. The parenthesis after FOR
contains 3 statements. In first statement, we have declared and initialized a variable. In second
statement, a condition of FOR LOOP has been shown. Means the FOR LOOP will repeats
itself unless this condition becomes false. And the third statement adds 1 to the variable
counter. As an output of this coding, a number series from 1 to 10 will be print in the same
line.

1 // Example06_b.cs
2
// Counter-controlled repetition with the while repetition
statement.
3 using System;
4
5 public class WhileCounter
6 {
7
public static void Main( string[] args )
8
{
9
While (counter <=10)
10
Console.Write( "{0} ", counter );
11
Counter=counter+1;//adds 1 to the counter
12
Console.WriteLine(); // output a newline
13
} // end Main
14
} // end class ForCounter

The above coding is representing an example of WHILE LOOP. In the above coding, we have
declared a variable named counter and initializes it to 1. The parenthesis after WHILE
contains a condition. Means the WHILE LOOP will repeats itself unless this condition
becomes false. And the counter=counter+1 statement adds 1 to the variable counter. As an
output of this coding, a number series from 1 to 10 will be print in the same line.

1 // Example06_c.cs : DoWhileTest.cs
2
// do...while repetition statement.
using System;
3
public class DoWhileTest
4
{
5
public static void Main( string[] args )
6
{
7
int counter = 1; // initialize counter
8
9
do
10
{
11
Console.Write( "{0} ", counter );
12
counter++;
13
} while ( counter <= 10 ); // end do...while
14
15
Console.WriteLine(); // outputs a newline
16
} // end Main
17
} // end class DoWhileTest

The above coding is representing an example of DO-WHILE LOOP. We have declared one
variable i.e. counter and initialized it to 1. The body of loop will repeat itself until the
condition becomes false. As an output of this coding, a number series from 1 to 10 will be print
in a same line. The statement counter ++ will increase the value of counter by adding 1 into
it.

The main difference between while & do-while loop is that a while loop will only execute if the
condition is true, otherwise it will not execute even once. On the other hand, a do-while loop
executes once. After that it will check the condition, if the condition is true than it will repeat
itself otherwise it will not repeat.

TASKS
1. Write a code that makes a calculator, and it will run as many times as user wants by using
FOR loop.
2. Write a code that takes the marks (out of 100) of subjects as an input from user and
calculate the sum of that marks using FOR loop. And the loop should repeat until the user
press q from a keyboard.
3. Write a code which draws a diamond shape with the help of * symbol using FOR loop.
4. Recode task # 01 using WHILE loop.
5. Recode task # 02 using WHILE loop.
6. Write a code that generates a random number and print any string that many times using
DO-WHILE loop.

LAB 10
Recursion
LAB OBJECTIVE
To learn and use recursion in C# programming language.

OVERVIEW
A recursive method is a method that calls itself, either directly or indirectly through another
method.
1
2
3
4
5
6
7
8
9
10
)
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

// Example07_a.cs
// Recursive Factorial method.
using System;
public class FactorialTest
{
public static void Main( string[] args )
{
// calculate the factorials of 0 through 10
for ( long counter = 0; counter <= 10; counter++
Console.WriteLine( "{0}! = {1}",
counter, Factorial( counter ));
} // end method Main
// recursive declaration of method Factorial
public static long Factorial( long number )
{
// base case
if ( number <= 1 )
return 1;
// recursion step
else
return number * Factorial( number - 1 );
} // end method Factorial
} // end class FactorialTest

To understand the concept of recursion program of Example07_a.cs is given. The program use
the recursion to find the factorial of different numbers. The method 16-24 take a number as a
long and also return number as a long which can be helpful to find the factorial of greater
number like 20.

1 // Example07_b.cs
2 // Testing the recursive fibonacci function.
3 using System;
4
5 unsigned long fibonacci( unsigned long ); // function
prototype
6
7 int main()
8 {
9
// calculate the fibonacci values of 0 through 10
10
for ( int counter = 0; counter <= 10; counter++ )
11
Console.Writeline ("fibonacci( " counter " ) = "
12
fibonacci( counter ) );
13
14
// display higher fibonacci values
15
Console.Writeline ("fibonacci( 20 ) = " << fibonacci( 20
) );
16
Console.Writeline ("fibonacci( 30 ) = " << fibonacci( 30
) );
17
Console.Writeline ("fibonacci( 35 ) = " fibonacci( 35 )
);
18
return 0; // indicates successful termination
19 } // end main
20
21 // recursive method fibonacci
22 unsigned long fibonacci( unsigned long number )
23 {
24
if ( ( number == 0 ) || ( number == 1 ) ) // base cases
25
return number;
26
else // recursion step
27
return fibonacci( number - 1 ) + fibonacci( number - 2
);
28}//endfunctionfibonacci

TASKS
1. Make a program that take 5 digit number from the user and print the some of them using
loop and recursion. e.g 12345=1+2+3+4+5=15.
2. Recode Example07_a.cs using loops.
3. Recode Example07_b.cs using loops.

LAB 11
ARRAYS
OBJECT
To learn the concepts of single-dimension and multi-dimensional array in C# language and
implement that in programming.

OVERVIEW
In this lab, a student will be learning about,
1. The concept of single-dimension array.
2. The concept of multi-dimensional array.
3. How to create different programs using the concepts of arrays
The following examples will help you in understanding.
1 // Example08_a.cs
2
// Creating an array.
3
using System;
4
5
public class InitArray
6
{
7
public static void Main( string[] args )
8
{
9
int[] array; // declare array named array
10
11
// create the space for array and initialize to
default zeros
12
array = new int[ 10 ]; // 10 int elements
13
14
Console.WriteLine( "{0}{1,8}", "Index", "Value"
15
); // headings
16
17
// output each array element's value
18
for ( int counter = 0; counter < array.Length;
counter++ )
19
Console.WriteLine( "{0,5}{1,8}", counter,
array[ counter ] );
20
} // end Main
21
} // end class InitArray

The above coding will simply generate a single-dimensional array. The array will consists of 10
elements that are integer in nature and are initially zero. The statement int[ ] array; declares an
array a reference capable of referring to an array of integer elements. The statement array=new
int[10]; creates the 10-elements array object and assigns its reference to variable array. As an
output of this coding two columns will create, the first column contains the index (09) of each
array element, and the second column contains the default value (0) of each array element and
has a field width of 8.
1 //Example08_b.cs
2 int i, j,cc=3;
3 int[,] arr1;
4 arr1 = new int[cc,cc];// indicate that a matrix is 3 x 3
5
6
//This will allow you to input the numbers individually
to fill the array.
7
for (i=0;i<cc;i++)
8
for (j=0;j<cc;j++)
9
{
Console.WriteLine("Entries row wise");
10
arr1 [i,j]=Int32.Parse(Console.ReadLine());
11
}
12
//This will output the array.
13
for (i = 0;i<cc;i++)
14
{
15
for (j=0; j<cc-2; j++)
16
Console.WriteLine("{0}
{1}
{2}", arr1[i,
j], arr1[i, j + 1], arr1[i, j + 2]);
17
}

Int32.Parse(): Converts the string representation of a number to its 32-bit signed integer
equivalent
In the above example, we have declared two integer type variable. By the help of these two
variables, a loop will be executed. In the 1st part, the integer will be taken input from user. And
in the 2nd part of this code a matrix will be printed on the screen containing the same entries as
input from user.

TASKS
1. Write a code that creates a matrix calculator containing the following FOUR functions:
Function # 1: Matrix addition
Function # 2: Matrix subtraction.
Function # 3: Multiply a matrix with any scalar.
Function # 5: Divide a matrix with any scalar.

2. Write a code that takes 2 matrix as an input from a user, then check that either those
matrix are possible for multiplication or not. If the multiplication is possible then
multiply them otherwise print that SORRY, MULTIPLICATION IS NOT POSSIBLE.
3. Write a code that takes 20 integers as an input from user and store them in 2 arrays of 20
elements each, such that even numbers are stored in one array and odd numbers are
stored in others.
4. Write a code that calculates the sum of integers using arrays.

LAB 12
FILING
OBJECT
To learn the concept of file handling, and implement it in C#.

OVERVIEW
File handling is an unmanaged resource in your application system. It is outside your application
domain (unmanaged resource). It is not managed by CLR.
Data is stored in TWO ways, persistent and non-persistent manner.
When you open a file for reading or writing, it becomes stream.
A stream is a sequence of bytes traveling from a source to a destination over a communication
path.
The TWO basic streams are input and output streams. Input stream is used to read, whereas
output stream is use to write.
The System.IO namespace includes various classes for file handling.
The parent class of file processing is stream. Stream is an abstract class, which is used as the
parent of the classes that actually implement the necessary operations.
The primary support of a file as an object is provided by a .NET Framework class called File.
This static class is equipped with various types of (static) methods to create, save, open, copy,
move, delete, or check the existence of a file.

The diagram is representing file-handling class hierarchy.

StreamWriter Class
The StreamWriter class in inherited from the abstract class TextWriter. The TextWriter class
represents a writer, which can write a series of characters.
The following table describes some of the methods used by StreamWriter class.
Methods
1. Close
2. Flush

3. Write
4. WriteLine

Description
Closes the current StreamWriter object and
underlying stream.
Clears all buffers for the current writer and
causes any buffered data to be written to the
underlying stream.
Writes to the stream
Writes data specified by the overloaded
parameters, followed by end of line

//Example09_a.cs
using System;
using System.Text;
using System.IO;
namespace FileWriting_SW
{
class Program
{
class FileWrite
{
public void WriteData()
{
FileStream fs = new FileStream("c:\\test.txt", FileMode.Append
, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
Console.WriteLine("Enter the text which you want to write to
the file");
string str = Console.ReadLine();
sw.WriteLine(str);
sw.Flush();
sw.Close();
fs.Close();
}
}
static void Main(string[] args)
{
FileWrite wr = new FileWrite();
wr.WriteData();

}
}
}

The above program is showing, that how to write user input to a file using StreamWriter Class.
StreamReader Class
The StreamReader class is inherited from the abstract class TextReader. The TextReader class
represents a reader, which can read series of characters.
The following table describes some methods of the StreamReader Class.
Methods
1. Close

Description
Closes the object of StreamReader class and
the underlying stream, and release any system
resources associated with the reader.

2. Peek

Returns the next available character but doesn't


consume it.

3. Read

Reads the next character or the next set of


characters from the stream.

4. ReadLine

Reads a line of characters from the current


stream and returns data as a string.

5. Seek

Allows the read/write position to be moved to


any position with the file.

//Example09_b.cs
using System;
using System.IO;
namespace FileReading_SR
{
class Program
{
class FileRead
{
public void ReadData()
{
FileStream fs = new FileStream("c:\\test.txt", FileMode.Open,
FileAccess.Read);
StreamReader sr = new StreamReader(fs);
Console.WriteLine("Program to show content of test file");
sr.BaseStream.Seek(0, SeekOrigin.Begin);
string str = sr.ReadLine();
while (str != null)
{
Console.WriteLine(str);
str = sr.ReadLine();
}
Console.ReadLine();
sr.Close();
fs.Close();
}
}
static void Main(string[] args)
{
FileRead wr = new FileRead();
wr.ReadData();
}
}
}

The above program is showing, how to read from a file using StreamReader Class.

The following table describes some commonly used classes in the system.IO namespace.
Class Name
1. FileStream
2. BinaryReader
3. BinaryWriter
4. StreamReader
5.
6.
7.
8.
9.

StreamWriter
StringReader
StringWriter
DirectoryInfo
FileInfo

Description
It is used to read from and write to any location
within a file.
It is used to read primitive data types from a
binary stream.
It is used to write primitive data types in binary
format.
It is used to read characters from a byte
Stream.
It is used to write characters to a stream.
It is used to read from a string buffer.
It is used to write into a string buffer.
It is used to perform operations on directories.
It is used to perform operations on file.

Knowledge about FileAccess


A FileAccess parameter is specified in many of the constructors for File, FileInfo, FileStream,
and other constructors where it is important to control the kind of access users have to a file.
Some of the members are
Member Name
1. Read
(Supported by the .NET Compact
Framework.)
2. ReadWrite
(Supported by the .NET Compact
Framework.)
3. Write
(Supported by the .NET Compact
Framework.)

Description
Read access to the file. Data can be read from
the file. Combine with Write for read/write
access.
Read and Write access to the file. Data can be
written to and read from the file.
Write access to the file. Data can be written to
the file. Combine with Read for read/write
access.

Knowledge about FileMode


A FileMode parameter is specified in many of the constructors for FileStream,
IsolatedStorageFileStream and in the Open methods of File and FileInfo to control how a file is
opened.
FileMode parameters control whether a file is overwritten, created, or opened, or some
combination thereof. Use Open to open an existing file. To append to a file, use Append. To
truncate a file or to create it if it does not exist, use Create.

Some of the members are:


Member Name
1. Append
(Supported by the .NET Compact
Framework).

2. Create
(Supported by the .NET Compact
Framework).

3. CreateNew
(Supported by the .NET Compact
Framework).
4. Open
(Supported by the .NET Compact
Framework).

5. OpenOrCreate
(Supported by the .NET Compact
Framework).

6. Truncate
(Supported by the .NET Compact
Framework).

Description
Opens the file if it exists and seeks to the end
of the file, or creates a new file.
FileMode.Append can only be used in
conjunction with FileAccess.Write. Any
attempt to read fails and throws an
ArgumentException.
Specifies that the operating system should
create a new file. If the file already exists, it
will be overwritten. This requires
FileIOPermissionAccess.Write and
FileIOPermissionAccess.Append.
System.IO.FileMode.Create is equivalent to
requesting that if the file does not exist, use
CreateNew; otherwise, use Truncate.
Specifies that the operating system should
create a new file. This requires
FileIOPermissionAccess.Write. If the file
already exists, an IOException is thrown.
Specifies that the operating system should
open an existing file. The ability to open the
file is dependent on the the value specified by
FileAccess. A
System.IO.FileNotFoundException is thrown if
the file does not exist.
Specifies that the operating system should
open a file if it exists; otherwise, a new file
should be created. If the file is opened with
FileAccess.Read,
FileIOPermissionAccess.Read is required. If
file access is FileAccess.ReadWrite and the
file exists, FileIOPermissionAccess.Write is
required. If file access is
FileAccess.ReadWrite and the file does not
exist, FileIOPermissionAccess.Append is
required in addition to Read and Write.
Specifies that the operating system should
open an existing file. Once opened, the file
should be truncated so that its size is zero
bytes. This requires
FileIOPermissionAccess.Write. Attempts to
read from a file opened with Truncate cause
an exception.

TASKS
1. Read a file and count the number of characters in it.
2. Using two-dimensional array, take 5 names as an input from a user and print them in a
file.

LAB 13
GUI (Graphical User Interface)
OBJECT
The objectives of this lab are:
1. To learn the use of Textbox, Label and Buttons by writing a program that displays the
password entered in the textbox after the button is pressed.
2. To practice and manipulate the Anchor and Dock properties of a control.
3. To practice the basics of Group Boxes and Panels.

OVERVIEW
Labels, Textboxes and Buttons
Labels provide text instructions or information about the program. Labels are defined with class
Label, which derives from class Control. A Label displays read-only text, or text that the user
cannot modify. Once labels are created, programs rarely change their contents.
A textbox (class TextBox) is an area in which text can be either input by the user from the
keyboard or displayed. A password textbox is a TextBox that hides what the user entered. As the
user types in characters, the password textbox displays only a certain character (usually *).
Altering the PasswordChar property of a textbox makes it a password textbox and sets the
appropriate character to be displayed. Deleting the value of PasswordChar in the Properties
window sets the textbox back to a regular textbox.
A button is a control that the user clicks to trigger a specific action. A program can use several
other types of buttons, such as checkboxes and radio buttons.
Steps to Follow:
1. First, create the GUI by dragging the components (a Button, a Label and a TextBox) onto
the form.
2. Change their names in the Properties window (by setting the (Name) property) from the
default values textBox1, label1, button1 to displayPasswordLabel,
inputPasswordTextBox and displayPasswordButton.
3. Then set displayPasswordLabels Text property to Show Me and clear the Text of
displayPasswordLabel and inputPasswordTextBox so that they are initially blank when
the program runs.
4. Set the BorderStyle property of displayPasswordLabel to Fixed3D.
5. The password character is set by assigning the asterisk character (*) to the PasswordChar
property. This property can take only one character.

Control Properties Anchor and Dock


Visual Studio .NET allows the programmer to anchor and dock controls, which help to specify
the layout of controls inside a container (such as a form). Anchoring allows controls to stay a
fixed distance from the sides of the container, even when the control is resized. Docking allows
controls to extend themselves along the sides of their containers.
A user may want a control to appear in a certain position (top, bottom, left or right) in a form
even when that form is resized. The user can specify this by anchoring the control to a side (top,
bottom, left or right). The control then maintains a fixed distance from the side to its parent
container. In most cases, the parent container is a form; however, other controls can act as a
parent container.
When parent containers are resized, all controls move. Unanchored controls move relative to
their original position on the form, while anchored controls move so that they will be the same
distance from each side that they are anchored to.

Sometimes a programmer wants a control to span the entire side of the form, even when the form
is resized. This is useful when we want one control to remain prevalent on the form, such as the
status bar that might appear at the bottom of a program.
Docking allows a control to spread itself along an entire side (left, right, top or bottom) of its
parent container. When the parent is resized, the docked control resizes as well. In the following
figure, a button is docked to the top of the form. (It lies across the top portion.) When the form is
resized, the button is resized as wellthe button always fills the entire top portion of the form.
The Fill dock option effectively docks the control to all sides of its parent, which causes it to fill
its entire parent. Windows Forms contain property DockPadding, which sets the distance from
docked controls to the edge of the form. The default value is zero, causing the controls to attach
to the edge of the form.

Group Boxes and Panels


GroupBoxes and Panels arrange components on a GUI. For example, buttons related to a
particular task can be placed inside a GroupBox or Panel inside the Visual Studio .NET form
designer. All these buttons move together when the GroupBox or Panel is moved.
The main difference between the two classes is that GroupBoxes can display a caption, and
Panels can have scrollbars. The scrollbars allow the user to view additional controls inside the
Panel by scrolling the visible area. GroupBoxes have thin borders by default, but Panels can be
set to have borders by changing their BorderStyle property.

TASKS
1. Write a suitable line in the code that displays the entered text in the textbox in the Label
after the button is pressed.

2. Create a simple windows application that contains two controls. Anchor one control to
the right side by setting the Anchor properties as shown in the following figure. Leave
the other control unanchored. Now, resize the form by dragging the right side farther to
the right.
Notice that both controls move. The anchored control moves so that it is always the same
distance to the right wall. The unanchored control moves so that it is in the same place on
the form, relative to each side. This control will continue to be somewhat closer to
whatever sides it was originally close to, but will still reposition itself when the user
resizes the application window.

3. Write a program to bring the following output.

Potrebbero piacerti anche