Docsity

C Programming Lab: Finding Sum of a Series of Integers, Exercises of Law

Partial preview of the text

Download C Programming Lab: Finding Sum of a Series of Integers and more Exercises Law in PDF only on Docsity!

Ahsanullah University of Science and Technology (AUST)

Department of Computer Science and Engineering

LABORATORY MANUAL

Course No.: CSE 1102

Course Title: Elementary Structured Programming Lab

For the students of 1

st

Year, 1

st

semester of

B.Sc. in Computer Science and Engineering program

TABLE OF CONTENTS

COURSE OUTCOMES................................................................................................... 1

PREFFERED TOOLS ...................................................................................................... 1

TEXT/REFERENCE BOOK ........................................................................................... 1

ADMINISTRATIVE POLICY OF THE LABORATORY .......................................... 1

LIST OF SESSIONS .........................................................................................................

SESSION 1: ........................................................................................................................ 2

Getting acquainted with major components and general form of a C Program.

SESSION 2: ........................................................................................................................ 5

Introducing Conditional Statements.

SESSION 3: ........................................................................................................................ 8

Introduction to C Loops

SESSION 4: ...................................................................................................................... 10

Introducing Loops (while loop and do-while loop).

SESSION 5: ...................................................................................................................... 13

Loop continued (nested loop).

SESSION 6: ...................................................................................................................... 15

Introducing Multiple Function Program.

SESSION 7: ...................................................................................................................... 17

Recursion and Recursive Function.

SESSION 8: ...................................................................................................................... 19

Introducing One Dimensional Array.

SESSION 9: ...................................................................................................................... 21

Introducing Two-Dimensional Array and Nested Loop.

SESSION 10: .................................................................................................................... 23

Introducing Array of Characters and String.

SESSION 11: .................................................................................................................... 25

Introducing advanced topics (Structure & Array of Structures)

SESSION 12: .................................................................................................................... 27

Introducing advanced topics (Pointer and Function)

SESSION 13: .................................................................................................................... 29

Introducing advanced topics (Pointer and File)

MID TERM EXAMINATION....................................................................................... 32

FINAL TERM EXAMINATION .................................................................................. 32

Session 1

1. OBJECTIVES:

i. Getting acquainted with major components of a C program ii. Typing and Executing a C Program Mark the elements of a function : int^1 main^2 (void^3 ) { ……………..^4 …………………; ……………….; . . . ……………^5 } 1 – Return type 2 – Function name 3 – Argument / parameter list 4 – A statement 5 – Special statement defining function output/ return Function head Body of the function as a ‘block’ of codes or sequence of statements within ‘{‘ and ‘}’. /* Instruction : Observe, Type, Save and Run / / A Program to find the sum of a series of integers / #include <stdio.h> int main() { int term1, interval, numberOfTerms; int sum, lastTerm; printf("Enter the first term:"); scanf("%d", &term1); printf("Enter the interval:"); scanf("%d", &interval); printf("Enter the number of terms:"); scanf("%d", &numberOfTerms); lastTerm = term1 + (numberOfTerms - 1) interval; sum = ((term1 + lastTerm) * numberOfTerms) /2; printf("The sum is %d.", sum); return 0; } Comment Header File: stdio.h Main function headline Function body begins Memory reservation or Variable declaration Output statement Input statement Calculating and assigning (remembering) values Output statement Function output / Return Statement Function body ends

2. General form of C Programs[Header Files and Library Functions]:

****** In C programs the main function return type is int and therefore it should return an integer value. The return value of the main function is considered the "Exit Status" of the application. The 0 exit code is a widely accepted convention for 'OK the program execution was successfull'. return 0 means no error.

3. Operators in C Programming:

a. Binary operator: + , - , / , * , % b. Unary operator: + ,- c. Relational operator: > , > = ,< , < = , = = ,! = [true will return 1 and false will return 0] d. Logical operator: && (AND) , || (OR) ,! (NOT) [true will return a nonzero value and false will return 0] e. Bitwise operator: & (AND), | (OR), ^ (XOR) , << , >> , ~ f. Increment and decrement operator: + + , - - g. Assignment operator: = , + = , * = , - = , / = , % = , & = , | = , ^ = , << = , >> = /* Instruction : Observe, Type, Compile and Run / / A simple multiple function program / #include <stdio.h> #include <math.h> int main() { float n1, n2, n3; / Variable declaration / double n4, n5; printf("\nEnter two decimal fractions:"); scanf("%f %f", &n1, &n2); n3 = sum_xy(n1, n2); / Function call with Parameters */ n4 = prdct_xy(n1, n2); n5 = sqrt(n4); printf("\nThe 1st function returns %f.", n3); printf("\nThe 2nd function returns %f.", n4); printf("\nThe square root of %f is %f.\n", n4, n5); return 0; } Inclusion of Header files main function

Session 2

1. OBJECTIVES:

i. Conditional Statements ii. Relational and Logical Operators Expression: An expression is the combination of functions, operators, commas, variables, identifiers etc. Ex: x = 0 , x + +. Statement: An expression as x = 0 , x + + or printf(...) becomes a statement when it is followed by a semicolon(;) as in x + + ; x = 0 ; printf(...) ; Braces { and }are syntactically equivalent to a single statement. if ... else: if ... else statement is used to express decisions. Formally the syntax is: if (expression) statement1; else statement2; Here the else part is optional. The expression inside if ... else statement expects a value. If the value is nonzero then it is true. If the value is 0 then it is false. /* Instruction : Observe, Type, Compile and Run / / A program to find odd or even number */ #include<stdio.h> int main() { int number; printf("Enter a number: "); scanf("%d", &number); if(number%2==0) printf(“Number is Even”); else printf(“Number is Even”); return 0; }

else ... if: if(expression 1) statement 1 else if(expression 2) statement 2 else if(expression 3) statement 3 . . . else statement n else ... if checks its expression sequentially. When it found one expression is true then it will not check other expressions within that else ... if block.

2. LET’S WRITE A PROGRAM TOGETHER:

Problem: Write a program to input a three integer number and print them ascending order. [if a user input 9,2,8 then the output of the program will be 2 8 9] /* Instruction : Observe, Type, Compile and Run / / A program to find income tax of an employee according to salary */ #include<stdio.h> int main() { int salary; float tax; printf("Enter your monthly salary: "); scanf("%d", &salary); if(salary>=9000) tax = salary * 0.2; else if(salary>=7500 && salary<9000) tax = salary * 0.1; else if(salary>=6500 && salary<7500) tax = salary * 0.05; else tax = 0; printf("Calculated tax = %.2f\n", tax); return 0; }

Session 3

1. OBJECTIVE:

i. Introduction to Loops (for loop) Loop: Loops are used in C for repeating some portion of the program either a specified number of times or until a particular condition is being satisfied. There are three methods in C for repeating a part of program. i) Using a for statement ii) Using a while statement iii) Using a do ... while statement for Loop: Syntax of for loop is given below: Expression1, expression2 and expression3 are normally used for initialization, loop condition and loop counter increment respectively. Expression2 returns a value which may true or false. Any non-zero value means true and zero means false in this case. All three expressions (phase) are optional in for loop. /* Instruction : Observe, Type, Compile and Run / / A program to demonstrate for loop */ #include<stdio.h> int main() { int i; for(i=1;i<6;i++) { printf("\n%d ",i); i=i+1; } for(i=4;i>=1;i=i- 1 ) { printf("%d ",i) } return 0; }

2. LET’S WRITE A PROGRAM TOGETHER:

Problem: Write a program to find the factorial of a given integer.

3. EXERCISES:

  1. Write a program to calculate and display the sum and average of first n odd natural numbers.
  2. Write a program to find the sum of the following series up to n terms. Assume entry of a fractional number x. i. x^2 /2! + x^3 /3! – x^4 /4! + … ii. 5 – 11 + 17 - ... (up to 75 th term ) iii. 1 + ( 1 + 2 ) + ( 1 + 2 + 3 ) + ... + ( 1 + 2 + 3 + ... + n )
  3. Write a program to determine the GCD (greatest common divisor) and LCM (least common multiple) of 3 numbers.
  4. Write a program to determine all prime numbers within the range [a ...b] where a & b are input through keyboard.

2. LET’S WRITE A PROGRAM TOGETHER:

Problem: Write a program to check whether a given integer is a prime number or not.

3. EXERCISES:

  1. Write a program to input an integer through the keyboard until the user chooses to quit upon the appearance of options. Every time a number is entered. The program should display whether it is greater than, less than or equal to the previous integer. [Assume initial integer value is 15] Sample Input and Output Enter an integer: 23 It is greater than 15. Do you want to continue (y/n)? y Enter an integer: 17 It is less than 23. Do you want to continue (y/n)? y Enter an integer: 17 It is equal to 17. Do you want to continue (y/n)? n
  2. Write a program to emulate the pow library function where the parameters will be user input. Sample Input Sample Output /* Instruction: Observe / / A program to demonstrate while loop and do-while loop. / /using do loop*/ #include <stdio.h> int main() { int lc=1, check=1, num = 909, guess; lc=1, check=1; do { printf("\nGuess the number:"); scanf("%d", &guess); if(num==guess) check=0; lc++; } while(lc<=5 && check); if(check==0) printf("\nCongrats! You have guessed in %d tries!\n", --lc); else printf("\nSorry!You failed in all 5 tries.\n"); return 0; }

Enter Base: 3 Enter Power: 5 Result: 243

4. ASSIGNMENT 2:

  1. Write a program to find, first using a ‘while’ loop and then a ‘for’ loop, the sum of first n terms (n  1) of the series 2x3, 3x4, 4x5, …, (n+1)x(n+2). You need to verify that you get the same result in both the cases.
  2. Write a program to check whether a given integer is palindrome or not. [ 121 is palindrome but 123 is not ]
  3. Write a program to print the Fibonacci series up to n terms where n is user input. [Fibonacci Series: 0, 1, 1, 2, 3, 5, … ]
  4. Write a program to print out all Armstrong numbers between 1 and 10000. [Example, 153 = (111) + (555) + (333)].

3. EXERCISES:

  1. Write a program to print all the prime numbers between two given integers using ‘for’ and ‘while’ as outer and inner loop respectively.
  2. Write separate programs to print the following patterns taking number of rows as user input. (a) * * * * * * * * * * * * * * * (b) a a ab bb abc ccc abcd dddd abcde eeeee

4. ASSIGNMENT 3:

1. Write a program to determine all Pythagorean triplets without duplication and with

minimum possible computational cost in the range 1 to 1000. (A Pythagorean triplet is a set of three integers i, j, k such that i^2 + j^2 = k^2. Use ‘break’ and/or ‘continue’ statements, where possible.)

2. Write a C program to remove white spaces from a given string.

3. Write a program that will read an integer between 20 and 99 from user and print it out

in words. You have to use switch statement and repeat the whole process ‘n’ [user input] times. Note that, you can use no more than 2 switch statements with 10 cases per switch at most. Sample Input Sample Output Enter an integer [20-99]: 38 In words: Thirty Eight Enter an integer [20-99]: 23 In words: Twenty Three

4. Construct the following table. Here n is input from the user.

1 2 3 ... n

2 4 6 ... 2n

3 6 9 ... 3n

n 2n 3n ... nn

Session 6

1. OBJECTIVES:

i. Introduction to Multiple Function Program /Instruction: Observe/ /*A program to demonstrate simple use of ‘global’ & ‘local’ variable and function */ #include<stdio.h> char char_f1(); void odd_even(int); int count; int main() { int num1; char ch1; count = 1; ch1 = char_f1(); num1 = ch1; printf("\nYou have entered %c,", ch1); printf(" the code of which is %d.\n", num1); odd_even(num1); printf("\nValue of global 'count': %d", count); return 0; } char char_f1() { char ch2; int count; printf("\nEnter a character:"); scanf("%c", &ch2); count = ch2; printf("\nValue of local 'count' in char_f1(): %d", count); return ch2; } void odd_even(int n) { if (n % 2 == 0) printf("\nIt is even.\n"); else printf("\nIt is odd.\n"); ++count; }

Session 7

1. OBJECTIVE:

i. Introduction to Recursion and Recursive Function A function is called recursive if a statement within the body of a function calls the same function. Sometimes called circular definition, recursion is thus the process of defining something in terms of itself.

2. LET’S WRITE A PROGRAM TOGETHER:

Problem: Write a program to find the sum of a series of positive even numbers using recursion.

3. EXERCISES:

  1. Write a program to find the sum of a series of positive odd numbers using recursion.
  2. The series 0, 1, 1, 2, 3, 5, 8, 13, … is called the Fibonacci series. Here, termn=termn- 1 + termn- 2 , for n>1, term 0 = 0, term 1 = 1. Write a program that finds the sum of first n terms of the series using recursion. /* Instruction: Observe / / A program to demonstrate simple use recursive functions. / #include <stdio.h> int fctrl(int x); int main() { int i, n1, n2, f1; printf("\nEnter a positive integer:"); scanf("%d", &n1); f1=fctrl(n1); / Factorial using recursion */ printf("\nThe factorial of %d is %d.\n", n1, f1); return 0; } int fctrl(int n) { if (n<2) return 1; else return n * fctrl(n-1); }
  1. Convert a decimal number into correspondent binary number using recursion where decimal number is input from user.
  2. A positive integer is entered through the keyboard, write a program to obtain the prime factors of the number. Modify the function suitability to obtain the prime factors recursively.

4. ASSIGNMENT 4:

  1. Write a multifunction program to print the following patterns where number of rows is user input and must be read in main function. There should be separate function for each of the following patterns and note that, you cannot pass any data through parameters to those functions. (a) 7654321 54321 321 1 (b) * * * * * * * * *


  1. The total number of moves of disks required to solve the Tower of Hanoi problem with n disks is expressed in the following equation: Hn = 2Hn- 1 +1, for n>1 and H 1 = 1. Write a program that finds the total number of moves for any given number n of disks using global variables and recursion. Write two different functions that are called from the main function.