INTRODUCTION TO COMPUTER SCIENCE Lab
1 | P a g e
Introduction to Computer Science-
CSE1007L
Laboratory Manual
School of Engineering
Computer Science Department
G D Goenka University
Gurgaon, Haryana
Name:
Roll Number:
Section/Group:
Introduction to Computer Science Lab
2 | P a g e
The document is for internal circulation only.
Copyright © 2013 G D Goenka University. All rights reserved.
All materials on these pages are copyrighted by the G D Goenka University. All rights reserved. Reproduction, modification, retransmission, in any form or by any means, electronic, mechanical or otherwise, for reasons other than personal use, is strictly prohibited without prior written permission.
First Edition Month, Year
Published by:
SCHOOL OF ENGINEERING
Department of Computer Science and Information Technology
INTRODUCTION TO COMPUTER SCIENCE Lab
3 | P a g e
Gurgaon, Haryana
PREFACE
The School of Engineering (SoE), GDGU has prepared this laboratory manual. It is designed as an instruction book for purposes listed in order of importance as follows:
1. To provide techniques, procedures and precautions related to the experiments. 2. To provide the laboratory safety and general rules and instructions.
3. To provide a general reference book that will give information which will assist in the understanding of details about the laboratory and the experiment to be performed.
The manual is prepared with the idea that the revisions must be made periodically in order to have the available text that represents the experiments. It has been tried to maintain the format with diagrams, tables and illustrations.
It is believed that the information in the manual will enhance the practical skills of the students along with developing the base of the subject.
Any suggestions and comments for further improvement of this manual will be gratefully acknowledged.
Authors
Introduction to Computer Science Lab
4 | P a g e
Table of Contents
S. No. Experiment Title Page
No.
1
Understanding the functional block diagram of computer:
CPU, Buses, Motherboard, RAM, Harddisk, CDROm, Keyboard, mouse and
printer. 6
2 Problem solving using Flowchart and Algorithm 7-8
3
Introduction to C programming concepts Write a program in C to print “Hello World”.
Write a program to perform addition, subtraction, multiplication, division and modulus using two operands.
Write a C program find average of three numbers. Write a C program to swap two numbers.
Write a C program to compute area and perimeter of a rectangle.
9-13
4
Understanding control structures in C:
Write a C program to check if number entered by the user is even or odd. Write a C program to find the greatest of three numbers.
Write a C program to check whether the Entered year is leap year or not. Write a C program to implement traffic light system
(using nested ifs).
14-16
5
Learning Switch Case in C:
Write a C program to design calculator with basic operations using switch. Write a menu driven program in C with following options:
1. Finding factorial of a number 2. Finding if number is prime or not 3. Finding if number is odd or even 4. Exit
17-18
6
Understanding String handling in C:
Write a C program to calculate the length of a string without using strlen() function.
Write a C program to concatenate two strings. 19
7
Understanding Loops in C:
Write a C program to find the sum of first n natural numbers where n is entered by user.
Write a C program to add all the numbers entered by a user until user enters 0. Write a C program to count the number of digits in a number.
Write a C program to reverse a number.
INTRODUCTION TO COMPUTER SCIENCE Lab
5 | P a g e
8
Learning Functions in C:
Write a C program to find sum of n natural numbers using functions.
Write a C program to find if number entered by the user is prime using functions. Write a C program to reverse a number using recursion.
Write a C program to power of a number entered by the user using recursion.
24-25
9
Understanding 1D and 2D Arrays in C: Write a program to display a matrix
Write a C program to find transpose of a matrix.
Write a C program to add two dimensional matrix using multi-dimensional matrix. Write a C program to multiply two matrix using multi-dimensional matrix.
26-29
10
Learning File Handling in C:
Write a C program to read data from the file and display on screen.
Introduction to Computer Science Lab
6 | P a g e
Experiment 1
Date of Performance__________ Date of Submission ____________Faculty’s Signature ______________
Understanding the functional block diagram of computer, CPU, Buses, Motherboard, RAM, Hard disk, CDROM, Keyboard, mouse and printer.
A computer is an electronic device, which mainly performs the four functions as reading, processing, displaying and storing on data. These functions of a computer system can be carried out by using the three main units namely input unit, system unit and output unit. The block diagram of a computer system is as follows :
Problem
INTRODUCTION TO COMPUTER SCIENCE Lab
7 | P a g e
Experiment 2
Date of Performance__________ Date of Submission ____________Faculty’s Signature ______________
Problem solving using Flowchart and Algorithm
The set of rules (unambiguous statements) that define how a particular problem can be solved in finite sequence of steps is known as algorithm.
To develop an algorithm. Follow the below steps: 1. Understand the problem
2. Identify the output of the problem
3. Identify the inputs required by the problem to reach the desired output 4. Design a logic to produce the desired result
5. Test the algorithm
6. Repeat step 1 to 5 till desired results are produced
A Flowchart is a pictorial representation of an algorithm.It is a symbolic diagram of operation sequence, dataflow ,control flow and processing logic in information processing.The symbol used are simple and easy to learn.It is a very helpful tool for programmers and beginners .
Symbol Purpose Description
Flow line Used to indicate the flow of logic by connecting symbols.
Terminal(Stop/Start) Used to represent start and end of flowchart.
Input/Output Used for input and output operation.
Processing Used for airthmetic operations and data-manipulations.
Introduction to Computer Science Lab
8 | P a g e
Problems:
Write an algorithm and draw flowchart for the following:
1.To check if the number entered by the user is odd or even. 2.To calculate even numbers between 20 and 40
3.To input a natural number, n, and calculate the odd numbers equal or less than n.
4.To Convert Temperature from Fahrenheit (℉) to Celsius (℃)
5. To check whether a number is prime number or not. 6.To calculate the roots of Quadratic Equation.
INTRODUCTION TO COMPUTER SCIENCE Lab
9 | P a g e
Experiment 3
Date of Performance__________ Date of Submission ____________Faculty’s Signature ______________
Introduction to C programming Concepts
Having read this section you should be able to:
1. Edit, link and run your C programs
This section is primarily aimed at the beginner who as no or little experience of using compiled languages. We cover the various stages of program development. The basic principles of this section will apply to what ever C compiler you choose to use, the stages are nearly always the same.
A C program basically consists of the following parts −
• Preprocessor Commands
• Functions
• Variables
• Statements & Expressions
• Comments
Writing and editing programs
Use any text editor (Ascii) available on your computer. Example: windows (Edit, TCIDE , Notepad), Linux( Vi, Vim, emacs etc.).
A simple program to print “Hello World” in C:
#include <stdio.h>
int main() {
/* my first program in C */
Introduction to Computer Science Lab
10 | P a g e
return 0;
}
Operator and Expressions
Operators are the symbol which operates on value or a variable. For example: + is a operator to perform addition. C programming language has wide range of operators to perform various operations. For better understanding of operators, these operators can be classified as:
Operators in C Programming Arithmetic Operators
Increment and Decrement Operators Assignment Operators
Relational Operators Logical Operators Conditional Operators Bitwise Operators Special Operators
Arithmetic Operators
Operator Meaning of Operator
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ Division
% Remainder after division( Modulo division)
Increment and Decrement Operators
INTRODUCTION TO COMPUTER SCIENCE Lab
11 | P a g e Difference between ++ and – operator as prefix and postfix
When i++ is used as prefix (like: ++var), ++var will increment the value of var and then return it but, if ++ is used as postfix (like: var++), operator will return the value of operand first and then only increment it
Assignment Operator
The most common assignment operator is =. This operator assigns the value in right side to the left side. For example:
Operator Example Same As
= a=b a=b
+= a+=b a=a+b
-+ a-=b a=a-b
*= a*=b a=a*b
/= a/=b a=a/b
%= a%=b a=a%b
Relational Operators
Relational operators checks relationship between two operands. If the relation is true, it returns value 1 and if the relation is false, it returns value 0. For example:
Here, > is a relational operator. If a is greater than b, a>b returns 1 if not then, it returns 0. Relational operators are used in decision making and loops in C programming.
Operator Meaning of Operator Example
= = Equal to 5==3 return false (0)
> Greater than 5>3 return true (1)
< Less than 5<3 return false (0)
!= Not equal to 5!=3 return true (1)
Introduction to Computer Science Lab
12 | P a g e
<= Less than or equal to 5<=3 return false (0)
Logical Operators
Logical operators are used to combine expressions containing relation operators. In C, there are 3 logical operators: -
Operator Meaning of Operator Example
&& Logical AND If c=5 and d=2 then, ((c==5) && (d>5)) returns false.
|| Logical OR If c=5 and d=2 then ((c== 5) || (d>5))
returns false.
! Logical NOT If c=5 then, ! (c==5) returns false.
Explanation
For expression, ((c==5) && (d>5)) to be true, both c==5 and d>5 should be true but, (d>5) is false in the given example. So, the expression is false. For expression ((c==5) || (d>5)) to be true, either the expression should be true. Since, (c==5) is true. So, the expression is true. Since, expression (c==5) is true, !(c==5) is false.
Conditional Operators
Conditional operator takes three operands and consists of two symbols? and: . Conditional operators are used for decision making in C. For example:
If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10.
Bitwise Operators: A bitwise operator works on each bit of data. Bitwise operators are used in bit level programming.
Operator Meaning of Operator
& Bitwise AND
| Bitwise OR
INTRODUCTION TO COMPUTER SCIENCE Lab
13 | P a g e
~ Bitwise Complement
<< Shift left
>> Shift right
Special Operators
Comma Operator
Comma operators are used to link related expressions together. For example:
The Sizeof Operator
It is a unary operator which is used in finding the size of data type, constant, arrays, structure etc.
Conditional Operators (?:)
Conditional operators are used in decision making in C programming, i.e, executes different statements according to test condition whether it is either true or false
Syntax of Conditional Operator:
If the test condition is true, expression1 is returned and if false expression2 is returned.
Programs:
1. Write a program in C to print “Hello World”.
2. Write a program to perform addition, subtraction, multiplication, division and modulus using two operands.
3. Write a C program find average of three numbers.
4. Write a C program to print value entered by user in decimal, octal and hexadecimal.
5. Write a C program to find size of int, float and char data type.
6. Write a C program to swap two numbers.
Introduction to Computer Science Lab
14 | P a g e
Experiment 4
Date of Performance__________ Date of Submission ____________Faculty’s Signature ______________
Control Structure
If Statement
If statement is a conditional branching statement. In conditional branching statement a condition is evaluated, if it is evaluate true a group of statement is executed. The simple format of an if statement is as follows:
INTRODUCTION TO COMPUTER SCIENCE Lab
15 | P a g e if else statement:
The if...else statement is used, if the programmer wants to execute some code, if the test expression is true and execute some other code if the test expression is false. The general form of the if-else statement is
Flowchart of if-else statement
If-elseif-else Statement
Introduction to Computer Science Lab
16 | P a g e
How nested if...else works?
If the test expression is true, it will execute the code before else part but, if it is false, the control of the program jumps to the else part and check test expression 1 and the process continues. If all the test expression are false then, the last statement is executed. The ANSI standard specifies that 15 levels of nesting may be continued.
Programs:
1. Write a C program to check if number entered by the user is even or odd. 2. Write a C program to find the greatest of three numbers.
3. Write a C program to check whether the Entered year is leap year or not. 4. Write a C program to relate two integers entered by user using = or > or < sign. 5. Write a C program to implement traffic light program (using nested ifs).
INTRODUCTION TO COMPUTER SCIENCE Lab
17 | P a g e
Experiment 5
Date of Performance__________ Date of Submission ____________Faculty’s Signature ______________
C Switch- case statement
Decision making are needed when, the program encounters the situation to choose a particular statement among many statements. If a programmer has to choose one among many alternatives if...else can be used but, this makes programming logic complex. This type of problem can be handled in C programming using switch...case statement.
Syntax of Switch-case statement
Introduction to Computer Science Lab
18 | P a g e Programs:
1.Write a C program to design calculator with basic operations using switch. 2.Write a menu driven program in C with following options:
INTRODUCTION TO COMPUTER SCIENCE Lab
19 | P a g e
Experiment 6
Date of Performance__________ Date of Submission ____________Faculty’s Signature ______________
Understanding String handling in C:
Strings are actually one-dimensional array of characters terminated by a nullcharacter '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null.
The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
1.strcpy(s1, s2)
Copies string s2 into string s1.
2.strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
3.strlen(s1);
Returns the length of string s1.
4.strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
5.strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.
6.strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1
Programs:
Introduction to Computer Science Lab
20 | P a g e
Experiment 7
Date of Performance__________ Date of Submission ____________Faculty’s Signature ______________
C Programming Loops
Loops causes program to execute the certain block of code repeatedly until some conditions are satisfied, i.e., loops are used in performing repetitive work in programming. Suppose you want to execute some code/s 100 times. You can perform it by writing that code/s only one time and repeat the execution 100 times using loop.
There are 3 types of loops in C programming:
1. for loop 2. while loop
3. do...while loop
For Loop
For loop in C is the most general looping construct. The loop header contains three parts: an initialization, a continuation condition, and update expression.
Syntax of for loop
In the pseudo code above:
• Variable initialization is the initialization of counter of loop.
• Condition is any logical condition that controls the number of times the loop statements are
executed.
INTRODUCTION TO COMPUTER SCIENCE Lab
21 | P a g e The initial expression is initialized only once at the beginning of the for loop. Then, the test expression is checked by the program. If the test expression is false, for loop is terminated. But, if test expression is true then, the codes are executed and update expression is updated. Again, the test expression is checked. If it is false, loop is terminated and if it is true, the same process repeats until test expression is false.
This flowchart describes the working of for loop in C programming.
While loop
Introduction to Computer Science Lab
22 | P a g e
In the beginning of while loop, test expression is checked. If it is true, codes inside the body of while loop,i.e, code/s inside parentheses are executed and again the test expression is checked and process continues until the test expression becomes false.
Do-while loop
This construct is also used for looping. In this case the loop condition is tested at the end of the body of the loop. Hence the loop is executed at least one.
Syntax of do while loop is
INTRODUCTION TO COMPUTER SCIENCE Lab
23 | P a g e Programs:
1. Write a C program to find the sum of first n natural numbers where n is entered by user. 2. Write a C program to count the number of digits in a number.
3. Write a C program to add all the numbers entered by a user until user enters 0. 4. Write a C program to count the number of digits in a number.
Introduction to Computer Science Lab
24 | P a g e
Experiment 8
Date of Performance__________ Date of Submission ____________Faculty’s Signature ______________
Pointer and Function
Introduction
Function: A large C program is divided into basic building blocks called C function. C function contains set of instructions enclosed by “{ }” which performs specific operation in a C program. Actually, Collection of these functions creates a C program .C functions are used to avoid rewriting same logic/code again and again in a program. There is no limit in calling C functions to make use of same functionality wherever required. The core concept of C functions are, re-usability, dividing a big task into small pieces to achieve the functionality and to improve understandability of very large C programs.
A function that calls itself is known as recursive function and the process of calling function itself is known as recursion in C programming.
There are 3 aspects in each C function. They are,
Ø Function declaration or prototype - This informs compiler about the function name, function parameters and return value’s data type.
Ø Function call – This calls the actual function
Ø Function definition – This contains all the statements to be executed.
• Program to find whether a number is prime or not using user defined function • Program to find the sum of natural numbers using Recursion
• Program to reverse a sentence using Recursion
• C program to calculate the factorial of number using Recursion.
Pointer
When a variable contains the address of some memory block location it is called a "pointer" because it is "pointing" at that particular block of memory. All programming languages contains variables of some kind, but only few contains pointers. That's because pointers gives direct access to physical memory locations anywhere inside the computer. With pointers it is possible to access any memory location and change the data at that location. A pointer is a variable which contains the address in memory of another variable. We can have a pointer to any variable type. The unary or monadic operator & gives the ``address of a variable''. The indirection or dereference operator * gives the ``contents of an object pointed to by a pointer''.
To declare a pointer to a variable do: int *pointer;
Let us now examine the close relationship between pointers and C's other major function parts. We will start with functions.
INTRODUCTION TO COMPUTER SCIENCE Lab
25 | P a g e 1. Call by value
2. Call by reference
Call by value: //Use of Function
Ø In call by value method, the value of the variable is passed to the function as parameter.
Ø The value of the actual parameter cannot be modified by formal parameter.
Ø Different Memory is allocated for both actual and formal parameters. Because, value of actual parameter is copied to formal parameter.
Note:
Ø Actual parameter – This is the argument which is used in function call.
Call by reference: //Use of Pointer
Ø In call by reference method, the address of the variable is passed to the function as parameter.
Ø The value of the actual parameter can be modified by formal parameter.
Ø Same memory is used for both actual and formal parameters since only address is used by both parameters.
Ø Formal parameter – This is the argument which is used in function definition
Programs:
1. Write a C program to find sum of n natural numbers using functions.
2. Write a C program to find if number entered by the user is prime using functions. 3. Write a C program to reverse a number using recursion.
4. Write a C program to power of a number entered by the user using recursion.
Introduction to Computer Science Lab
26 | P a g e
Experiment 9
Date of Performance__________ Date of Submission ____________Faculty’s Signature ______________
Arrays
In C programming, one of the frequently arising problem is to handle similar types of data. For example: If the user want to store marks of 100 students. This can be done by creating 100 variable individually but, this process is rather tedious and impracticable. These type of problem can be handled in C programming using arrays. An array is a sequence of data item of homogeneous value (same type).
Arrays are of two types:
• One-dimensional arrays
• Multidimensional arrays
One dimensional array in c programming language: ID array
Declaration of one dimensional array
Here, the name of array is age. The size of array is 5,i.e., there are 5 items(elements) of array age. All element in an array are of the same type (int, in this case).
Array elements
INTRODUCTION TO COMPUTER SCIENCE Lab
27 | P a g e Note that, the first element is numbered 0 and so on.
Here, the size of array age is 5 times the size of int because there are 5 elements.
Suppose, the starting address of age [0] is 2120d and the size of int be 4 bytes. Then, the next address (address of a [1]) will be 2124d, address of a[2] will be 2128d and so on.
Initialization of one-dimensional array:
Arrays can be initialized at declaration time in this source code as:
It is not necessary to define the size of arrays during initialization.
In this case, the compiler determines the size of array by calculating the number of elements of an array.
Accessing array elements
In C programming, arrays can be accessed and treated like variables in C.
For example:
Multi-Dimensional Array
Introduction to Computer Science Lab
28 | P a g e
A Multidimensional array is a collection of data storage locations, each of which holds the same type of data. Each storage location is called an element of the array. You declare an array by writing the type, followed by the array name and the subscript. The subscript is the number of elements in the array, surrounded by square brackets.
Eg: type arrayName [ x ][ y ];
Where type can be any valid C data type and arrayName will be a valid C identifier. A two-dimensional array can be think as a table which will have x number of rows and y number of columns. A 2-dimensional array a, which contains three rows and four columns can be shown as below:
Column0 Column1 Column2 Column3
Row0 A[0][0] A[0][1] A[0][2] A[0][3]
Row1 A[1][0] A[1][1] A[1][2] A[1][3]
Row2 A[2][0] A[2][1] A[2][2] A[2][3]
Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is the name of the array, and i and j are the subscripts that uniquely identify each element in a.
For example: int a [5][10], declares an array of 50 integers, named a. Its declaration shows that array comprises of 5 one dimensional arrays and each one dimensional array contains 10 elements.
When the compiler sees this declaration, it sets aside enough memory to hold all 50 elements. Because each integer requires 2 bytes, this declaration sets aside 100 contiguous bytes of memory.
Initializing Two-Dimensional Arrays:
Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array with 2 rows and each row has 3 columns.
int a[2][3] = {
{1, 2, 3}, /* initializers for row indexed by 0 */ {4, 5, 6}, /* initializers for row indexed by 1 */ };
The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to previous example:
int a[2][3] = {1,2,3,4,5,6};
Accessing Two-Dimensional Array Elements:
An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and column index of the array. For example:
INTRODUCTION TO COMPUTER SCIENCE Lab
29 | P a g e The above statement will take 1st element from the 2nd row of the array. You can verify it in the above diagram.
Programs:
1. Write a C program to calculate average of n numbers entered by user. 2. Write a C program to find largest element of an array.
3. Write a C program to sort elements of an array.
4. Write a C program to search an element in a list of integers. 5. Write a C program to add two 1-D arrays.
Introduction to Computer Science Lab
30 | P a g e
Experiment 10
Date of Performance__________ Date of Submission ____________Faculty’s Signature ______________
File handling
In C programming, file is a place on disk where a group of related data is stored.
When the program is terminated, the entire data is lost in C programming. If you want to keep large volume of data, it is time consuming to enter the entire data. But, if file is created, these information can be accessed using few commands.
There are large numbers of functions to handle file I/O in C language. High level file I/O functions can be categorized as:
1. Text file 2. Binary file
File Operations
1. Creating a new file 2. Opening an existing file
3. Reading from and writing information to a file 4. Closing a file
Working with file
While working with file, you need to declare a pointer of type file. This declaration is needed for communication between file and program.
FILE *ptr; Opening a file
Opening a file is performed using library function fopen(). The syntax for opening a file in standard I/O is:
Ptr = fopen("fileopen","mode")
For Example:
fopen("E:\\cprogram\program.txt","w"); //E:\\cprogram\program.txt is the location to create file. "w" represents the mode for writing.
Here, the program.txt file is opened for writing mode.
Opening Modes in Standard I/O
INTRODUCTION TO COMPUTER SCIENCE Lab
31 | P a g e Opening Modes in Standard I/O
File Mode Meaning of Mode During Inexistence of file
r Open for reading. If the file does not exist, fopen() returns NULL.
w Open for writing. If the file exists, its contents are overwritten. If the file does not exist, it will be created.
a Open for append. i.e, Data is added to end of file. If the file does not exists, it will be created.
r+ Open for both reading and writing. If the file does not exist, fopen() returns NULL.
w+ Open for both reading and writing. If the file exists, its contents are overwritten. If the file does not exist, it will be created.
a+ Open for both reading and appending. If the file does not exists, it will be created.
Closing a File
The file should be closed after reading/writing of a file. Closing a file is performed using library function fclose().
fclose(ptr); //ptr is the file pointer associated with file to be closed. The Functions fprintf() and fscanf() functions.
The functions fprintf() and fscanf() are the file version of printf() and fscanf(). The only difference while using fprintf() and fscanf() is that, the first argument is a pointer to the structure FILE
Program:
1. Write a C program to read data from the file and display on screen.
2. Write a C program to create a file and store data in it as entered by the user.