Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
47 views

Structured Programming Language Lab Manual

This a manual on lab

Uploaded by

raverahat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

Structured Programming Language Lab Manual

This a manual on lab

Uploaded by

raverahat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Basic Outputs and Data Types

printf() - The printf() function is a standard library function in C used for outputting
formatted text to the console. It allows for the inclusion of various data types within the output string
through the use of format specifiers (we will learn later).
Example – 1:
#include <stdio.h> Hello, World!
int main() {
printf("Hello, World!\n");
return 0;
}
Here's a breakdown of the code:
1. #include <stdio.h>: This line includes the standard input-output library, which is
necessary for using the printf() function.
2. int main() { ... }: This is the main function where the program execution begins.

3. printf("Hello, World!\n");: This line uses the printf() function to print "Hello,
World!" to the console, followed by a newline character (\n).
4. return 0;: This statement returns 0 from the main() function, indicating that the program
has executed successfully.
Exercise:
i) Print your name.
ii) Print your name, department and ID using separate printf() function.
Escape Sequences: Escape sequences in C are used to represent special characters within string
literals and character constants. Each escape sequence begins with a backslash (\) followed by a
character or a combination of characters that represent the special character. Here are some commonly
used escape sequences in C:
1. \n - Newline: Moves the cursor to the next line.

2. \t - Horizontal Tab: Moves the cursor to the next tab stop.

3. \\ - Backslash: Inserts a backslash character.

4. \" - Double Quote: Inserts a double quote character.

5. \r - Carriage Return: Moves the cursor to the beginning of the line.

6. \b - Backspace: Moves the cursor back one position.

7. \v - Vertical Tab: Moves the cursor to the next vertical tab stop.

8. \? - Question Mark: Inserts a question mark.


Example – 2:
#include <stdio.h> Hello, World!
Tabbed Text
int main() { Backslash: \
printf("Hello, World!\n");
Double Quote: "
printf("Tabbed\tText\n");
printf("Backslash: \\\n"); Backspace: ABD
printf("Double Quote: \"\n"); Vertical Tab:
printf("Backspace: ABC\bD\n"); Text
printf("Vertical Tab:
\vText\n");

return 0;
}

Exercise:
i) Print your information in different line using escape sequences.
ii) Print the following pattern using escape sequences:
Name | Age | Blood Group
----------------------------------------
A | 21 | O+
----------------------------------------
B | 20 | B+
----------------------------------------
C | 21 | AB-
----------------------------------------

Basic Data Types:


Integer Types
• int(%d): A basic integer type. Size is typically 4 bytes.

• short int or short(%d): A shorter integer type. Size is typically 2 bytes.

• long int or long(%ld): A longer integer type. Size is typically 4 or 8 bytes,


depending on the system.
• long long int or long long(%lld): An extended integer type. Size is typically 8
bytes.
• unsigned int(%u): An unsigned integer (only positive values). Size is the same as int.

Floating-Point Types
• float(%f): A single-precision floating-point type. Size is typically 4 bytes.

• double(%lf): A double-precision floating-point type. Size is typically 8 bytes.

Character Type
• char(%c): A single-byte character type. Size is 1 byte. It can store a single character or a
small integer.
Void Type
• void: Represents the absence of a type. It is used for functions that do not return a value or
for generic pointers.
Example – 3:
#include <stdio.h> printf("int: %d\n", a); int: 10
printf("short int: %d\n", b);
int main() { printf("long int: %ld\n", c);
short int: 20
int a = 10; printf("long long int: long int: 30
short int b = 20; %lld\n",d); long long int: 40
long int c = 30; printf("unsigned int: %u\n", e); unsigned int: 50
long long int d = 40; printf("float: %f\n", f);
unsigned int e = 50; printf("double: %lf\n", g);
float: 1.230000
float f = 1.23; printf("char: %c\n", i); double: 4.560000
double g = 4.56; char: A
char i = 'A'; return 0;
}

sizeof() - The sizeof() operator in C is used to determine the size (in bytes) of a data type or a
variable.

• sizeof(type)
• sizeof(variable)

Exercise:
i) Display the size of basic data types occupied in memory.
ii) Initialize two variables with value and then perform arithmetic (+, -, *, /, %) operation.
Basic I/O and Math Functions
scanf(): scanf() is a function in the C programming language that is used for reading input from
standard input (keyboard by default). It belongs to the stdio.h (standard input-output header) library in
C.
1. Format Specifiers: scanf() uses format specifiers to determine the type of data that it is
reading. For example:
o %d is used for integers

o %f is used for floating-point numbers

o %c is used for characters

o %s is used for strings (a sequence of characters)

2. Reading Input: scanf() reads input from standard input (usually the keyboard) based on the
format specifiers provided. It stops reading when whitespace (space, tab, newline) is
encountered.
Example – 4:
#include <stdio.h> Enter an integer: 15
You entered: 15
int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
printf("You entered: %d\n",
num);
return 0;
}

Example – 5:
#include <stdio.h> Enter height in centimeters: 170
int main() {
double height_cm, height_inches,
Height in feet and inches: 5 feet 7.1
height_feet; inches

// Prompt the user to enter height in


centimeters
printf("Enter height in centimeters: ");
scanf("%lf", &height_cm);

// Convert centimeters to inches and feet


height_inches = height_cm / 2.54;
// 1 inch = 2.54 cm
height_feet = height_inches / 12.0;
// 1 foot = 12 inches

// Calculate remaining inches


height_inches = fmod(height_inches, 12.0);

// Display the converted height


printf("Height in feet and inches: %.0f
feet %.1f inches\n", height_feet,
height_inches);

return 0;
}
fmod(x,y): fmod() is a useful function in C for computing remainders involving floating-point
numbers.
sin(x): sin() function is used to calculate the sine of an angle, given in radians.

ceil(x): ceil() function is used to calculate the smallest integer value that is greater than or
equal to a given floating-point number x.
exp(x): exp() function is used to calculate the exponential value of a given number x.

fabs(x): fabs() function is used to calculate the absolute value of a floating-point number.

floor(x): floor() function is used to calculate the largest integer value less than or equal to a
given floating-point number x.

pow(x,y): pow() function is used to calculate the power of a number. It computes xy, where x is
the base and y is the exponent.
sqrt(x): sqrt() function is used to calculate the square root of a given non-negative number.
sqrt(x) returns the square root of x as a double.
Exercise:
i) Based on user input, perform basic arithmetic operation of two float numbers.
ii) Take 5 integer numbers from the user. Calculate the mean and the RMS of these numbers.
iii) Convert the followings:
a) Feet-inches to CM [Hint: 2.54 CM = 1 Inches, 12 Inches = 1 Feet]
b) KGs to LBs [Hint: 1KG = 2.20462 LB]
c) BDT to Dollar-BDT
d) Character to ASCII value.
e) Celsius to Fahrenheit.
f) Uppercase to Lowercase and vice-versa.
iv) Take two float numbers from user and find the value returns by the function mentioned in
above for those numbers.
v) Write a C program to swap/interchange values of two numbers using third variable.
vi) Write a C program to swap/interchange values of two numbers without using third
variable.
Operators and Conditional Statements
Operators are used to perform operations on variables and values.
There are 7 types of operators in C as mentioned below:

Arithmetic Operators
Relational Operators

Logical Operators
Bitwise Operators

Assignment Operators

Operator Description Example


Simple assignment operator. Assigns values from C = A + B will
= right side operands to left side operand assign the value
of A + B to C
Add AND assignment operator. It adds the right C += A is
+= operand to the left operand and assign the result equivalent to C =
to the left operand. C+A
Subtract AND assignment operator. It subtracts C -= A is
-= the right operand from the left operand and equivalent to C =
assigns the result to the left operand. C-A
Multiply AND assignment operator. It multiplies C *= A is
*= the right operand with the left operand and equivalent to C =
assigns the result to the left operand. C*A
Divide AND assignment operator. It divides the left C /= A is
/= operand with the right operand and assigns the equivalent to C =
result to the left operand. C/A
Modulus AND assignment operator. It takes C %= A is
%= modulus using two operands and assigns the equivalent to C =
result to the left operand. C%A
Left shift AND assignment operator. C <<= 2 is same
<<=
as C = C << 2
Right shift AND assignment operator. C >>= 2 is same
>>=
as C = C >> 2
Bitwise AND assignment operator. C &= 2 is same as
&=
C=C&2
Bitwise exclusive OR and assignment operator. C ^= 2 is same as
^=
C =C^2
Bitwise inclusive OR and assignment operator. C |= 2 is same as
|=
C =C|2

Special Operators

C has the following conditional statements:


• Use if to specify a block of code to be executed, if a specified condition is true

if (condition) {
// block of code to be executed if the condition is true
}

Example – 6:
int x = 20; x is greater than y
int y = 18;
if (x > y) {
printf("x is greater than
y");
}

• Use else to specify a block of code to be executed, if the same condition is false

if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example – 7:
int time = 20; Good evening.
if (time < 18) {
printf("Good day.");
} else {
printf("Good evening.");
}

• Use else if to specify a new condition to test, if the first condition is false

if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and
condition2 is true
} else {
// block of code to be executed if the condition1 is false and
condition2 is false
}

Example – 8:
int myNum = -15; Negative number.

if (myNum > 0) {
printf("Positive number.");
} else if (myNum < 0) {
printf("Negative number.");
} else {
printf("Zero.");
}

• Use switch to specify many alternative blocks of code to be executed

switch (expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This is how it works:
• The switch expression is evaluated once

• The value of the expression is compared with the values of each case

• If there is a match, the associated block of code is executed


• The break statement breaks out of the switch block and stops the execution

• The default statement is optional, and specifies some code to run if there is no case match

Example – 9:
int day = 4; Wednesday
switch (day) {
case 1:
printf("Sunday");
break;
case 2:
printf("Monday");
break;
case 3:
printf("Tuesday");
break;
case 4:
printf("Wednesday");
break;
case 5:
printf("Thursday");
break;
case 6:
printf("Friday");
break;
case 7:
printf("Saturday");
break;
default:
printf("Invalid day number");
}

Exercise:
i) Write a program (WAP) to input a number and check whether it is even or odd.
ii) WAP to input a number. If the number is even, print its square otherwise print its cube
iii) WAP to input marks of a subject and calculate the grade according to the following
conditions:
Percentage Grade
>80 A+
75-79 A
70-74 A-
65-69 B+
60-64 B
55-59 B-
50-54 C+
45-49 C
40-44 D
<40 F
iv) WAP to check that a given year is a leap year or not.
v) WAP to input a character and check that it’s a vowel or a consonant.
vi) WAP to input a character and check that it’s a small letter, capital letter, a digit or a special
symbol
vii) WAP to find out the largest/smallest among three numbers.
viii) WAP to input two numbers n1, n2 and an operator and calculate the result according
to the following conditions using switch statement:
Operator Result
+ n1 + n2
- n1 - n2
* n1 * n2
/ n1 / n2
% n1 % n2

ix) WAP to perform bitwise operation on variable(s).


Control Statements/ Loop
There are mainly two types of loops in C Programming:
1. Entry Controlled loops: In Entry controlled loops the test condition is checked before
entering the main body of the loop. For Loop and While Loop is Entry-controlled loops.
2. Exit Controlled loops: In Exit controlled loops the test condition is evaluated at the end of the
loop body. The loop body will execute at least once, irrespective of whether the condition is
true or false. do-while Loop is Exit Controlled loop.

Loop Type Description

First Initializes, then condition check, then executes the body and at last, the update
for loop
is done.

First Initializes, then condition checks, and then executes the body, and updating can
while loop
be inside the body.

do-while
do-while first executes the body and then the condition check is done.
loop
For Loop: When you know exactly how many times you want to loop through a block of code, use
the for loop instead of a while loop. More suitable for iterating over a collection of items or when the
number of iterations is fixed.
Syntax
for (expression 1; expression 2; expression 3) {
// code block to be executed
}
///////////////////////////////////////////////////////////////////////
///
for(initialization; condition; incr/decr){
//code to be executed
}
expression 1 is executed (one time) before the execution of the code block.
expression 2 defines the condition for executing the code block.
expression 3 is executed (every time) after the code block has been executed.
Example – 10:
#include <stdio.h> 20
int main() 25
{ 30
int i = 0;
35
for (i = 20; i <= 40; i=i+5) 40
{
printf( "%d\n",i);
}
return 0;
}

Example – 11:
#include <stdio.h> Check yourself
int main (){
for( ; ; ){
printf("Executing...\n");
}
return 0;
}

While Loop: The while loop loops through a block of code as long as a specified condition is true.
While loop is better when the loop needs to run until a specific condition changes.
Syntax
initialization_expression;
while (test_expression){
update_expression;}
Example – 12:
#include <stdio.h> 7
int main() 7*1=7
{ 7 * 2 = 14
int n, i=1;
scanf("%d", &n);
7 * 3 = 21
while(i <= 10) 7 * 4 = 28
{ 7 * 5 = 35
printf( "%d * %d = %d\n",n,i,n*i); 7 * 6 = 42
i++; 7 * 7 = 49
} 7 * 8 = 56
return 0; 7 * 9 = 63
} 7 * 10 = 70

Do/While Loop: The do/while loop is a variant of the while loop. This loop will execute the code block
once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
Syntax
initialization_expression;
do
{
update_expression;
} while (test_expression);

Example – 13:
#include <stdio.h> 10
int main() {
int i = 10;
do {
printf("%d\n", i);
i++;
}
while (i < 9);
return 0;
}

Exercise:

i) Write a program to display –


a) Sum of first ten numbers.
b) Sum of first ten odd numbers.
c) Sum of first ten even numbers.
ii) Write a program to calculate the sum of following series –
a) 1 + 2 + 4 + 8 + 16 + ... + 2n
b) 1 – 2 + 4 - 8 + 16 - … ± 2n
c) 12 + 22 + 32 + … + n2
d) 1 + 2 + 4 + 7 + 11 + … + nth term
iii) Write a program to find out factorial value of given integer number.
iv) Write a program to power function ( an , where a and n are user input).
v) Write a program to find out GCD an LCM of two integer numbers.
vi) Write a program to find out factors of an integer number.
vii) Write a program to display the Fibonacci series up to nth term.
viii) Write a program to input an integer number and –
a) Count the number of digits in it.
b) Sum of digits in it.
c) Reverse the number.
d) Check whether it is palindrome or not.
ix) Write a program to check whether a number is prime or not.
x) Write a program to display the following n line triangle where n is a user input. For n = 4,
output will be:

* **** *
** *** ***
*** ** *****
**** * *******

* **** *******
** *** *****
*** ** ***
**** * *

You might also like