lab manual: programming fundamentals (cs-302) lab session 1:...

34
Lab Manual CS-302, Department of CS & IT, UoB 2013 Dr. Ihsan Ullah 1 Lab Manual: Programming Fundamentals (CS-302) Lab session 1: Getting started Objective: Working with the code::block IDE: understanding the environment, typing the code, compilation, error correction, execution of programs, practicing to display some text on the screen. Open Code::Block IDE and then click on File New Empty file as shown below. Then click on the save button, choose a folder for your programs and write a File name (e.g. prog1) as shown in the next screenshot.

Upload: others

Post on 20-Mar-2020

12 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

1

Lab Manual: Programming Fundamentals (CS-302)

Lab session 1: Getting started

Objective: Working with the code::block IDE: understanding the environment, typing

the code, compilation, error correction, execution of programs, practicing to display some text

on the screen.

Open Code::Block IDE and then click on File New Empty file as shown below.

Then click on the save button, choose a folder for your programs and write a File name (e.g.

prog1) as shown in the next screenshot.

Page 2: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

2

Now type your program as shown below.

To compile this program, press ctrl+F9 keys and to Run press F9 key. If there are no errors in

the code, it will show the following screen.

Here, the output of your program is shown in the first line while the remaining two lines show

information about the program execution and to proceed further. Pressing any key will quit this

Page 3: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

3

screen.

In case of a syntax error, the erroneous line number is marked by a red box which shows the

location of the error. Furthermore, an error message is shown in the logs window below as

shown in the next screenshot.

The text inside printf() function can be displayed over different lines through using the escape

sequence ‘ \n ’. For instance, type the following code and see the output.

# include <stdio.h>

void main (void)

{

printf("hi! \nI am here to teach you how to program");

}

Exercise 1: Use other escape sequences such as \\, \t etc. in the above given code.

Exercise 2: Write a program that prints your full name with the symbols as shown below.

=============== == your name == ===============

Page 4: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

4

Lab session 2: Variables and formatted input

Objective: To get insight into defining and using variables, applying arithmetic

operations on them and displaying their values on the screen along with text through printf()

function. Moreover, to learn taking formatted input through scanf() function.

Variable is a named space in memory. To define a variable, write its data type followed by its

name you choose. The following program demonstrates such an example.

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

int a; float b;

a=3; b=2.5;

printf("value of a=%d, value of b=%f",a,b); }

Modify this program to add other types of variables such as char, long etc. and print their

values.

Type the following code and run it to see its output.

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

float length; float width; float area; length=5.6; width=4.3; area=length*width; printf("Area=%f",area);

}

Same type of variables can be declared together by mentioning the type once and separating

variable names by a comma. Following is the same program written in a shorter form.

# include <stdio.h> void main (void)

Page 5: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

5

{ float length, width, area; length=5.6; width=4.3; area=length*width; printf("Area=%f",area);

}

Exercise 3: Write a program to calculate the area of a circle. (area of circle= Pi x r2 )

Note: Input from keyboard can be taken by using the scanf() function. Like print(), this function

too has its declaration in stdio.h header file.

Given below is a repeat of the above-given program but instead of fixed values in the code,

they are being taken from the user. Type the following code and run it.

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

float length, width, area; printf("please enter length: "); scanf("%f",&length); printf("please enter width: "); scanf("%f",&width); area=length*width; printf("\n Area=%.2f\n\n",area);

} Modify the above-given program by changing the types of variables used.

Exercise 4: Write your own program that asks to enter marks of a student in four subjects, calculates and displays the total and percent marks.

Page 6: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

6

Lab Sessions 3-4: Selection structures

Objectives: To learn the use of different selection structures.

The following program demonstrates the use of if statement through calculating tax on a salary

which lies in the tax circle. Let us suppose that a basic salary of rupees 10000 or above lies in

that range.

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

floatbasic_salary,tax; printf("Enter basic salary:"); scanf("%f",&basic_salary); if(basic_salary>=10000) {

tax=2*basic_salary/100; //2 per cent tax printf("\nTax to be paid: %.2f \n\n\n",tax);

} } The above program will not display any message if the basic salary is less than 10000. To make it more interactive, add the following else statement to it else printf("\nYou are exempted from paying the tax\n\n\n"); Statements can be nested by putting if statement inside the body of another if statement. In that case the inner if evaluates only if the outer if evaluates to true. Given below is a program that demonstrates nested if statements. It takes the marks in different subjects and calculates the grade achieved by a student. Write down this code and run it a few times. #include<stdio.h> void main(void) {

Int const total_marks=400; float sub1,sub2,sub3,sub4,percent_Marks; printf("Enter marks in four subjects, separated by spaces:"); scanf("%f%f%f%f",&sub1,&sub2,&sub3,&sub4); percent_Marks=((sub1+sub2+sub3+sub4)/total_marks)*100; if(percent_Marks>=90) printf("Grade A+"); else if(percent_Marks<90 &&percent_Marks>=80)

Page 7: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

7

printf("Grade A"); else if(percent_Marks<80 &&percent_Marks>=70)

printf("Grade B"); else if(percent_Marks<70 &&percent_Marks>=60) printf("Grade C");

else if(percent_Marks<60 &&percent_Marks>=50) printf("Grade D");

else printf("Not qualified"); }

Exercise 5: Write a program that inputs a number and tells whether it is even or odd. (Hint: Use % operator to check the division.)

The following program inputs a character from the keyboard and tells whether it is a small case letter, capital case letter or a digit. Type this code and run it. # include <stdio.h> void main() { charch; printf("Enter any character:"); scanf("%c",&ch); if(ch>=65 &&ch<=90)

printf("\n You entered a capital letter \n"); else if(ch>97&&ch<=122)

printf("\nyou entered a small case letter\n"); else if(ch>=48 &&ch<=57)

printf("\nyou entered a digit\n"); else printf("\nyou entered a special character\n");

} The following code inputs two numbers and an arithmetic operator from the user and displays

the result.

#include<stdio.h> void main(void) { floata,b,r; char op; printf("Enter operation(example 4+5):"); scanf("%f%c%f",&a,&op,&b); switch(op)

Page 8: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

8

{ case '+': r=a+b; break; case '*': r=a*b; break; case '-': r=a-b; break; case '/': r=a/b; break;

} printf("\n Result is: %.2f \n\n",r); }

This program also adds a default case which runs when no other case is met and in that case the chosen operator by the user is invalid which is notified. Run this program with correct and incorrect operators. #include<stdio.h> void main(void) {

floata,b,r; char op; printf("operation(example 4+5):"); scanf("%f%c%f",&a,&op,&b); switch(op) { case '+': printf("\n The sum is: %.2f \n\n",a+b); break; case '*': printf("\n The product is: %.2f \n\n",a*b);

Page 9: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

9

break; case '-': printf("\n The subtraction is: %.2f \n\n",a-b); break; case '/': printf("\n The division is: %.2f \n\n",a/b); break; default: printf("\ninvalid operator (only +, -, /, *)\n"); }

}

Exercise 6: Write a program using nested if else construct instead of switch case structure to produce the same output as of the above-given program.

See the following code and before running it on the computer, decide its output. Then run the code and see what you get. #include<stdio.h> void main(void) {

int a; printf("Enter a number:"); scanf("%d”,&a); switch(a) {

case 1: case 2: case 3: case 4: printf("\n The number is from 1 to 4"); break; default: printf("\nSome other number");

} }

Page 10: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

10

The following program demonstrates the use of conditional operator. Run the code and compare it with if else statement. # include <stdio.h> void main() {

int num; printf("Enter a number to check:"); scanf("%d",&num); num%2==0?printf("Even number"):printf("Odd number");

}

Page 11: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

11

Lab Sessions 5-7: Iterations/loops

Objective: Syntax of different iteration structures, choosing the appropriate one for a

problem, the purpose and use of break and continue statements.

The following program demonstrates the use of for loop. It prints the first 10 positive odd

numbers.

# include <stdio.h>

void main()

{

int a;

for (a=1; a<20; a+=2)

{

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

}

}

Exercise 7: Modify the above program to print even numbers between 1 and 20.

The following program inputs an integer, calculates and displays its factorial.

#include<stdio.h>

int main()

{

int c,num, fact=1;

printf("Enter the number:");

scanf("%d",&num);

for (c=num ; c>0 ; c--)

fact=fact*c;

printf("Factorial of %d is %d \n",num,fact);

}

The following program prints a Fabonacci series of N terms where the number of terms is input

by the user.

#include<stdio.h>

Page 12: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

12

main()

{

int n, a = 0, b = 1, c, m;

int num;

printf("how many terms?");

scanf("%d",&num);

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

for ( m = 1 ; m < num-1 ; m++ )

{

c = a + b;

a = b;

b = c;

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

}

}

A program that demonstrates the use of while loop by taking characters as input, counts the

number of typed characters until en enter key is pressed.

#include<stdio.h>

#include<conio.h>

void main (void)

{

char ch;

int count=0;

printf("start typing… to end press enter: \n");

while(ch=getche()!='\r')

{

count++;

}

printf("\n\nYou pressed %d keys:",count);

}

The following program prints primes numbers between 1 and 100. A nested for loop has been

used to check the number, if prime or not.

Page 13: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

13

#include<stdio.h>

void main (void)

{

int a,num;

int flag;

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

{

flag=1;

for(a=2;a<(num/2);a++)

{

if (num%a==0)

{

flag=0;

break;

}

}

if(flag)

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

}

}

Exercise 7: Write a program that generates the following output through using loops.

ABCDE

FGHIJ

KLMNO

PQRST

UVWXY

A continue statement inside a loop skips the current iteration of the loop and proceeds directly

to the next iteration. The following program uses continue statement to exclude 5 multiples

from integers between 1 and 50.

#include<stdio.h>

void main (void)

{

Page 14: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

14

int a;

for(a=1;a<50;a++)

{

if (a%5==0)

continue;

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

}

}

A do while loop executes its body at least once and afterwards, its iterations depend upon the

condition. If the condition is true it will repeat otherwise the loop exits. Given below is a simple

program that demonstrates the use of do while loop by checking a number for being even or

odd and then prompts the user if he/she wants to check another number.

#include <stdio.h>

#include <conio.h>

void main (void)

{

int num,flag;

char ch;

do{

printf("\nplease enter a number: ");

scanf("%d",&num);

if(num%2==0)

printf("\n %d is even",num);

else

printf("\n %d is odd",num);

printf("\n Do you want to check another number? (press y for yes and any other key

for no)");

ch=getche();

if(ch=='y' || ch=='Y') flag=1;

else flag=0;

}

while(flag);

Page 15: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

15

}

A label and goto statement enables a jump from one statement to another without following

the ordered sequence. Such a jump is not recommended however, a goto example is given

below.

The following program is a repeat of the above-given program; however instead of pressing any

key for “no”, it requires to press “n” only. Therefore, in case of any other key pressed by the

user, the program must ask the user to choose between “y” and “n” only. Hence a jump is

required which has been achieved through using goto statement.

#include <stdio.h>

#include <conio.h>

void main (void)

{

int num,flag;

char ch;

do{

printf("\nplease enter a number: ");

scanf("%d",&num);

if(num%2==0)

printf("\n %d is even",num);

else

printf("\n %d is odd",num);

printf("\n Do you want to check another number? (y/n)");

label1:

ch=getche();

if(ch=='y' || ch=='Y') flag=1;

else if(ch=='n' || ch=='N') flag=0;

else

{

printf(" \n please choose y or n: ");

goto label1;

}

}

while(flag);

}

Page 16: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

16

Since goto is not recommended, there are ways to avoid it. The following program achieves the

desired result without using the goto statement.

#include<stdio.h>

#include<conio.h>

void main (void)

{

int num;

char ch;

do

{

printf("\nplease enter a number: ");

scanf("%d",&num);

if(num%2==0)

printf("\n %d is even",num);

else

printf("\n %d is odd",num);

printf("\n Do you want to check another number? (y/n)");

while(1)

{

ch=getche();

if(ch=='y' || ch=='Y' || ch=='n' || ch=='N')

break;

else

printf("\n please choose y or n: ");

}

}

while(ch=='y' || ch=='Y' );

}

Exercise 8: Write a program that inputs two numbers say x and y and calculates x raise to the

power y.

Page 17: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

17

Home work:

1. Write a program that inputs a number and displays its reverse.

2. Write a program that inputs a number and counts its digits.

Page 18: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

18

Lab session 8: Functions and pointers

Objective: Being able to code user defined functions, their types and use to enhance

readability of the program and avoid redundancy. The use of pointers, call by value and call by

reference.

A function is a block of code that performs a specific task. Each function has a unique name

through which it can be called. Functions can accept arguments during calling and can return

values to the calling program. Given below is a simple function taking no arguments and not

returning any value.

#include<stdio.h> void line(void); //prototype of function line() just like void main (void) { line(); printf("\t\t Hello"); line(); } void line(void) //function definition { printf("\n ***********************************\n"); } The following program uses a function named as primeCheck(). This function takes an integer as an argument and checks whether it is prime or not. #include<stdio.h> void primeCheck(int n); //prototype void main (void) { int num; printf("\nplease enter a number: "); scanf("%d",&num); primeCheck(num); } void primeCheck(int n) //function {

Page 19: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

19

int flag=1; int a; for(a=2;a<n/2;a++) { if (n%a==0)

{ printf("\n%d is composite\n",n); flag=0; break; } } if(flag) printf("\n %d is prime",n); } A function that returns a value: The following program inputs a number, passes it to a function which calculates returns its factorial. #include<stdio.h> void main (void) { int num,res; printf("enter a number: "); scanf("%d",&num); res=fact(num); printf("Factorial of %d is %d",num,res); } int fact(int n){ int a,fact=1; for(a=n;a>1;a--) fact*=a; return fact; }

The following program declares a variable and a pointer where the latter points to the former and prints the address and content of the variable.

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

Page 20: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

20

int a=5; int *x; x=&a; printf("Value of a=%d \n",a); //content of a printf("Address of a=%d \n",&a); //address of a printf("Value of a=%d \n",*x); //content of a through a pointer to a printf("address of a=%d \n",x); //address of a through a pointer to a }

Exercise 9: Write a program that defines two pointers. Store the address of one pointer into another.

The following program contains a function which accepts calling by reference.

#include<stdio.h> void func(int*); void main (void) { int a=5; func(&a); //call func with the address of a printf("Value of a=%d \n",a); //value of a after the function call } void func(int *x) { *x=*x+10; //change the value of a through pointer x. // *x means the content/value of the variable to which x points }

A functional can return only one value. However, to enable a function return more than one value, calling by reference can be used that achieves this indirectly. Here is an example.

#include <stdio.h> void areaperi(int,float*,float*); void main(void) { int radius ; float area, perimeter ; printf ( "\nEnter radius of a circle " ) ; scanf ( "%d", &radius ) ;

Page 21: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

21

areaperi(radius, &area, &perimeter) ; printf ("Area = %f", area) ; printf ("\nPerimeter = %f",perimeter) ; } void areaperi( int r, float *a, float *p ) { *a = 3.14 * r * r ; *p = 2 * 3.14 * r ;

} A function calling itself is termed as recursion. The following program demonstrates that use of recursion. It calculates the factorial of a number.

# include<stdio.h> int factorial(int number); void main() { int x; printf("Enter the number:"); scanf("%d",&x); printf("factorial of %d is %d \n",x,factorial(x)); } int factorial(int number) { if(number <= 1) return 1; return number * factorial(number - 1); }

Exercise 10: Write a program that inputs a number, passes it into a function and the function reverses it through using recursion.

Page 22: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

22

Lab sessions 10-11: Arrays Objectives: Understanding the arrays data structure, accessing array elements, array initialization, manipulation, multi-dimensional arrays and passing arrays into functions, The following program demonstrates defining an array, storing elements in the array and accesses those elements.

# include<stdio.h> main() {

int sno[40]; //defining an integer array int a; for(a=0;a<40;a++) //loop to set array elements sno[a]=a+100; for(a=0;a<40;a++) //loop to print array elements printf("%d\t",sno[a]);

}

Arrays can be initialized through putting values in curly braces separated by commas for example, int arr[]={3,4,7,15,18,0,14}; Write a program that initializes an array and prints it’s all elements. Elements of an array can be set through taking input from the keyboard. Here is an example.

# include<stdio.h> main() { int marks[10]; //defining an integer array int a;

Page 23: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

23

for(a=0;a<10;a++) //loop to set array elements { printf("\nEnter marks:"); scanf("%d",&marks[a]); } printf("Marks are:\n"); for(a=0;a<10;a++) //loop to print array elements printf("%d\t",marks[a]); }

The following program demonstrates passing an array to a function. Remember that an array is passed by address.

# include<stdio.h> main() { int sno[40]; int a; for(a=0;a<40;a++) sno[a]=a+10; display(sno); } void display(int arr[]) { int i; for(i=0;i<40;i++) printf("%d\t",arr[i]); }

The following program verifies passing by address. Type and run this program and see how the actual array is modified in the function.

# include<stdio.h> main() { const int size=20; int sno[size]; int a;

Page 24: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

24

for(a=0;a<size;a++) sno[a]=a; printf("Arary before passing into the function\n\n"); for(a=0;a<size;a++) printf("%d\t",sno[a]); modify(sno,size); printf("Arary after passing int the function\n\n"); for(a=0;a<size;a++) printf("%d\t",sno[a]); } void modify(int arr[], int length) { int i; for(i=0;i<length;i++) arr[i]=arr[i]+10; printf("\n\n"); }

Two dimensional arrays can also be initialized. The following program demonstrates such a use. # include<stdio.h> void main(void) { //initialization int marks[][4]={{1,2,3,4},{345,456,435,378}}; //first dimension is optional int a,b; printf("\n**********Rsult****************\n"); for(a=0;a<2;a++)

{ for(b=0;b<4;b++) printf("%d\t",marks[a][b]); printf("\n"); }

Page 25: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

25

} Write a program that inputs roll numbers and marks of students and displays the result # include<stdio.h> void main(void) { const int size=2; int marks[2][2]; int a,b; for(a=0;a<size;a++)

{ printf("Enter roll number:"); scanf("%d",&marks[0][a]); printf("Enter marks:"); scanf("%d",&marks[1][a]); }

printf("\n**********Rsult****************\n"); for(a=0;a<2;a++)

{ for(b=0;b<size;b++) printf("%d\t",marks[a][b]); printf("\n"); }

}

Exercise 11: Define an array that inputs 10 integers, stores them, calculate their average value and display it.

Page 26: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

26

Lab sessions 12-13: Structures and variable storage classes Objective: Understanding the use of structures, their definition, accessing elements, passing a structure into a function, creating array of structures, use of global and static variables. Structure combines different type of variables in a same group accessed through a same name. The following program declares a function, sets its members and displays their values.

# include<stdio.h> void main(void) { struct result //structure declaration { int rno; int marks; char grade; } ; struct result s1; //defining variables of structure type printf("Enter grade: "); scanf("%c",&s1.grade); printf("Enter Roll number:"); scanf("%d",&s1.rno); printf("Enter Marks:"); scanf("%d",&s1.marks); printf("Roll no=%d Marks=%d Grade=%c",s1.rno,s1.marks,s1.grade); printf("\n\n"); }

Strings can be manipulated in different ways in C language. Here is a program that uses structure having a string member.

# include<stdio.h> struct result {

int rno; char name[15]; int marks; char grade; float per;

Page 27: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

27

} ; void main(void) { struct result s1; s1.rno=1; strcpy(s1.name,"Ahmed"); //copies string Ahmed into s1.name s1.marks=90; s1.per=90; s1.grade='A'; printf("Roll=%d Name=%s Marks=%d percentage=%.2f Grade=%c", s1.rno,s1.name,s1.marks,s1.per,s1.grade); printf("\n\n");

} The following program uses puts() and gets() functions for string output and input. Moreover, this program contains function for estimating percent marks and the grade. # include<stdio.h> float estPer(int); void estGrade(); char grade[2]; struct result { int rno; char name[20]; int marks; char grade[2]; float per; } ; struct result s1; void main(void) { char nm[20]; puts("Enter Name:"); gets( s1.name ); puts("Enter Roll number:"); scanf("%d",&s1.rno); puts("Enter Marks:");

Page 28: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

28

scanf("%d",&s1.marks); s1.per=estPer(s1.marks); estGrade(); printf("\n\n----------------Result------------------------- \n\n"); printf("Roll=%d Name=%s Marks=%d percentage=%.2f Grade=%s",s1.rno,s1.name,s1.marks,s1.per,s1.grade); printf("\n\n"); } float estPer(int marks){ int total=500; float per1=marks*1.0/total*100; return per1; } void estGrade(){ if(s1.per>=90) strcpy(s1.grade,"A+"); else if(s1.per<90 && s1.per>=80) strcpy(s1.grade,"A"); else if(s1.per<80 &&s1.per>=70) strcpy(s1.grade,"B"); else if(s1.per<70 && s1.per>=60) strcpy(s1.grade,"C"); else if(s1.per<60 && s1.per>=50) strcpy(s1.grade,"D"); else strcpy(s1.grade,"F"); }

Exercise 12: Modify the above program by adding a new function that takes name as input and stores it in the appropriate structure member, instead of using gets() function.

The following program demonstrates how arrays of structures can be created and how they could be useful? This program inputs the complete result of students and displays their result. # include<stdio.h> float estPer(int); void estGrade(int); char grade[2];

Page 29: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

29

struct result { int rno; char name[20]; int marks; char grade[2]; float per; } ; struct result s1[3]; void main(void) { int a; for(a=0;a<3;a++) { printf("\nEntering data of student %d\n",a+1); printf("\nEnter Name:"); inputName(a); //scanf("%[^\n]s", s1[a].name ); //multiword string (string with spaces) printf("\nEnter Roll number:"); scanf("%d",&s1[a].rno); printf("\nEnter Marks:"); scanf("%d",&s1[a].marks); s1[a].per=estPer(s1[a].marks); estGrade(a); } printf("\n\n----------------Result------------------------- \n\n"); for(a=0;a<3;a++) { printf("Roll=%d \nName=%s \nMarks=%d \npercentage=%.2f \nGrade=%s\n",s1[a].rno,s1[a].name,s1[a].marks,s1[a].per,s1[a].grade); printf("\n----------------------------------------\n"); } } float estPer(int marks){ int total=500; float per1=marks*1.0/total*100; return per1;

Page 30: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

30

} void estGrade(int ind){ if(s1[ind].per>=90) strcpy(s1[ind].grade,"A+"); else if(s1[ind].per<90 && s1[ind].per>=80) strcpy(s1[ind].grade,"A"); else if(s1[ind].per<80 &&s1[ind].per>=70) strcpy(s1[ind].grade,"B"); else if(s1[ind].per<70 && s1[ind].per>=60) strcpy(s1[ind].grade,"C"); else if(s1[ind].per<60 && s1[ind].per>=50) strcpy(s1[ind].grade,"D"); else strcpy(s1[ind].grade,"F"); } void inputName(int ind){ char ch; int i=0; while((ch=getche())!='\r') s1[ind].name[i++]=ch; s1[ind].name[i++]='\0'; } Variable storage classes: The storage class of a variable decides its scope and lifetime. The following program explores the use of static variables. #include <stdio.h> void main(){ test(); test(); test(); } void test() { static int count; //to count the number of times this function is being called count++; printf("Function test has been called %d times\n",count); }

Page 31: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

31

The program given below demonstrates the use of global variables.

#include <stdio.h> void incr(void); void decr(void); int a; void main(){ a=10; incr(); incr(); decr(); } void incr() { a++; printf("Value of global variable a=%d \n",a); } void decr() { a--; printf("Value of global variable a=%d \n",a); }

Page 32: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

32

Lab Session 14: File input/output

Objective: Learning operations over files stored on the permanent memory. These include, creating a new file, open an existing file, reading and writing from/to files and closing a file. The following program reads the contents of a file by loading it into memory and displays them. To read a file, the file must be present. Here, we will be reading the following program which is saved as file1.c.

# include <stdio.h> //contains definition of FILE structure void main(void) { FILE *fp ; // FILE is a structure that contains file information such as size, mode of //opening, location in the file from where the next operation will occur, etc. char ch ; fp = fopen ( "file1.c", "r" ) ; /* opens the file. The first argument is the name of the file we want to open and the second argument is the mode in which the file will be opened. "r" means read mod */ while ( 1 ) // repeat the following process { ch = fgetc ( fp ) ; //read the current character from the file and point to the next one if ( ch == EOF ) //if the end of file has reached then stop the loop

break ; printf ( "%c", ch ) ; //print the character } fclose ( fp ) ; //close the file }

The following program takes strings from the keyboard and writes them to a file.

#include <stdio.h> void main(void ) { FILE *fp ; char s[80] ; fp = fopen ( "myFileC.txt", "w" ) ; if ( fp == NULL ) { puts ( "Cannot open the file" ) ;

Page 33: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

33

exit( ) ; } printf ( "\nEnter a few lines of text:\n press enter twice to stop…..\n" ) ; while ( strlen ( gets ( s ) ) > 0 ) { fputs ( s, fp ) ; //write the string to the file fputs ( "\n", fp ) ; //write new line } fclose ( fp ) ; } The following program writes records of mixed types of data into a file. #include <stdio.h> main( )

{ FILE *fp ; char add ; struct emp

{ char name[40] ; int age ; float bs ; } ;

struct emp e ; fp = fopen ( "emp.dat", "w" ) ; if ( fp == NULL )

{ puts ( "Cannot open file" ) ; exit(0) ; }

do () { printf ( "\nEnter name, age and basic salary: " ) ; scanf ( "%s %d %f", e.name, &e.age, &e.bs ) ; fprintf ( fp, "%s %d %f\n", e.name, e.age, e.bs ) ; //write a record printf ( "Add another record (Y/N) " ) ; fflush ( stdin ) ; add = getche( ) ; }

while(add == 'Y' || add==’y’); fclose ( fp ) ;

Page 34: Lab Manual: Programming Fundamentals (CS-302) Lab session 1: …csit.uob.edu.pk/images/web/staff/lecture/doc-6.2013-6-30... · 2015-09-10 · Lab Manual CS-302, Department of CS &

Lab Manual CS-302, Department of CS & IT, UoB 2013

Dr. Ihsan Ullah

34

}

The following program reads the records from a file. #include <stdio.h> void main(void ) { FILE *fp ;

struct emp { char name[40] ; int age ; float bs ; } ;

struct emp e ; fp = fopen ( " emp.dat ", "r" ) ; if ( fp == NULL )

{ puts ( "Cannot open file" ) ; exit(0 ) ; }

while ( fscanf ( fp, "%s %d %f", e.name, &e.age, &e.bs ) != EOF ) printf ( "\n%s %d %f", e.name, e.age, e.bs ) ; fclose ( fp ) ; }

Exercise 13: Enter data for 10 employees through using the program given earlier that writes the records into file. Then write a program that reads the same file and calculates the average basic salary and sum of all salaries.