mnk.muhammadiyah.infomnk.muhammadiyah.info/lab manuals/ver 2/csc103_pf... · web...

124
1 Course: CSC103-PROGRAMMING FUNDAMENTAL Department of Computer C ++ Learning Procedure 1) Stage J (Journey inside-out the concept) 2) Stage a 1 (Apply the learned) 3) Stage v (Verify the accuracy) 4) Stage a 2 (Assess your work)

Upload: vuongbao

Post on 28-Jun-2019

216 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

1

Course: CSC103-PROGRAMMING FUNDAMENTAL

Department of Computer Science

C ++ Learning Procedure

1) Stage J (Journey inside-out the concept)

2) Stage a1 (Apply the learned)

3) Stage v (Verify the accuracy)

4) Stage a2 (Assess your work)

Page 2: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Table of Contents

Lab #

Topics Covered Page #

Lab # 01

Introduction to the IDE of Dev C++.Data types in C, Basic syntax

Lab # 02

Basic syntaxVariables, Data Types and Expressions and operators in C++

Lab # 03

Conditional statementsIterative Control Structures-I

Lab # 04

Iterative Control Structures-IILab Sessional 1

Lab # 05

Functions and Parameter Passing-IFunctions and Parameter Passing-II

Lab # 06

Functions and Parameter Passing-IIIFunctions and Parameter Passing-IV

Lab # 07

Arrays I Arrays II

Lab # 08

Arrays IIIArrays IV

Lab # 09

Strings and String ProcessingRecursion

Lab # 10

File I/O-IFile I/O-II

Lab # 11

Types ofErrors (Syntax, Logic, Run-Time),Lab Sessional 2

Lab # 12

Code Reviews, Testing FundamentalsUnit Testing

Lab # 13

Lab # 14

Lab # 15

Lab # 16

Terminal Examination

2

Page 3: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Statement Purpose:This lab will give you the overview of C Programming Environment.

Activity Outcomes:

This lab teaches you the following topics:

Installing Dev C++ Review of the main C programming concepts. Recall algorithm and pseudo-code approaches.

3

LAB # 01

Page 4: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

1) Stage J (Journey)

Step-by-step Process of Programming in Dev C++:

Start the IDE from the Program folder Dev-C++ or Bloodshed Dev-C++.

Before creating the source code file, it is necessary to create a project (File > New > Project).

Select the folder to store the files in the next window. It is convenient to store each project in a different folder.

4

Page 5: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

The IDE window looking like this will appear in which you can read/write/debug your program

The IDE window includes three sub-windows: the Project Files Explorer, the Result Tabs, and the Source Code Editor. These windows can be resized and minimized. The Files Explorer window shows the name of the project and the included files. The Project tab usually contains a single file with the source code of the program. In this pane, we can find two additional tabs: Classes and Debug. Classes tab shows the functions of the program. Debug tab shows watched variables in the debugging process. The Results window is used to present the results of the actions of the IDE: compilation errors, compiling directives, debugging commands, etc. The Source code editor shows the code of the program.

Write your code here;

5

Page 6: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Save the file with .c extension.

Execution and Output:

Tasks

Create a new source file named CS-2K14. Write code to Display your name, registration number and institute name. Write, compile and execute all codes discussed in class. Explore the following terms and prepare a report explaining each term in 4 to 5 lines:o Linker

6

Page 7: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

o Debugger o Compiler o Assembler o Machine language o Popular languages nowadays o Generation of languageso Header files.

Data types in C

Data types in c refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted.

The types in C can be classified as follows −

S.N. Types & Description

1 Basic Types

They are arithmetic types and are further classified into: (a) integer types and (b) floating-point types.

2 Enumerated types

They are again arithmetic types and they are used to define variables that can only assign certain discrete integer values throughout the program.

3 The type void

The type specifier void indicates that no value is available.

4 Derived types

They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e) Function types.

The array types and structure types are referred collectively as the aggregate types. The type of a function specifies the type of the function's return value. We will see the basic types in the following section, where as other types will be covered in the upcoming chapters.

7

Page 8: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Integer Types

The following table provides the details of standard integer types with their storage sizes and value ranges −

Type Storage size Value range

char 1 byte -128 to 127 or 0 to 255

unsigned char 1 byte 0 to 255

signed char 1 byte -128 to 127

int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647

unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295

short 2 bytes -32,768 to 32,767

unsigned short 2 bytes 0 to 65,535

long 4 bytes -2,147,483,648 to 2,147,483,647

unsigned long 4 bytes 0 to 4,294,967,295

Floating-Point Types

The following table provide the details of standard floating-point types with storage sizes and value ranges and their precision

Type Storage size Value range Precision

float 4 byte 1.2E-38 to 3.4E+38 6 decimal places

double 8 byte 2.3E-308 to 1.7E+308 15 decimal places

8

Page 9: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places

Declarations, functions, expressionsA C program is a sequence of global declarations and definitions declarations of global variables and functions definitions of variables and functions often, declarations are implicit (the definition is an implicit declaration) Examples:

2) Stage a1 (apply) Activity 1

Write a C program to add two numbers

#include <stdio.h>

int main()

{

int firstNumber, secondNumber, sumOfTwoNumbers;

printf("Enter two integers: ");

// Two integers entered by user is stored using scanf() function

scanf("%d %d", &firstNumber, &secondNumber);

// sum of two numbers in stored in variable sumOfTwoNumbers

sumOfTwoNumbers = firstNumber + secondNumber;

// Displays sum

9

Page 10: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

printf("%d + %d = %d", firstNumber, secondNumber, sumOfTwoNumbers);

return 0;

}

Output

Enter two integers: 12

11

12 + 11 = 23

Activity 2 Write a C program to multiply two numbers

#include <stdio.h>

int main()

{

int firstNumber, secondNumber, sumOfTwoNumbers;

printf("Enter two integers: ");

// Two integers entered by user is stored using scanf() function

scanf("%d %d", &firstNumber, &secondNumber);

// sum of two numbers in stored in variable sumOfTwoNumbers

sumOfTwoNumbers = firstNumber * secondNumber;

// Displays sum

printf("%d * %d = %d", firstNumber, secondNumber, sumOfTwoNumbers);

return 0;

}

Output

10

Page 11: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Enter two integers: 5

5

5 * 5 = 25

3) Stage v (verify)

Ex1. Write a c program to divide 50 by 10Ex2. Write a c program to subtract 50 from 80Ex3. Write a c program to print 'hello world'

4) Stage a2 (assess)

Lab Work: In each laboratory you are assessed on your work within lab session based on your participation, discussions and achievement of lab activities. Thus, each lab has a portion of the (LAB WORK MARK). Therefore, a checklist of each lab is used to evaluate your work. This checklist accounts the following criteria:

Following the lab manual step by step

Answering given questions concisely and precisely

Practicing and implementing given examples correctly

Writing code of required programming tasks

Being focused, positive, interactive and serious during lab session

Asking good questions or answering instructor questions if any

11

Page 12: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Statement Purpose:This lab will give you overview of variables, data types, expressions and operators in C.

Activity Outcomes:This lab teaches you the following topics:

Declaration of Variables in C Assign values in to variables in C Implementations of expressions and operators in C

12

LAB # 02

Page 13: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

1) Stage J (Journey)

C - VariablesA variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.

The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is case-sensitive. Based on the basic types explained in the previous chapter, there will be the following basic variable types −

Type Description

char Typically a single octet(one byte). This is an integer type.

int The most natural size of integer for the machine.

float A single-precision floating point value.

double A double-precision floating point value.

void Represents the absence of type.

Variable Definition in C

A variable definition tells the compiler where and how much storage to create for the variable. A variable definition specifies a data type and contains a list of one or more variables of that type.

Variable Declaration in C

A variable declaration provides assurance to the compiler that there exists a variable with the given type and name so that the compiler can proceed for further compilation without requiring the complete detail about the variable. A variable definition has its meaning at the time of compilation only, the compiler needs actual variable definition at the time of linking the program.

13

Page 14: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

A variable declaration is useful when you are using multiple files and you define your variable in one of the files which will be available at the time of linking of the program. You will use the keyword extern to declare a variable at any place. Though you can declare a variable multiple times in your C program, it can be defined only once in a file, a function, or a block of code.

Expressions

In programming, an expression is any legal combination of symbols that represents a value. C Programming Provides its own rules of Expression, whether it is legal expression or illegal expression. For example, in the C language x+5 is a legal expression. Every expression consists of at least one operand and can have one or more operators. Operands are values and Operators are symbols that represent particular actions.

Valid C programming expressions

C Programming code gets compiled firstly before execution. In the different phases of compiler, c programming expression is checked for its validity.Expressions Validity

a + b Expression is valid since it contain + operator which is binary operator

+ + a + b Invalid Expression

Types of Expressions

In Programming, different verities of expressions are given to the compiler. Expressions can be classified on the basis of Position of Operators in an expression

Type Explanation Example

Infix Expression in which Operator is in between Operands a + b

Prefix Expression in which Operator is written before Operands + a b

Postfix Expression in which Operator is written after Operands a b +

C Operators

An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. C language is rich in built-in operators and provides the following types of operators −

Arithmetic Operators

Relational Operators

14

Page 15: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Logical Operators

Bitwise Operators

Assignment Operators

Misc Operators

Arithmetic Operators

The following table shows all the arithmetic operators supported by the C language. Assume variable A holds 10 and variable B holds 20 then −

Show Examples

Operator Description Example

+ Adds two operands. A + B = 30

− Subtracts second operand from the first. A − B = -10

* Multiplies both operands. A * B = 200

/ Divides numerator by de-numerator. B / A = 2

% Modulus Operator and remainder of after an integer division.

B % A = 0

++ Increment operator increases the integer value by one. A++ = 11

-- Decrement operator decreases the integer value by one. A-- = 9

Relational Operators

The following table shows all the relational operators supported by C. Assume variable A holds 10 and variable B holds 20 then −

Show Examples

Operator Description Example

15

Page 16: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

== Checks if the values of two operands are equal or not. If yes, then the condition becomes true.

(A == B) is not true.

!= Checks if the values of two operands are equal or not. If the values are not equal, then the condition becomes true.

(A != B) is true.

> Checks if the value of left operand is greater than the value of right operand. If yes, then the condition becomes true.

(A > B) is not true.

< Checks if the value of left operand is less than the value of right operand. If yes, then the condition becomes true.

(A < B) is true.

>= Checks if the value of left operand is greater than or equal to the value of right operand. If yes, then the condition becomes true.

(A >= B) is not true.

<= Checks if the value of left operand is less than or equal to the value of right operand. If yes, then the condition becomes true.

(A <= B) is true.

Logical Operators

Following table shows all the logical operators supported by C language. Assume variable A holds 1 and variable B holds 0, then −

Operator Description Example

&& Called Logical AND operator. If both the operands are non-zero, then the condition becomes true.

(A && B) is false.

|| Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true.

(A || B) is true.

! Called Logical NOT Operator. It is used to reverse the !(A &&

16

Page 17: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

logical state of its operand. If a condition is true, then Logical NOT operator will make it false.

B) is true.

Bitwise Operators

Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ is as follows −

p q p & q p | q p ^ q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

2) Stage a1 (apply)

Lab Activities:

Activity 1:

A C program where variables declaration, initialization is available

#include <stdio.h>

// Variable declaration:

extern int a, b;

extern int c;

extern float f;

int main () {

/* variable definition: */

int a, b;

int c;

17

Page 18: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

float f;

/* actual initialization */

a = 10;

b = 20;

c = a + b;

printf("value of c : %d \n", c);

f = 70.0/3.0;

printf("value of f : %f \n", f);

return 0;

}

Output

value of c : 30value of f : 23.333334

Activity 2

C Program to demonstrate the working of arithmetic operators

#include <stdio.h>

int main()

{

int a = 9,b = 4, c;

c = a+b;

printf("a+b = %d \n",c);

c = a-b;

printf("a-b = %d \n",c);

c = a*b;

printf("a*b = %d \n",c);

c=a/b;

printf("a/b = %d \n",c);

c=a%b;

18

Page 19: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

printf("Remainder when a divided by b = %d \n",c);

return 0;

}

Output

a+b = 13

a-b = 5

a*b = 36

a/b = 2

Remainder when a divided by b=1

Activity 3. C Program to demonstrate the working of assignment operators

#include <stdio.h>

int main()

{

int a = 5, c;

c = a;

printf("c = %d \n", c);

c += a; // c = c+a

printf("c = %d \n", c);

c -= a; // c = c-a

printf("c = %d \n", c);

c *= a; // c = c*a

printf("c = %d \n", c);

c /= a; // c = c/a

19

Page 20: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

printf("c = %d \n", c);

c %= a; // c = c%a

printf("c = %d \n", c);

return 0;

}

Output

c = 5

c = 10

c = 5

c = 25

c = 5

c = 0

Activity 4

C Program to demonstrate the working of arithmetic operators

#include <stdio.h>

int main()

{

int a = 5, b = 5, c = 10;

printf("%d == %d = %d \n", a, b, a == b); // true

printf("%d == %d = %d \n", a, c, a == c); // false

printf("%d > %d = %d \n", a, b, a > b); //false

printf("%d > %d = %d \n", a, c, a > c); //false

20

Page 21: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

printf("%d < %d = %d \n", a, b, a < b); //false

printf("%d < %d = %d \n", a, c, a < c); //true

printf("%d != %d = %d \n", a, b, a != b); //false

printf("%d != %d = %d \n", a, c, a != c); //true

printf("%d >= %d = %d \n", a, b, a >= b); //true

printf("%d >= %d = %d \n", a, c, a >= c); //false

printf("%d <= %d = %d \n", a, b, a <= b); //true

printf("%d <= %d = %d \n", a, c, a <= c); //true

return 0;

}

Output

5 == 5 = 1

5 == 10 = 0

5 > 5 = 0

5 > 10 = 0

5 < 5 = 0

5 < 10 = 1

5 != 5 = 0

21

Page 22: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

5 != 10 = 1

5 >= 5 = 1

5 >= 10 = 0

5 <= 5 = 1

5 <= 10 = 1

3) Stage v (verify)

Ex1. Write a C program to implement logical OR and logical AND

Ex2. Write a C program to implement the Bitwise Shift left and shift right operators

Ex3. Write a c program to implement the Increment and Decrement Operators

4) Stage a2 (assess)

Lab Work: In each laboratory you are assessed on your work within lab session based on your participation, discussions and achievement of lab activities. Thus, each lab has a portion of the (LAB WORK MARK). Therefore, a checklist of each lab is used to evaluate your work. This checklist accounts the following criteria:

Following the lab manual step by step Answering given questions concisely and precisely Practicing and implementing given examples correctly Writing code of required programming tasks Being focused, positive, interactive and serious during lab session Asking good questions or answering instructor questions if any

22

Page 23: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Purpose StatementThis lab will demonstrate you that how to use the conditional and Switch statement in C

Activity Outcomes:

This lab teaches you the following topics:

Use of If statement in C Use of If-else statement in C Use of Switch Statement

23

LAB # 03

Page 24: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

1) Stage J (Journey)

Decision Making

Decision making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

Below is the general form of a typical decision making structure

C programming language assumes any non-zero and non-null values as true, and if it is either zero or null, then it is assumed as false value.

C programming language provides the following types of decision making statements.

S.N. Statement & Description

1 if statement

An if statement consists of a boolean expression followed by one or more statements.

2 if...else statement

An if statement can be followed by an optional else statement, which

24

Page 25: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

executes when the Boolean expression is false.

3 nested if statements

You can use one if or else if statement inside another if or else if statement(s).

4 switch statement

A switch statement allows a variable to be tested for equality against a list of values.

5 nested switch statements

You can use one switch statement inside another switch statement(s).

Syntax of If statement

if(boolean_expression) { /* statement(s) will execute if the boolean expression is true */}

Syntax of If else statement

if(boolean_expression) { /* statement(s) will execute if the boolean expression is true */}else { /* statement(s) will execute if the boolean expression is false */}

Syntax of nested If statement

if(boolean_expression 1) { /* Executes when the boolean expression 1 is true */}else if( boolean_expression 2) { /* Executes when the boolean expression 2 is true */}else if( boolean_expression 3) { /* Executes when the boolean expression 3 is true */}else { /* executes when the none of the above condition is true */}

25

Page 26: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Syntax of Switch Statement

switch(expression) {

case constant-expression :

statement(s);

break; /* optional */

case constant-expression :

statement(s);

break; /* optional */

/* you can have any number of case statements */

default : /* Optional */

statement(s);

}

The following rules apply to a switch statement −

The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type.

You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.

The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.

When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.

When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.

Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.

A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.

26

Page 27: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

2) Stage a1 (apply)

Activity 1 a C program with If

#include <stdio.h>

int main () {

/* local variable definition */

int a = 100;

/* check the boolean condition */

if( a < 20 ) {

/* if condition is true then print the following */

printf("a is less than 20\n" );

}

printf("value of a is : %d\n", a);

return 0;

27

Page 28: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

}

Activity 2 A C program with If-else statement

#include <stdio.h>

int main () {

/* local variable definition */

int a = 100;

/* check the boolean condition */

if( a == 10 ) {

/* if condition is true then print the following */

printf("Value of a is 10\n" );

}

else if( a == 20 ) {

/* if else if condition is true */

printf("Value of a is 20\n" );

}

else if( a == 30 ) {

/* if else if condition is true */

printf("Value of a is 30\n" );

}

else {

/* if none of the conditions is true */

printf("None of the values is matching\n" );

}

printf("Exact value of a is: %d\n", a );

return 0;

}

Output

None of the values is matchingExact value of a is: 100

28

Page 29: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Activity 3 A C program with Switch Statement

#include <stdio.h>

int main () {

/* local variable definition */

char grade = 'B';

switch(grade) {

case 'A' :

printf("Excellent!\n" );

break;

case 'B' :

case 'C' :

printf("Well done\n" );

break;

case 'D' :

printf("You passed\n" );

break;

case 'F' :

printf("Better try again\n" );

break;

default :

printf("Invalid grade\n" );

}

printf("Your grade is %c\n", grade );

return 0;

}

Output

Well doneYour grade is B

29

Page 30: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

3) Stage v (verify)

Complete the following exercisesEx1. What is wrong with the following if statement (there are at least 3 errors). Theindentation indicates the desired behavior.

if numNeighbors >= 3 || numNeighbors = 4++numNeighbors;cout << "You are dead!" << endl;else--numNeighbors;

Ex 2. Write a C program to display a number if user enters negative number , // If user enters positive number, that number won't be displayed

Ex3. Write a C program by implementing if-else structure to check whether an integer entered by the user is odd or even.

Ex4. What will be the output of below C program

int main(){ int i=2; switch (i) { case 1: printf("Case1 "); case 2: printf("Case2 "); case 3: printf("Case3 "); case 4: printf("Case4 "); default: printf("Default "); } return 0;}

30

Page 31: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

4) Stage a2 (assess)

Lab Work:

In each laboratory you are assessed on your work within lab session based on your participation, discussions and achievement of lab activities. Thus, each lab has a portion of the (LAB WORK MARK). Therefore, a checklist of each lab is used to evaluate your work.

This checklist accounts the following criteria:

Following the lab manual step by step

Answering given questions concisely and precisely

Practicing and implementing given examples correctly

Writing code of required programming tasks

Being focused, positive, interactive and serious during lab session

Asking good questions or answering instructor questions if any

31

Page 32: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Statement Purpose:

This lab will give you practice with Loop structure in C

Activity Outcomes:

This lab teaches you the following topics:

Use of while loop in C

Use of do-while loop in C

Use of for loop in C

32

LAB # 04

Page 33: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

1) Stage J (Journey)

Introduction

You may encounter situations, when a block of code needs to be executed several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths.

A loop statement allows us to execute a statement or group of statements multiple times. Given below is the general form of a loop statement.

C programming language provides the following types of loops to handle looping requirements.

While Loop

Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.

33

Page 34: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

do- while loop

It is more like a while statement, except that it tests the condition at the end of the loop body.

For Loop

Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.

34

Page 35: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Nested loops

You can use one or more loops inside any other while, for, or do..while loop.

Loop Control Statements

Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.

C supports the following control statements.

S.N. Control Statement & Description

1 break statement

Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.

2 continue statement

35

Page 36: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

3 goto statement

Transfers control to the labeled statement.

36

Page 37: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

2) Stage a1 (apply)

Activity 1 A C program with While loop

#include <stdio.h>

int main () {

/* local variable definition */

int a = 10;

/* while loop execution */

while( a < 20 ) {

printf("value of a: %d\n", a);

a++;

}

return 0;

}

Output

value of a: 10value of a: 11value of a: 12value of a: 13value of a: 14value of a: 15value of a: 16value of a: 17value of a: 18value of a: 19

Activity 2 d--While implementation in C

#include <stdio.h>

int main () {

/* local variable definition */

int a = 10;

/* do loop execution */

37

Page 38: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

do {

printf("value of a: %d\n", a);

a = a + 1;

}while( a < 20 );

return 0;

}

value of a: 10value of a: 11value of a: 12value of a: 13value of a: 14value of a: 15value of a: 16value of a: 17value of a: 18value of a: 19

Activity 3

Program to calculate the sum of first n natural numbers

// Positive integers 1,2,3...n are known as natural numbers

#include <stdio.h>

int main()

{

int num, count, sum = 0;

printf("Enter a positive integer: ");

scanf("%d", &num);

// for loop terminates when n is less than count

for(count = 1; count <= num; ++count)

{

sum += count;

}

printf("Sum = %d", sum);

return 0;

}

38

Page 39: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Output

Enter a positive integer: 10

Sum = 55

Activity 4 Nested Loop to find the find the prime numbers from 2 to 100

#include <stdio.h>

int main () {

/* local variable definition */

int i, j;

for(i = 2; i<100; i++) {

for(j = 2; j <= (i/j); j++)

if(!(i%j)) break; // if factor found, not prime

if(j > (i/j)) printf("%d is prime\n", i);

}

return 0;

}

Output

2 is prime3 is prime5 is prime7 is prime11 is prime13 is prime17 is prime19 is prime23 is prime29 is prime31 is prime37 is prime41 is prime43 is prime47 is prime53 is prime59 is prime61 is prime67 is prime

39

Page 40: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

71 is prime73 is prime79 is prime83 is prime89 is prime97 is prime

3) Stage v (verify)

Ex1. Write a C Program using while loop to find factorial of a number

Hint For a positive integer n, factorial = 1*2*3...n

Ex2. Write a C program to add numbers until user enters zero using do-while loop

Ex3. Change the following C code from using a while loop to for loop:

x=1;

while(x<10){

printf("%d\t",x);

++x;

}

Ex4. What would be the output from the following C code segment?

x=10;

while(x>5){

printf("%d\n",x);

x--;

}

40

Page 41: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

4) Stage a2 (assess)

Lab Work:

In each laboratory you are assessed on your work within lab session based on your participation, discussions and achievement of lab activities. Thus, each lab has a portion of the (LAB WORK MARK). Therefore, a checklist of each lab is used to evaluate your work. This checklist accounts the following criteria:

Following the lab manual step by step

Answering given questions concisely and precisely

Practicing and implementing given examples correctly

Writing code of required programming tasks

Being focused, positive, interactive and serious during lab session

41

Page 42: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Statement Purpose

This Lab will give you the practice with function in C

Activity Outcomes:

This lab teaches you the following topics:

Function Declaration

Calling a Function

Function with arguments

42

LAB # 05

Page 43: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

1) Stage J (Journey)

Introductions

A function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions. You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division is such that each function performs a specific task.

A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function. The C standard library provides numerous built-in functions that your program can call. For example, strcat() to concatenate two strings, memcpy() to copy one memory location to another location, and many more functions. A function can also be referred as a method or a sub-routine or a procedure, etc.

Defining a Function

A function definition in C programming consists of a function header and a function body. Here are all the parts of a function

Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.

Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature.

Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.

Function Body − The function body contains a collection of statements that define what the function does.

Function Declarations

A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately. A function declaration has the following parts −

return_type function_name( parameter list );

43

Page 44: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

For the above defined function max(), the function declaration is as follows −

int max(int num1, int num2);

Parameter names are not important in function declaration only their type is required, so the following is also a valid declaration −

int max(int, int);

Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function.

Calling a Function

While creating a C function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task. When a program calls a function, the program control is transferred to the called function. A called function performs a defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns the program control back to the main program.

To call a function, you simply need to pass the required parameters along with the function name, and if the function returns a value, then you can store the returned value. For example

Function Arguments

If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function. Formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit. While calling a function, there are two ways in which arguments can be passed to a function

S.N. Call Type & Description

1 Call by value

This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.

2 Call by reference

This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.

44

Page 45: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

By default, C uses call by value to pass arguments. In general, it means the code within a function cannot alter the arguments used to call the function.

2) Stage a1 (apply)

Activity 1. Function returning the max between two numbers

int max(int num1, int num2) {

/* local variable declaration */

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

}

Activity 2

To call a function, you simply need to pass the required parameters along with the function name, and if the function returns a value, then you can store the returned value. For example

#include <stdio.h>

/* function declaration */

int max(int num1, int num2);

int main () {

/* local variable definition */

int a = 100;

int b = 200;

int ret;

/* calling a function to get max value */

45

Page 46: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

ret = max(a, b);

printf( "Max value is : %d\n", ret );

return 0;

}

/* function returning the max between two numbers */

int max(int num1, int num2) {

/* local variable declaration */

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

}

Activity 3

The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. By default, C programming uses call by value to pass arguments. In general, it means the code within a function cannot alter the arguments used to call the function. Consider the function swap() definition as follows.

/* function definition to swap the values */

void swap(int x, int y) {

int temp;

temp = x; /* save the value of x */

x = y; /* put y into x */

y = temp; /* put temp into y */

46

Page 47: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

return;

}

Now, let us call the function swap() by passing actual values as in the following example −

#include <stdio.h>

/* function declaration */

void swap(int x, int y);

int main () {

/* local variable definition */

int a = 100;

int b = 200;

printf("Before swap, value of a : %d\n", a );

printf("Before swap, value of b : %d\n", b );

/* calling a function to swap the values */

swap(a, b);

printf("After swap, value of a : %d\n", a );

printf("After swap, value of b : %d\n", b );

return 0;

}

Put the above code in a single C file, compile and execute it, it will produce the following result 

Before swap, value of a :100Before swap, value of b :200After swap, value of a :100After swap, value of b :200

Activity 4

The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. It means the changes made to the parameter affect the passed argument. To pass a value by reference, argument pointers are passed to the functions

47

Page 48: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

just like any other value. So accordingly you need to declare the function parameters as pointer types as in the following function swap(), which exchanges the values of the two integer variables pointed to, by their arguments.

/* function definition to swap the values */

void swap(int *x, int *y) {

int temp;

temp = *x; /* save the value at address x */

*x = *y; /* put y into x */

*y = temp; /* put temp into y */

return;

}

Let us now call the function swap() by passing values by reference as in the following example −

#include <stdio.h>

/* function declaration */

void swap(int *x, int *y);

int main () {

/* local variable definition */

int a = 100;

int b = 200;

printf("Before swap, value of a : %d\n", a );

printf("Before swap, value of b : %d\n", b );

/* calling a function to swap the values.

* &a indicates pointer to a ie. address of variable a and

* &b indicates pointer to b ie. address of variable b.

*/

swap(&a, &b);

printf("After swap, value of a : %d\n", a );

printf("After swap, value of b : %d\n", b );

48

Page 49: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

return 0;

}

Put the above code in a single C file, compile and execute it, it will produce the following result 

Before swap, value of a :100Before swap, value of b :200After swap, value of a :200After swap, value of b :100

Activity 5. C function with arguments

#include<stdio.h>

float calculate_area(int);

int main()

{

int radius;

float area;

printf("\nEnter the radius of the circle : ");

scanf("%d",&radius);

area = calculate_area(radius);

printf("\nArea of Circle : %f ",area);

return(0);

}

float calculate_area(int radius)

{

float areaOfCircle;

areaOfCircle = 3.14 * radius * radius;

return(areaOfCircle);

}

Output

Enter the radius of the circle : 2

Area of Circle : 12.56

Explanation

49

Page 50: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

1. In the above program we can see that inside main function we are calling a user

defined calculate_area() function.

2. We are passing integer argument to the function which after area calculation returns

floating point area value.

3) Stage v (verify)

Ex1. Write a C program in which define and call a function by valueEx2. Write a C program in which define and call a function by referenceEx3. Write a C function which should take three parameters as input and return one parameter.

4) Stage a2 (assess)

Lab Work:

In each laboratory you are assessed on your work within lab session based on your participation, discussions and achievement of lab activities. Thus, each lab has a portion of the (LAB WORK MARK). Therefore, a checklist of each lab is used to evaluate your work.

This checklist accounts the following criteria:

Following the lab manual step by step

Answering given questions concisely and precisely

Practicing and implementing given examples correctly

Writing code of required programming tasks

Being focused, positive, interactive and serious during lab session

Asking good questions or answering instructor questions if any

50

Page 51: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Statement Purpose:

This lab will give you practice with functions and parameters.

Activity Outcomes:

This lab teaches you the following topics:

Functions with Arguments

Library function in C

User defined function in C

51

LAB # 06

Page 52: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

1) Stage J (Journey)

Introduction

All C functions can be called either with arguments or without arguments in a C program. These functions may or may not return values to the calling function. Now, we will see simple example C programs for each one of the below.

1. C function with arguments (parameters) and with return value.2. C function with arguments (parameters) and without return value.3. C function without arguments (parameters) and without return value.4. C function without arguments (parameters) and with return value.

C functions aspects syntax

1. With arguments and withreturn values

function declaration:int function ( int );function call: function ( a );function definition:       int function( int a ){statements;return a;}

2. With arguments and withoutreturn values

function declaration:void function ( int );function call: function( a );function definition:void function( int a ){statements;}

3. Without arguments and withoutreturn values

function declaration:void function();function call: function();function definition:void function(){statements;}

4. Without arguments and withreturn values

function declaration:int function ( );function call: function ( );function definition:int function( ){statements;return a;}

52

Page 53: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

53

Page 54: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

C – Library functions Library functions in C language are inbuilt functions which are grouped together

and placed in a common place called library. Each library function in C performs specific operation. We can make use of these library functions to get the pre-defined output instead of

writing our own code to get those outputs. These library functions are created by the persons who designed and created C

compilers. All C standard library functions are declared in many header files which are saved

as file_name.h. Actually, function declaration, definition for macros are given in all header files. We are including these header files in our C program using

“#include<file_name.h>” command to make use of the functions those are declared in the header files.

When we include header files in our C program using “#include<filename.h>” command, all C code of the header files are included in C program. Then, this C program is compiled by compiler and executed.

User Defined Functions in C:

User defined functions are the functions which are written by us for our own requirement.

2) Stage a1 (apply)

Activity 1. Example program for with arguments & with return value:

In this program, integer, array and string are passed as arguments to the function. The return type of this function is “int” and value of the variable “a” is returned from the function. The values for array and string are modified inside the function itself.

#include<stdio.h>#include<string.h>int function(int, int[], char[]); int main(){      int i, a = 20;      int arr[5] = {10,20,30,40,50};        char str[30] = "\"fresh2refresh\"";       printf("    ***values before modification***\n");        printf("value of a is %d\n",a);         for (i=0;i<5;i++)      {         // Accessing each variable

54

Page 55: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

         printf("value of arr[%d] is %d\n",i,arr[i]);        }      printf("value of str is %s\n",str);       printf("\n    ***values after modification***\n");       a= function(a, &arr[0], &str[0]);      printf("value of a is %d\n",a);        for (i=0;i<5;i++)      {         // Accessing each variable         printf("value of arr[%d] is %d\n",i,arr[i]);        }      printf("value of str is %s\n",str);       return 0;} int function(int a, int *arr, char *str){    int i;     a = a+20;    arr[0] = arr[0]+50;    arr[1] = arr[1]+50;    arr[2] = arr[2]+50;    arr[3] = arr[3]+50;    arr[4] = arr[4]+50;    strcpy(str,"\"modified string\"");     return a; }

Output

***values before modification***value of a is 20value of arr[0] is 10value of arr[1] is 20value of arr[2] is 30value of arr[3] is 40value of arr[4] is 50value of str is “fresh2refresh”***values after modification***value of a is 40value of arr[0] is 60value of arr[1] is 70value of arr[2] is 80value of arr[3] is 90value of arr[4] is 100value of str is “modified string”

Activity 2 Program for with arguments & without return value:

55

Page 56: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

In this program, integer, array and string are passed as arguments to the function. The return type of this function is “void” and no values can be returned from the function. All the values of integer, array and string are manipulated and displayed inside the function itself.

#include<stdio.h> void function(int, int[], char[]); int main(){      int a = 20;      int arr[5] = {10,20,30,40,50};        char str[30] = "\"fresh2refresh\"";       function(a, &arr[0], &str[0]);      return 0;} void function(int a, int *arr, char *str){    int i;    printf("value of a is %d\n\n",a);      for (i=0;i<5;i++)      {         // Accessing each variable         printf("value of arr[%d] is %d\n",i,arr[i]);        }    printf("\nvalue of str is %s\n",str);  }

Output

value of a is 20value of arr[0] is 10value of arr[1] is 20value of arr[2] is 30value of arr[3] is 40value of arr[4] is 50value of str is “fresh2refresh”

Activity 3. Program for without arguments & without return value:

In this program, no values are passed to the function “test” and no values are returned from this function to main function

#include<stdio.h>void test();           int main(){

56

Page 57: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

    test();                             return 0;} void test()  {     int a = 50, b = 80;       printf("\nvalues : a = %d and b = %d", a, b);}

Output

values : a = 50 and b = 80

Activity 4. Program for without arguments & with return value:

In this program, no arguments are passed to the function “sum”. But, values are returned from this function to main function. Values of the variable a and b are summed up in the function “sum” and the sum of these value is returned to the main function.

#include<stdio.h> int sum();           int main(){    int addition;    addition = sum();                      printf("\nSum of two given values = %d", addition);    return 0;} int sum()  {     int a = 50, b = 80, sum;       sum = a + b;    return sum;       }

Output

Sum of two given values = 130

57

Page 58: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

3) Stage v (verify)

Ex1. Write a c function which should take 2 arguments and return a value

Ex1. Write a c function which should take 3 arguments and return no value

Ex1. Write a c function which should take no arguments and return a no value

4) Stage a2 (apply)

Lab Work:

In each laboratory you are assessed on your work within lab session based on your participation, discussions and achievement of lab activities. Thus, each lab has a portion of the (LAB WORK MARK). Therefore, a checklist of each lab is used to evaluate your work.

This checklist accounts the following criteria:

Following the lab manual step by step

Answering given questions concisely and precisely

Practicing and implementing given examples correctly

Writing code of required programming tasks

Being focused, positive, interactive and serious during lab session

Asking good questions or answering instructor questions if any

58

Page 59: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Statement Purpose

This lab will give you the practice with One Dimensional arrays in C

Activity Outcomes:

This lab teaches you the following topics:

Array declaration

Array initialization

Array traversing

59

LAB # 07

Page 60: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

1) Stage J (Journey)

Introduction Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

2) Stage a1 (apply)

Activity 1 Declaring Arrays

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follow

type arrayName [ arraySize ];double balance[5];

Activity 2 Initializing Arrays

double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};Activity 3. Accessing Array Elements

double salary = balance[4];This will return 50.0Activity 4. Following c program will use above mentioned all three concepts

#include <stdio.h>

int main () {

int n[ 10 ]; /* n is an array of 10 integers */

int i,j;

60

Page 61: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

/* initialize elements of array n to 0 */

for ( i = 0; i < 10; i++ ) {

n[ i ] = i + 100; /* set element at location i to i + 100 */

}

/* output each array element's value */

for (j = 0; j < 10; j++ ) {

printf("Element[%d] = %d\n", j, n[j] );

}

return 0;

}

Output

Element[0] = 100Element[1] = 101Element[2] = 102Element[3] = 103Element[4] = 104Element[5] = 105Element[6] = 106Element[7] = 107Element[8] = 108Element[9] = 109

Activity 5 Passing arrays as argument to function

Now, consider the following function, which takes an array as an argument along with another argument and based on the passed arguments, it returns the average of the numbers passed through the array as follows −

ouble getAverage(int arr[], int size) {

int i;

double avg;

double sum = 0;

for (i = 0; i < size; ++i) {

sum += arr[i];

}

61

Page 62: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

avg = sum / size;

return avg;

}

Now, let us call the above function as follows −

#include <stdio.h>

/* function declaration */

double getAverage(int arr[], int size);

int main () {

/* an int array with 5 elements */

int balance[5] = {1000, 2, 3, 17, 50};

double avg;

/* pass pointer to the array as an argument */

avg = getAverage( balance, 5 ) ;

/* output the returned value */

printf( "Average value is: %f ", avg );

return 0;

}

When the above code is compiled together and executed, it produces the following result

Average value is: 214.400000

Activity 6 C Program to Insert an Element in a Specified Position in a given Array

#include <stdio.h> void main(){ int array[10]; int i, j, n, m, temp, key, pos;  printf("Enter how many elements \n"); scanf("%d", &n); printf("Enter the elements \n"); for (i = 0; i < n; i++)

62

Page 63: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

{ scanf("%d", &array[i]); } printf("Input array elements are \n"); for (i = 0; i < n; i++) { printf("%d\n", array[i]); } for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { if (array[i] > array[j]) { temp = array[i]; array[i] = array[j]; array[j] = temp; } } } printf("Sorted list is \n"); for (i = 0; i < n; i++) { printf("%d\n", array[i]); } printf("Enter the element to be inserted \n"); scanf("%d", &key); for (i = 0; i < n; i++) { if (key < array[i]) { pos = i; break; } if (key > array[n-1]) { pos = n; break; } } if (pos != n) { m = n - pos + 1 ; for (i = 0; i <= m; i++) { array[n - i + 2] = array[n - i + 1] ; } } array[pos] = key; printf("Final list is \n"); for (i = 0; i < n + 1; i++) {

63

Page 64: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

printf("%d\n", array[i]); }}

Execution and output of above program

$ cc pgm41.c$ a.outEnter how many elements5Enter the elements7690567812Input array elements are7690567812Sorted list is1256767890Enter the element to be inserted61Final list is125661767890

Activity 7 This C Program sorts array in an ascending order.

#include <stdio.h> void main(){ int i, j, a, n, number[30];  printf("Enter the value of N \n"); scanf("%d", &n); printf("Enter the numbers \n"); for (i = 0; i < n; ++i) scanf("%d", &number[i]); for (i = 0; i < n; ++i)

64

Page 65: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

{ for (j = i + 1; j < n; ++j) { if (number[i] > number[j]) { a = number[i]; number[i] = number[j]; number[j] = a; } } } printf("The numbers arranged in ascending order are given below \n"); for (i = 0; i < n; ++i) printf("%d\n", number[i]);}

Execution and output of above program

$ cc pgm66.c$ a.outEnter the value of N6Enter the numbers37890456780200The numbers arranged in ascending order are given below37890200456780

Activity 8 C Program to Delete the Specified Integer from an Array

#include <stdio.h> void main(){ int vectorx[10]; int i, n, pos, element, found = 0;  printf("Enter how many elements\n"); scanf("%d", &n);

65

Page 66: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

printf("Enter the elements\n"); for (i = 0; i < n; i++) { scanf("%d", &vectorx[i]); } printf("Input array elements are\n"); for (i = 0; i < n; i++) { printf("%d\n", vectorx[i]); } printf("Enter the element to be deleted\n"); scanf("%d", &element); for (i = 0; i < n; i++) { if (vectorx[i] == element) { found = 1; pos = i; break; } } if (found == 1) { for (i = pos; i < n - 1; i++) { vectorx[i] = vectorx[i + 1]; } printf("The resultant vector is \n"); for (i = 0; i < n - 1; i++) { printf("%d\n", vectorx[i]); } } else printf("Element %d is not found in the vector\n", element);}

Execution and output of above program

$ cc pgm69.c$ a.outEnter how many elements4Enter the elements345234678987

66

Page 67: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Input array elements are345234678987Enter the element to be deleted234The resultant vector is345678987

3) Stage v (verify)

Perform following exercises to verify the above labsEx1. Read carefully the following C program and find an error

#include <stdio.h>

int main()

{

int num[] = {2,8,7,6,0};

int i;

for(i=0;i<6;i++) {

printf("\nArray Element num[%d] : %d",i+1,num[i]);

}

return 0;

}

Ex2. Write a c program to calculate the sum of following arraysa1=[2,8,7,6,0,10,20,50]

Ex3. C Program finds second largest & smallest elements in following array

a1=[2,8,7,6,0,10,20,50]Ex4. Five different numbers are input in an array. Write a program to determine how many of them are positive, negative, even and odd

67

Page 68: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

4) Stage a2 (assess)

Lab Work:

In each laboratory you are assessed on your work within lab session based on your participation, discussions and achievement of lab activities. Thus, each lab has a portion of the (LAB WORK MARK). Therefore, a checklist of each lab is used to evaluate your work.

This checklist accounts the following criteria:

Following the lab manual step by step

Answering given questions concisely and precisely

Practicing and implementing given examples correctly

Writing code of required programming tasks

Being focused, positive, interactive and serious during lab session

Asking good questions or answering instructor questions if any

68

Page 69: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Statement Purpose

This lab will give you the practice with Multi Dimensional arrays in C

Activity Outcomes:

This lab teaches you the following topics:

Declaration of Multi-Dimensional Arrays

Initializing Multi -Dimensional Arrays

Accessing Multi -Dimensional Array Elements

69

LAB # 08

Page 70: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

1) Stage J (Journey)Introduction

C programming language allows multidimensional arrays. The simplest form of multidimensional array is the two-dimensional array. A two-dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of size [x][y], you would write something as follows

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 considered as a table which will have x number of rows and y number of columns. A two-dimensional array a, which contains three rows and four columns can be shown as follows −

Thus, every element in the 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'.

2) Stage a1 (apply)Activity 1. Initializing Two-Dimensional Arrays

int a[3][4] = {

{0, 1, 2, 3} , /* initializers for row indexed by 0 */

{4, 5, 6, 7} , /* initializers for row indexed by 1 */

{8, 9, 10, 11} /* initializers for row indexed by 2 */

};

Activity 2 Accessing Two-Dimensional Array Elements

int val = a[2][3];The above statement will take the 4th element from the 3rd row of the array. You can verify it in the above figure. Let us check the following program where we have used a nested loop to handle a two-dimensional array −

#include <stdio.h>

int main () {

70

Page 71: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

/* an array with 5 rows and 2 columns*/

int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};

int i, j;

/* output each array element's value */

for ( i = 0; i < 5; i++ ) {

for ( j = 0; j < 2; j++ ) {

printf("a[%d][%d] = %d\n", i,j, a[i][j] );

}

}

return 0;

}

Output of above program

a[0][0]: 0a[0][1]: 0a[1][0]: 1a[1][1]: 2a[2][0]: 2a[2][1]: 4a[3][0]: 3a[3][1]: 6a[4][0]: 4a[4][1]: 8

Activity 3. Two dimensional array to store roll number and marks obtained by a student

side by side in a matrix

main( )

{

int stud[4][2] ;

int i, j ;

for ( i = 0 ; i <= 3 ; i++ )

{

printf ( "\n Enter roll no. and marks" ) ;

scanf ( "%d %d", &stud[i][0], &stud[i][1] ) ; }

for ( i = 0 ; i <= 3 ; i++ )

71

Page 72: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

printf ( "\n%d %d", stud[i][0], stud[i][1] ) ;

}

Activity 4 C program to find sum of all elements of two dimensional array

#include <stdio.h>#include <conio.h>  int main(){    /* Two dimentional array declaration */    int matrix[20][20];    int rowCounter, colCounter, rows, cols, sum=0;         printf("Enter size of a matrix\n");    scanf("%d %d", &rows, &cols);    /* Populating elements inside matrix */    printf("Enter elements of a matrix of size %dX%d\n", rows, cols);    for(rowCounter = 0; rowCounter < rows; rowCounter++){        for(colCounter = 0; colCounter < cols; colCounter++){            scanf("%d", &matrix[rowCounter][colCounter]);        }    }    /* Accessing all elements of matrix to calculate their sum */    for(rowCounter = 0; rowCounter < rows; rowCounter++){        for(colCounter = 0; colCounter < cols; colCounter++){            sum += matrix[rowCounter][colCounter];        }    }         printf("Sum of all elements = %d", sum);    getch();    return 0;}

Note: Above program first declares a matrix of size 20X20 then populates it by taking input from user. Now using two for loops it access each element of matrix and add their values to a variable sum. Output

Enter size of a matrix

3 3

Enter elements of a matrix of size 3X3

1 2 3

4 5 6

7 8 9

Sum of all elements = 45

Activity 5 Passing to a Function

We pass a two-dimensional array to a function in the same way that we pass a one-dimensional array. We specify the name of the array as an argument in the function call. The

72

Page 73: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

corresponding function parameter receives the value of this argument as the address of the array. The parameter declaration identifies the array as two-dimensional by two pairs of brackets. The parameter declaration includes the array's column dimension - the column dimension must be included.

// Two-Dimensional Arrays // pass2DArray.c

#include <stdio.h>

#define NCOLS 3 void foo(int a[][NCOLS], int r, int c);

int main(void) { int a[2][NCOLS] = {{11, 12, 13}, {21, 22, 23}};

foo (a, 2, 3); }

void foo(int a[][NCOLS], int r, int c) { int i, j;

for (i = 0; i < r; i++) { for (j = 0; j < c; j++) printf("%d ", a[i][j]); printf("\n"); } }

3) Stage v (verify)

Ex1. Write a C program to sum all the elements of following 2D arrays.

int a[4][5] = {{11, 12, 13, 14, 15}, {21, 22, 23, 24, 25}, {31, 32, 33, 34, 35}, {41, 42, 43, 44, 45}};

Ex2. Write a program that takes two dimensional two matrices of any size and applyi. Addition

ii. Subtraction andiii. Multiplication

on them.

4) Stage a2 (assess)

73

Page 74: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Lab Work:

In each laboratory you are assessed on your work within lab session based on your participation, discussions and achievement of lab activities. Thus, each lab has a portion of the (LAB WORK MARK). Therefore, a checklist of each lab is used to evaluate your work.

This checklist accounts the following criteria:

Following the lab manual step by step

Answering given questions concisely and precisely

Practicing and implementing given examples correctly

Writing code of required programming tasks

Being focused, positive, interactive and serious during lab session

Asking good questions or answering instructor questions if any

74

Page 75: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Statement Purpose

This lab will give you the practice with string processing and recursion in C

Activity Outcomes:

This lab teaches you the following topics:

String Functions in C

Implementation of Recursion in C

75

LAB # 09

Page 76: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

1) Stage J (Journey)

A. String in CStrings are actually one-dimensional array of characters terminated by a null character '\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'};

If you follow the rule of array initialization then you can write the above statement as follows

char greeting[] = "Hello";

Following is the memory presentation of the above defined string in C

C supports a wide range of functions that manipulate null-terminated string

S.N. Function & Purpose

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.

76

Page 77: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

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.

B. Recursion

Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function.

The C programming language supports recursion, i.e., a function to call itself. But while using recursion, programmers need to be careful to define an exit condition from the function, otherwise it will go into an infinite loop. Recursive functions are very useful to solve many mathematical problems, such as calculating the factorial of a number, generating Fibonacci series, etc.

2) Stage a1 (apply)

Activity 1. C program which used strcpy string function

#include <stdio.h>

#include <string.h>

int main () {

char str1[12] = "Hello";

char str2[12] = "World";

char str3[12];

77

Page 78: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

/* copy str1 into str3 */

strcpy(str3, str1);

printf("strcpy( str3, str1) : %s\n", str3 );

return 0;

}

Activity 2. C program which used strcat string function

#include <stdio.h>

#include <string.h>

int main () {

char str1[12] = "Hello";

char str2[12] = "World";

char str3[12];

/* concatenates str1 and str2 */

strcat( str1, str2);

printf("strcat( str1, str2): %s\n", str1 );

return 0;

}

Activity 3. C program which used strlen string function

#include <stdio.h>

#include <string.h>

int main () {

char str1[12] = "Hello";

/* total lenghth of str1 after concatenation */

len = strlen(str1);

printf("strlen(str1) : %d\n", len );

return 0;

}

78

Page 79: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Activity 4 Example: Find the Frequency of Characters

#include <stdio.h>

int main()

{

char str[1000], ch;

int i, frequency = 0;

printf("Enter a string: ");

gets(str);

printf("Enter a character to find the frequency: ");

scanf("%c",&ch);

for(i = 0; str[i] != '\0'; ++i)

{

if(ch == str[i])

++frequency;

}

printf("Frequency of %c = %d", ch, frequency);

return 0;

}

Output

Enter a string: This website is awesome.

Enter a character to find the frequency: e

Frequency of e = 4

79

Page 80: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Activity 5 Remove Characters in String Except Alphabets

#include<stdio.h>

int main()

{

char line[150];

int i, j;

printf("Enter a string: ");

gets(line);

for(i = 0; line[i] != '\0'; ++i)

{

while (!( (line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z') || line[i] == '\0') )

{

for(j = i; line[j] != '\0'; ++j)

{

line[j] = line[j+1];

}

line[j] = '\0';

}

}

printf("Output String: ");

puts(line);

return 0;

}

Output

Enter a string: p2'r-o@gram84iz./

Output String: programiz

80

Page 81: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Activity 6 C program to generate the Fibonacci series for a given number using a recursive function

#include <stdio.h>

int fibonacci(int i) {

if(i == 0) {

return 0;

}

if(i == 1) {

return 1;

}

return fibonacci(i-1) + fibonacci(i-2);

}

int main() {

int i;

for (i = 0; i < 10; i++) {

printf("%d\t\n", fibonacci(i));

}

return 0;

}

Output of above program is

0 1 1 2 3 5 8 13 21 34

Activity 7 C program to generate the factorial of a number using recursive function

#include <stdio.h>

long int multiplyNumbers(int n);

int main()

81

Page 82: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

{

int n;

printf("Enter a positive integer: ");

scanf("%d", &n);

printf("Factorial of %d = %ld", n, multiplyNumbers(n));

return 0;

}

long int multiplyNumbers(int n)

{

if (n >= 1)

return n*multiplyNumbers(n-1);

else

return 1;

}

Output 8

Enter a positive integer: 6

Factorial of 6 = 720

Activity C program to count number of digits in an integer

#include <stdio.h>

int main()

{

long long n;

int count = 0;

printf("Enter an integer: ");

scanf("%lld", &n);

while(n != 0)

{

// n = n/10

n /= 10;

++count;

}

82

Page 83: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

printf("Number of digits: %d", count);

}

Output

Enter an integer: 3452

Number of digits: 4

3) Stage v (verify)Ex1. Write a C program which takes two string as input and compare both strings using strcmp function

Ex2. What will be the output of following code

#include<stdio.h>void main(){    char arr[7]="Network";    printf("%s",arr);}

Ex 3. Write a program which take Positive Integer as input from the user and generate its factors using recursion

Ex4. Write a C Program to Find whether a Number is Prime or Not using Recursion

Ex5. C Program to Find LCM of a Number using Recursion

83

Page 84: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

4) Stage a2 (assess)Lab Work:

In each laboratory you are assessed on your work within lab session based on your participation, discussions and achievement of lab activities. Thus, each lab has a portion of the (LAB WORK MARK). Therefore, a checklist of each lab is used to evaluate your work. This checklist accounts the following criteria:

Following the lab manual step by step

Answering given questions concisely and precisely

Practicing and implementing given examples correctly

Writing code of required programming tasks

Being focused, positive, interactive and serious during lab session

Asking good questions or answering instructor questions if any

84

Page 85: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Statement Purpose

This lab will give you the practice with File Input/output in C

Activity Outcomes:

Understand the importance and use of files in C

Create, Read from and Write to files

85

LAB # 10

Page 86: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

1) Stage J (Journey)A file is a named collection of data, stored in secondary storage (typically). It is stored as sequence of bytes which are logically contiguous (may not be physically contiguous on disk). The last byte of a text file contains the end-of-file character (EOF), with ASCII code 1A (hex). While reading a text file, the EOF character can be checked to know the end. Typical operations on files:

1. Open

2. Read

3. Write

4. Close

There are two kinds of files, text files which contains ASCII codes only and binary

files which can contain non-ASCII characters.

Opening Files

You can use the fopen( ) function to create a new file or to open an existing file. This call will initialize an object of the type FILE, which contains all the information necessary to control the stream. The prototype of this function call is as follows

FILE *fopen( const char * filename, const char * mode );

Here, filename is a string literal, which you will use to name your file, and access mode can have one of the following values −

Mode Description

r Opens an existing text file for reading purpose.

w Opens a text file for writing. If it does not exist, then a new file is created. Here your program will start writing content from the beginning of the file.

a Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here your program will start appending content in the existing file content.

r+ Opens a text file for both reading and writing.

86

Page 87: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

w+ Opens a text file for both reading and writing. It first truncates the file to zero length if it exists, otherwise creates a file if it does not exist.

a+ Opens a text file for both reading and writing. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended.

If you are going to handle binary files, then you will use following access modes instead of the above mentioned ones −

"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"

Closing a File

To close a file, use the fclose( ) function. The prototype of this function is −

The fclose(-) function returns zero on success, or EOF if there is an error in closing the file. This function actually flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file. The EOF is a constant defined in the header file stdio.h. There are various functions provided by C standard library to read and write a file, character by character, or in the form of a fixed length string.

Writing a File

Following is the simplest function to write individual characters to a stream

int fputc( int c, FILE *fp );The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the written character written on success otherwise EOF if there is an error. You can use the following functions to write a null-terminated string to a stream 

int fputs( const char *s, FILE *fp );

The function fputs() writes the string s to the output stream referenced by fp. It returns a non-negative value on success, otherwise EOF is returned in case of any error. You can use int fprintf(FILE *fp,const char *format, ...) function as well to write a string into a file.

Reading a File

Given below is the simplest function to read a single character from a file

int fgetc( FILE * fp );The fgetc() function reads a character from the input file referenced by fp. The return value is the character read, or in case of any error, it returns EOF. The following function allows to read a string from a stream −

87

Page 88: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

char *fgets( char *buf, int n, FILE *fp );The functions fgets() reads up to n-1 characters from the input stream referenced by fp. It copies the read string into the buffer buf, appending a null character to terminate the string. If this function encounters a newline character '\n' or the end of the file EOF before they have read the maximum number of characters, then it returns only the characters read up to that point including the new line character. You can also use int fscanf(FILE *fp, const char *format, ...) function to read strings from a file, but it stops reading after encountering the first space character.

2) Stage a1 (apply)Activity 1. Display contents of a file on screen

# include "stdio.h"

void main( )

{

FILE *fp ;

char ch ;

fp = fopen ( "PR1.c", "r" ) ;

while ( 1 )

{

ch = fgetc ( fp ) ;

if ( ch == EOF )

break ;

printf ( "%c", ch ) ;

}

fclose ( fp ) ;

}

Activity 2 Writing on a File

#include <stdio.h>

main() {

FILE *fp;

fp = fopen("/tmp/test.txt", "w+");

88

Page 89: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

fprintf(fp, "This is testing for fprintf...\n");

fputs("This is testing for fputs...\n", fp);

fclose(fp);

}

Activity 3. Reading from a file

#include <stdio.h>

main() {

FILE *fp;

char buff[255];

fp = fopen("/tmp/test.txt", "r");

fscanf(fp, "%s", buff);

printf("1 : %s\n", buff );

fgets(buff, 255, (FILE*)fp);

printf("2: %s\n", buff );

fgets(buff, 255, (FILE*)fp);

printf("3: %s\n", buff );

fclose(fp);

}

3) Stage v (verify)

Ex1. Write a program to add the contents of one file at the end of another.

Ex2. Write a program which read characters from keyboard and write in a file until user input “enter key” from keyboard

Ex3. Write a program to carry out the following:

(a) Read a text file ‘INPUT.TXT’

89

Page 90: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

(b) Print each word in reverse order

Example,

Input: PAKISTAN IS MY COUNTRY

Output: NATSIKAP SI YM YRTNUOC

4) Stage a2 (assess)Lab Work:

In each laboratory you are assessed on your work within lab session based on your participation, discussions and achievement of lab activities. Thus, each lab has a portion of the (LAB WORK MARK). Therefore, a checklist of each lab is used to evaluate your work.

This checklist accounts the following criteria:

Following the lab manual step by step

Answering given questions concisely and precisely

Practicing and implementing given examples correctly

Writing code of required programming tasks

Being focused, positive, interactive and serious during lab session

Asking good questions or answering instructor questions if any

90

Page 91: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Statement Purpose

This lab will give you the description about the errors in C

Activity Outcomes

This lab teaches you the following topics:

Syntax error

Logic error

Run time error

91

LAB # 11

Page 92: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

1) Stage J (Journey)Error is a abnormal condition whenever it occurs execution of the program is stopped these are mainly classified into following types.

1. Compile time error/Syntax error2. Logic Error3. Run time error

Compile time error/Syntax error

A collection of the rules for writing programs in a programming language is known as

syntax. All program statements are written according do these rules. Syntax error is a type

of error that occurs when a invalid statement is written in program. The compiler detects

syntax errors and display error massage to describe the cause of error. A program

containing syntax errors can't be compiled successfully.

These can be many causes of syntax error some important causes are as follows:

The statement terminator is missing at the end of statement like coma, semicolon ( ); etc.

A misspelled keyword is used in the program. Any of the delimiters is missing.

Logical Error

Logical errors are the errors in the output of the program. The presence of logical errors leads to undesired or incorrect output and are caused due to error in the logic applied in the program to produce the desired output. Also, logical errors could not be detected by the compiler, and thus, programmers has to check the entire coding of a c program line by line.

Run time error

runtime errors are those errors that occur during the execution of a c program and generally occur due to some illegal operation performed in the program. Examples of some illegal operations that may produce runtime errors are:

Dividing a number by zero

Trying to open a file which is not created Lack of free memory space

It should be noted that occurrence of these errors may stop program execution, thus to

encounter this, a program should be written such that it is able to handle such unexpected

errors and rather than terminating unexpectedly, it should be able to continue operating.

92

Page 93: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

This ability of the program is known as robustness and the code used to make a program

robust is known as guard code as it guards program from terminating abruptly due to

occurrence of execution errors.

2) Stage a1 (apply)

Activity 1. Syntax error

Examples of Syntax error

1. int a,b:

2. a=5 ( while a is not declared)

3. int a;

a=6 ( semicolon is missing)

Activity 2. Logical Error

1. You want to find the modulo of a certain number eg: a%4) instead you wrote the program for division(eg: a/4) then this type of error is considered to be the logical error.

2. For example the following program

#include <stdio.h>

int main()

{

int firstNumber, secondNumber, sumOfTwoNumbers;

printf("Enter two integers: ");

// Two integers entered by user is stored using scanf() function

scanf("%d %d", &firstNumber, &secondNumber);

// sum of two numbers in stored in variable sumOfTwoNumbers

sumOfTwoNumbers = firstNumber * secondNumber;

93

Page 94: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

// Displays sum

printf("%d + %d = %d", firstNumber, secondNumber, sumOfTwoNumbers);

return 0;

}

Note the programmer wants to sum the two numbers but he is using the symbol of multiplication so it will generate the wrong result

Activity 3. Logical Errors

1. Divide by Zero Errors

#include <stdio.h>

#include <stdlib.h>

main() {

int dividend = 20;

int divisor = 0;

int quotient;

quotient = dividend / divisor;

fprintf(stderr, "Value of quotient : %d\n", quotient );

exit(0);

}

This program will result an error as the divisor is 0, in following program the problem is fixed.

#include <stdio.h>

#include <stdlib.h>

main() {

94

Page 95: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

int dividend = 20;

int divisor = 0;

int quotient;

if( divisor == 0){

fprintf(stderr, "Division by zero! Exiting...\n");

exit(-1);

}

quotient = dividend / divisor;

fprintf(stderr, "Value of quotient : %d\n", quotient );

exit(0);

}

3) Stage v (verify)Ex1. Find the Syntax error from the following program

#include <stdio.h>

// Variable declaration:

extern int a, b;

extern int c;

extern float f;

int main () {

/* variable definition: */

int a, b;

int c;

float f;

/* actual initialization */

a = 10;

b = 20;

d = a + b;

printf("value of c : %d \n", c);

95

Page 96: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

f = 70.0/3.0;

printf("value of f : %f \n", f);

return 0;

}

Ex2. Find the Logical error from the following program

#include <stdio.h>

int main()

{

int a = 9,b = 4, c;

c = a+b;

printf("a+b = %d \n",c);

c = a-b;

printf("a-b = %d \n",c);

c = a*b;

printf("a*b = %d \n",c);

/*Divide b with a */

c=a/b;

printf("a/b = %d \n",c);

c=a%b;

printf("Remainder when a divided by b = %d \n",c);

return 0;

}

Ex. 3 Find the Logical Error from the following program

#include <stdio.h>

int main () {

96

Page 97: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

/* local variable definition */

int a = 100;

/* check the Boolean condition wheather a < 10 or not */

if( a < 20 ) {

/* if condition is true then print the following */

printf("a is less than 20\n" );

}

printf("value of a is : %d\n", a);

return 0;

}

4) Stage a2 (assess)

Lab Work: In each laboratory you are assessed on your work within lab session based on your participation, discussions and achievement of lab activities. Thus, each lab has a portion of the (LAB WORK MARK). Therefore, a checklist of each lab is used to evaluate your work.

This checklist accounts the following criteria: Following the lab manual step by step Answering given questions concisely and precisely Practicing and implementing given examples correctly Writing code of required programming tasks Being focused, positive, interactive and serious during lab session Asking good questions or answering instructor questions if any

97

Page 98: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Statement Purpose

This lab will give you the description about Testing fundamentals.

Activity Outcomes

This lab teaches you the following topics:

Code Review

Unit testing

98

LAB # 12

Page 99: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

1) Stage J (Journey)

Code Review

Code review is systematic examination (often known as peer review) of computer source code. It is intended to find and fix mistakes overlooked in the initial development phase, improving both the overall quality of software and the developers’ skills.

The main goals of code review are:

1. To spot and fix defects early in the process.2. Better-shared understanding of the code base as team members learn from each other3. Helps to maintain a level of consistency in design and implementation.4. Helps to identify common defects across the team thus reducing rework.5. Builds confidence of stakeholders about technical quality of the execution.6. Uniformity in understanding will help interchangeability of team members in case of non-

availability of any one of them.7. A different perspective. “Another set of eyes” adds objectivity. Similar to the reason for

separating your coding and testing teams, peer reviews provide the distance needed to recognize problems.

8. Pride/reward. Recognition of coding prowess is a significant reward for many programmers.9. Team cohesiveness. Working together helps draw team members closer. It also provides a

brief respite from the isolation that coding often brings

The main areas a reviewer is focusing on are as follows:

General Unit Testing Comment and Coding Conventions Error Handling Resource Leaks Thread Safety Control Structures Performance Functionality Security

Roles and Responsibilities

Developer: is the person who has written the code to be reviewed and has initiated the review request.

Reviewer/s: are the people who are going to review the code and report the findings to the developer.

99

Page 100: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Tips for Reviewer

1. Critique code instead of people – be kind to the coder, not to the code. As much as possible, make all of your comments positive and oriented to improving the code. Relate comments to local standards, program specs, increased performance, etc.

2. Treat people who know less than you with respect, deference, and patience. Nontechnical people who deal with developers on a regular basis almost universally hold the opinion that we are prima donnas at best and crybabies at worst. Don’t reinforce this stereotype with anger and impatience.

3. The only true authority stems from knowledge, not from position. Knowledge engenders authority, and authority engenders respect – so if you want respect in an egoless environment, cultivate knowledge.

4. Please note that Review meetings are NOT problem solving meetings.5. Ask questions rather than make statements. A statement is accusatory. “You didn’t follow

the standard here” is an attack—whether intentional or not. The question, “What was the reasoning behind the approached you used?” is seeking more information. Obviously, that question can’t be said with a sarcastic or condescending tone; but, done correctly, it can often open the developer up to stating their thinking and then asking if there was a better way.

6. Avoid the “Why” questions. Although extremely difficult at times, avoiding the”Why” questions can substantially improve the mood. Just as a statement is accusatory—so is a why question. Most “Why” questions can be reworded to a question that doesn’t include the word “Why” and the results can be dramatic. For example, “Why didn’t you follow the standards here…” versus “What was the reasoning behind the deviation from the standards here…”

7. Remember to praise. The purposes of code reviews are not focused at telling developers how they can improve, and not necessarily that they did a good job. Human nature is such that we want and need to be acknowledged for our successes, not just shown our faults. Because development is necessarily a creative work that developers pour their soul into, it often can be close to their hearts. This makes the need for praise even more critical.

8. Make sure you have good coding standards to reference. Code reviews find their foundation in the coding standards of the organization. Coding standards are supposed to be the shared agreement that the developers have with one another to produce quality, maintainable code. If you’re discussing an item that isn’t in your coding standards, you have some work to do to get the item in the coding standards. You should regularly ask yourself whether the item being discussed is in your coding standards.

9. Remember that there is often more than one way to approach a solution. Although the developer might have coded something differently from how you would have, it isn’t necessarily wrong. The goal is quality, maintainable code. If it meets those goals and follows the coding standards, that’s all you can ask for.

10. You shouldn’t rush through a code review - but also, you need to do it promptly. Your coworkers are waiting for you.

11. Review fewer than 200-400 lines of code at a time.

Unit Testing

Unit testing, a testing technique in which individual modules are tested to determine if there are any issues by the developer himself. It is concerned with functional correctness of the standalone modules. The main aim is to isolate each unit of the system to identify, analyze and fix the defects.

100

Page 101: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Unit Testing Advantages

1. Reduces Defects in the Newly developed features or reduces bugs when changing the existing functionality.

2. Reduces Cost of Testing as defects are captured in very early phase.3. Improves design and allows better refactoring of code.4. Unit Tests, when integrated with build gives the quality of the build as well

Unit Testing Life Cycle

Unit Testing Techniques

Black Box Testing - Using which the user interface, input and output are tested. White Box Testing - used to test each one of those functions behaviour is tested. Gray Box Testing - Used to execute tests, risks and assessment methods.

2) Stage a1 (apply)

101

Page 102: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Review Guidelines

C Programming Standards

Readability and Maintainability

The programmer makes consistent use of indentation.

The programmer makes consistent use of braces.

Include Files

Include files are listed immediately after the file documentation block.

The ‘<’ and ‘>’ symbols are used to include system header files. The system header files are listed in alphabetical order.

Double quotation is used for the inclusion of all non-system header files. The non-system header files are listed in alphabetical order.

Absolute or relative paths are not used in the #include to point to header file locations.

Header files contain preprocessor directives preventing multiple inclusions.

Variable and Function Scope

Global variables are used sparingly.

Variable Declaration, Initialization, and Qualifiers

Variable names with leading and/or trailing underscores are not used.

The names of constants defined by #define, enumerated constants, and constants defined with a specific data type are in all CAPITAL letters.

Variables names which differ only by case are not used.

Variable names do not conflict with standard library function names.

Variable names are descriptive.

A consistent format for the naming of variables is used. Words in the names of local variables are distinguished either by separating them by underscores or by using camel case with the leading letter of the variable in lower case.

The names of variables of user-defined types be in camel case with the first letter capitalized. Underscores are not used.

102

Page 103: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Pointers are initialized to NULL.

Pointers are tested for NULL before being referenced.

Pointers and Dynamic Memory

Dynamically allocated memory is deallocated when no longer needed.

Functions do not return pointers to non-static stack dynamic variables.

Large arrays are dynamically allocated on the heap.

Functions

A consistent format for the naming of functions is used. Words in function names are distinguished either by separating them by underscores or by using camel case with the leading letter of the function name in lower case.

Function prototypes are declared in header files which are included in the source modules that call the functions.

The arguments specified in function prototypes are associated with variable names. The variable names match the variable names in the function definitions.

Functions used only in the source module they are created in are preceded by the “static” keyword. They do not have prototypes in header files. The return types of functions are explicitly stated.

Standard C Library routines are used where appropriate.

Portability

Non-portable code is avoided.

The code does not assume that data are stored in a particular way with respect to word boundaries in memory.

C Programming Guidelines

File Organization

The names of C source files which belong to a common library or an executable have a common prefix.

Comments

Block comments, one-line comments and inline comments are used appropriately.

A blank line is placed before and after a block comment or a one-line comment to separate it from the surrounding source code.

Variable Declaration, Initialization, and Qualifiers

103

Page 104: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

Loop index variable names are short.

Pointer variables are named in a consistent fashion.

User Defined Types

Enumerations are used to group logically-related constants.

Macros are used judiciously.

Parentheses are used in macros to ensure correct evaluation order.

Structures are used to reduce the number of function calling arguments.

Pointers and Dynamic Memory

Pointers are used as arguments to functions in place of passing by value large user-defined types or structures.

Functions

Functions are “inlined” if they are small and called many times.

The number of library function calls is limited in large loops.

Embedded statements are avoided, minimizing the possibility of side effects.

Pointers and Dynamic Memory

Pointers are used as arguments to functions in place of passing by value large user-defined types or structures.

Functions

Functions are “inlined” if they are small and called many times.

The number of library function calls is limited in large loops.

Embedded statements are avoided, minimizing the possibility of side effects.

Program Control

Unnecessary code is avoided in loops.

The number of loop counters is kept to a minimum.

Loops are combined when possible to reduce the total loop overhead costs.

Logical tests are optimized by performing the fastest and most capable test first.

Non-Boolean variables are tested against an explicit value.

Unit Testing A unit test is just some code that calls some other code, used to test that it behaves as you expect

104

Page 105: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

void this_is_a_unit_test(void) {

      int next = get_next_fibonacci(5);

      ASSERT_EQUAL(next,8);

}

In this example we're testing the get_next_fibonacci function. We call the function with an input of 5 and we expect to get an 8 back.

3) Stage v (verify)

Ex1. Review the following code according to above mentioned standard

#include<stdio.h>

float calculate_area(int);

int main()

{

int radius;

float area;

printf("\nEnter the radius of the circle : ");

scanf("%d",&radius);

area = calculate_area(radius);

printf("\nArea of Circle : %f ",area);

return(0);

}

float calculate_area(int radius)

{

float areaOfCircle;

areaOfCircle = 3.14 * radius * radius;

return(areaOfCircle);

}

Ex2. Write a script for the unit test of following code

#include <stdio.h>

int main()

{

long long n;

int count = 0;

105

Page 106: mnk.muhammadiyah.infomnk.muhammadiyah.info/Lab Manuals/ver 2/CSC103_PF... · Web viewmnk.muhammadiyah.info

printf("Enter an integer: ");

scanf("%lld", &n);

while(n != 0)

{

// n = n/10

n /= 10;

++count;

}

printf("Number of digits: %d", count);

}

106