F.Y. Cloud Computing Workbook
F.Y. Cloud Computing Workbook
Name : _____________________________
Year : _____________________________
Batch : _____________________________
Roll No : _____________________________
Department: __________________________
Teacher : __________________________
Subjects:
1. Laboratory Course on Database Managemnet Systems
2. Laboratory Course on C Programming
INTRODUCTION
The Practical Workbook for “Programming Languages” and Data base Management
system introduces the basic as well as few advance concepts of programming using C
language. C encompasses the characteristics of both the high level languages; which give a
better programming efficiency and faster program development; and the low level
languages; which have a better machine efficiency.
Each lab session begins with a brief theory of the topic. Many details have not been
incorporated as the same is to be covered in Theory classes. The Exercise section follows
this section.
The Workbook has been arranged as ten labs starting with a practical on the Introduction to
programming environment and fundamentals of programming language.
The slots allotted to each Practical Assignment may vary.
CONTENTS
Lab Course I
Data Structure
Sr. Assignment Name Marks Teachers
No (Out of 5) Sign
1 Familiarization with Programming -no
Environment using Turbo C and evaluation
Fundamentals of Programming Language
Assignment on use of data types, simple
operators (expressions)
Debugging and Single-Stepping of Programs
2 Assignment on decision making statements
(if and if-else, nested Structures
3 Assignment on decision making statements
(switch case)
4 Assignment on use of loops
5 Assignment on nested loop and study of
Jump Statements
6 Assignment on menu driven programs.
7 Assignment on Functions (user defined)
8 Assignment on Arrays 1-D
9 Assignment on Arrays 2-D
10 Assignment on Arrays and functions
Total (Out of 45 )
Total (Out of 15)
OBJECTIVE:
THEORY
To do so from the command prompt go in the specific directory and type ‘tc’. This
makes you enter the IDE interface, which initially displays only a menu bar at the top of
the screen and a status line below will appear. The menu bar displays the menu names
and the status line tells what various function keys will do.
Using Menus
If the menu bar is inactive, it may be invoked by pressing the [F10] function key. To
select different menu, move the highlight left or right with cursor (arrow) keys. You can
also revoke the selection by pressing the key combination for the specific menu.
Writing a Program
When the Edit window is active, the program may be typed. Use the certain key
combinations to perform specific edit functions.
Saving a Program
To save the program, select save command from the file menu. This function can also
be performed by pressing the [F2] button. A dialog box will appear asking for the path
and name of the file. Provide an appropriate and unique file name. You can save the
program after compiling too but saving it before compilation is more appropriate
Project/Make
Before compiling and linking a file, a part of the IDE called Project/Make checks the
time and date on the file you are going to compile.
Executing a Program
If the program is compiled and linked without errors, the program is executed by
selecting Run from the Run Menu or by pressing the [Ctrl+F9] key combination.
Correcting Errors
If the compiler recognizes some error, it will let you know through the Compiler
window. You’ll see that the number of errors is not listed as 0, and the word “Error”
appears instead of the word “Success” at the bottom of the window. The errors are to be
removed by returning to the edit window. Usually these errors are a result of a typing
mistake. The compiler will
not only tell you what you did wrong; they’ll point you to the exact place in your code
where you made the mistake.
Exiting IDE
An Edit window may be closed in a number of different ways. You can click on the
small square in the upper left corner, you can select close from the window menu, or
you can press the [Alt][F3] combination. To exit from the IDE select Exit from the File
menu or press [Alt][X] combination.
A C program source code can be written in any text editor; however the file should be
saved with .c extension. Lets write the First C program.
PREREQUISITE:
•If you want to create, compile and execute c programs by your own, you have to install c
compiler in your machine. Then, you can start to execute your own c programs in your
machine.
• You can refer below link for how to install c compiler and compile and execute c programs
in your machine.
• Once c compiler is installed in your machine, you can create, compile and execute c
programs as shown in below link.
• If you don’t want to install c/c++ compilers in your machine, you can refer online
compilers which will compile and execute c/c++ and many other programming languages
online and display outputs on the screen. Please search for online c/c++ compilers in google
for more details.
/*
Documentation section
C programming basics & structure of C programs
Author: New Author
Date :01/01/2018
*/
Header files that are required to execute a C program are included in this
Link Section section
Definition
Section In this section, variables are defined and values are set to these variables.
Global
declaration Global variables are defined in this section. When a variable is to be used
section throughout the program, can be defined in this section.
Function
prototype
declaration Function prototype gives many information about a function like return
section type, parameter names used inside the function.
Every C program is started from main function and this function contains
Main function two major sections called declaration section and executable section.
User defined User can define their own functions in this section which perform particular
function section task as per the user requirement.
A SIMPLE C PROGRAM:
Below C program is a very simple and basic program in C programming language. This C
program displays “Hello World!” in the output window. And, all syntax and commands in C
programming are case sensitive. Also, each statement should be ended with semicolon (;) which
is a statement terminator.
1 #include <stdio.h>
2 int main()
3{
4 /* Our first simple C basic program */
5 printf("Hello World! ");
6 getch();
7 return 0;
8}
OUTPUT:
Hello World!
n C, we have 32 keywords, which have their predefined meaning and cannot be used as a
variable name. These words are also known as “reserved words”. It is good practice to avoid sing
these keywords as variable name. These are –
Basics usage of these keywords –
if, else, switch, case, default – Used for decision control programming structure.
int, float, char, double, long – These are the data types and used during variable declaration.
continue – It is generally used with for, while and dowhile loops, when compiler encounters this
statement it performs the next iteration of the loop, skipping rest of the statements of current
iteration.
enum – Set of constants.
struct, typedef – Both of these keywords used in structures (Grouping of data types in a single
record).
union – It is a collection of variables, which shares the same memory location and memory
storage.
Operators
There are various types of operators that may be placed in following categories:
I. Arithmetic Operators
II. Increment and Decrement Operators
III. Assignment Operators
IV. Relational Operators
V. Logical Operators
VI. Conditional Operators
VII. Bitwise Operators
VIII . Special Operators
I. Arithmetic Operators
* Multiplication
/ division
Increment operators are used to increase the value of the variable by one and decrement
operators are used to decrease the value of the variable by one in C programs.
Syntax:
Increment operator: ++var_name; (or) var_name++;
Decrement operator: – -var_name; (or) var_name – -;
Example:
Increment operator : ++ i ; i ++ ;
Decrement operator : – – i ; i – – ;
#include <stdio.h>
int main()
{
int i=0;
while(++i < 5 )
{
printf("%d ",i);
}
return 0;
}
Output:
1234
Step 1 : In above program, value of “i” is incremented from 0 to 1 using pre-increment
operator.
Step 2 : This incremented value “1” is compared with 5 in while expression.
Step 3 : Then, this incremented value “1” is assigned to the variable “i”.
Above 3 steps are continued until while expression becomes false and output is
displayed as “1 2 3 4”.
#include <stdio.h>
int main()
{
int i=0;
while(i++ < 5 )
{
printf("%d ",i);
}
return 0;
}
Output:
12345
Step 1 : In this program, value of i “0” is compared with 5 in while expression.
Step 2 : Then, value of “i” is incremented from 0 to 1 using post-increment operator.
Step 3 : Then, this incremented value “1” is assigned to the variable “i”.
Above 3 steps are continued until while expression becomes false and output is
displayed as “1 2 3 4 5”.
Output:
9876
Step 1 : In above program, value of “i” is decremented from 10 to 9 using pre-
decrement operator.
Step 2 : This decremented value “9” is compared with 5 in while expression.
Step 3 : Then, this decremented value “9” is assigned to the variable “i”.
Above 3 steps are continued until while expression becomes false and output is
displayed as “9 8 7 6”.
Output:
98765
Step 1 : In this program, value of i “10” is compared with 5 in while expression.
Step 2 : Then, value of “i” is decremented from 10 to 9 using post-decrement operator.
Step 3 : Then, this decremented value “9” is assigned to the variable “i”.
Above 3 steps are continued until while expression becomes false and output is
displayed as “9 8 7 6 5”.
Operators
Example/Description
= sum = 10;
10 is assigned to variable sum
+= sum += 10;
This is same as sum = sum + 10
-= sum -= 10;
This is same as sum = sum – 10
*= sum *= 10;
This is same as sum = sum * 10
sum /= 10;
/= This is same as sum = sum / 10
%= sum %= 10;
This is same as sum = sum % 10
&= sum&=10;
This is same as sum = sum & 10
sum ^= 10;
^= This is same as sum = sum ^ 10
Operators
Example/Description
>
x > y (x is greater than y)
<=
x <= y (x is less than or equal to
y)
== x == y (x is equal to y)
!= x != y (x is not equal to y)
#include <stdio.h>
int main()
{
int m=40,n=20;
if (m == n)
{
printf("m and n are equal");
}
else
{
printf("m and n are not equal");
}
}
Output:
m and n are not equal
V. Logical Operators
These operators are used to perform logical operations on the given expressions.
There are 3 logical operators in C language. They are, logical AND (&&), logical OR
(||) and logical NOT (!).
Operators Example/Description
&& (logical AND) (x>5)&&(y<5)
It returns true when both conditions are
true
|| (logical OR) (x>=10)||(y>=10)
It returns true when at-least one of the
condition is true
! (logical NOT) !((x>5)&&(y<5))
It reverses the state of the operand
“((x>5) && (y<5))”
If “((x>5) && (y<5))” is true, logical
NOT operator makes it false
VI. Conditional Operators
CONDITIONAL OR TERNARY OPERATORS IN C:
Conditional operators return one value if condition is true and returns another value is
condition is false.
This operator is also called as ternary operator.
Syntax : (Condition? true_value: false_value);
Example : (A > 100 ? 0 : 1);
In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal
to if else conditional statement
#include <stdio.h>
int main()
{
int x=1, y ;
y = ( x ==1 ? 2 : 0 ) ;
printf("x value is %d\n", x);
printf("y value is %d", y);
}
Output:
x value is 1
y value is 2
TRUTH TABLE FOR BIT WISE OPERATION & BIT WISE OPERATORS:
Note:
Bit wise NOT : Value of 40 in binary is 00000000000000000000000000000000
00000000000000000010100000000000. So, all 0’s are converted into 1’s in bit wise NOT
operation.
Bit wise left shift and right shift : In left shift operation “x << 1 “, 1 means that the bits will be
left shifted by one place. If we use it as “x << 2 “, then, it means that the bits will be left shifted
by 2 places.
#include <stdio.h>
int main()
{
int m = 40,n = 80,AND_opr,OR_opr,XOR_opr,NOT_opr ;
AND_opr = (m&n);
OR_opr = (m|n);
NOT_opr = (~m);
XOR_opr = (m^n);
printf("AND_opr value = %d\n",AND_opr );
printf("OR_opr value = %d\n",OR_opr );
printf("NOT_opr value = %d\n",NOT_opr );
printf("XOR_opr value = %d\n",XOR_opr );
printf("left_shift value = %d\n", m << 1);
printf("right_shift value = %d\n", m >> 1);
}
Output:
AND_opr value = 0
OR_opr value = 120
NOT_opr value = -41
XOR_opr value = 120
left_shift value = 80
right_shift value = 20
VIII . Special Operators
Below are some of the special operators that the C programming language offers.
Operators Description
These identifiers actually have upto 6 parts as shown in the table below. They MUST be used in
the order shown.
% Flags Minimum Period Precision.
field width Maximum Argument
field width type
Format Specifiers
Format Specifiers tell the printf statement where to put the text and how to display the text.
The various format specifiers are:
char
%c Character
unsigned char
short
unsigned short
%d Signed Integer
int
long
float
%e or %E Scientific notation of float values
double
short
unsigned short
%i Signed Integer
int
long
unsigned int
%lu Unsigned integer
unsigned long
short
unsigned short
%o Octal representation of Integer. int
unsigned int
long
%s String char *
unsigned int
%u Unsigned Integer
unsigned long
short
unsigned short
Hexadecimal representation of Unsigned
%x or %X int
Integer
unsigned int
long
%n Prints nothing
%% Prints % character
Flags
The format identifers can be altered from their default function by applying the following flags:
- Left justify.
0 Field is padded with 0's instead of blanks.
+ Sign of number always O/P.
blank Positive values begin with a blank.
# Various uses:
%#o (Octal) 0 prefix inserted.
%#x (Hex) 0x prefix added to non-zero values.
%#X (Hex) 0X prefix added to non-zero values.
%#e Always show the decimal point.
%#E Always show the decimal point.
%#f Always show the decimal point.
%#g Always show the decimal point trailing
zeros not removed.
%#G Always show the decimal point trailing
zeros not removed.
They are used with % to limit precision in floating point number. The number showing
limit follows the radix point.
ach number is printed using just the number of columns required. Since this varies from
one number to the next, they do not line up. If we want to, we could get the numbers
lined up using a field width of 5, say. The statements
printf("%5d\n", a);
printf("%5d\n", b);
printf("%5d\n", c);
Escape Sequences
Escape Sequence causes the program to escape from the normal interpretation of a
string, so that the next character is recognized as having a special meaning. The back
slash “\” character is called the Escape Character”. The escape sequence includes the
following:
\n => new line
\b => back space
\r => carriage return
double
\” => quotations
\\ => back slash etc.
3
Getting Input From the User
The input from the user can be taken by the following techniques: scanf( ), getch( ),
getche( ), getchar( ) etc.
Examples
1. Implementing a Simple C Program
#include<conio.h>
#include<stdio.h>
void main(void)
{
clrscr();
printf(“\n Hello World”);
getch();
}
#include<conio.h>
#include<stdio.h>
void main(void)
{
clrscr();
int num1,num2,sum,product;
printf(“\tThe program takes two numbers as input and prints their
sum and product”);
printf(“\n Enter first number:”);
scanf(“%d”,&num1);
printf(“\n Enter second number:”);
scanf(“%d”,&num2);
sum=num1+num2;
product=num1*num2;
printf(“\n%d+%d=%d”,num1,num2,sum);
printf(“\n%d*%d=%d”,num1,num2,product);
getch();
}
OBJECTIVE
THEORY
One of the most innovative and useful features of Turbo C++ is the integration of
debugging facilities into the IDE.
Even if your program compiles perfectly, it still may not work. Such errors that cause
the program to give incorrect results are called Logical Errors. The first thing that
should be done is to review the listing carefully. Often, the mistake will be obvious. But,
if it is not, you’ll need the assistance of the Turbo C Debugger.
Our intention in this program is that when number is between 0 and 100, answer will
be 1, when the number is 100 or greater, answer will be 0, and when number is less
than 0, answer will retain its initialized value of –1. When we run this program with a
test value of -50 for number, we find that answer is set to 0 at the end of the program,
instead of staying –1.
We can understand where the problem is if we single step through the program. To do
this, simply press the [F7] key. The first line of the program will be highlighted. This
highlighted line is called the run bar. Press [F7] again. The run bar will move to the
next program line. The run bar appears on the line about to be executed. You can
execute each line of the program in turn by pressing [F7]. Eventually you’ll reach the
first if statement:
if (num < 100 )
7
This statement is true (since number is –50); so, as we would expect the run bar moves
to the second if statement:
This is false. Because there’s no else matched with the second if, we would expect the
run bar to the printf( ) statement. But it doesn’t! It goes to the line
answer = 0;
Now that we see where the program actually goes, the source of the bug should become
clear. The else goes with the last if, not the first if as the indenting would lead us to
believe. So, the else is executed when the second if statement is false, which leads to
erroneous results. We need to put braces around the second if, or rewrite the program in
some other way.
Watches
Single stepping is usually used with other features of the debugger. The most useful of
these is the watch (or watch expression). This lets you see how the value of variable
changes as the program runs. To add a watch expression, press [Ctrl+F7] and type the
expression.
Breakpoints
It often happens that you’ve debugged part of your program, but must deal with a bug in
another section, and you don’t want to single-step through all the statements in the first
part to get to the section with the bug. Or you may have a loop with many iterations that
would be tedious to step through. The way to do this is with a breakpoint. A breakpoint
marks a statement where the program will stop. If you start the program with [Ctrl][F9],
it will execute all the statements up to the breakpoint, then stop. You can now examine
the state of the variables at that point using the watch window.
Installing breakpoints
To set a breakpoint, first position the cursor on the appropriate line. Then select Toggle
Breakpoint from the Debug menu (or press [Ctrl][F8]). The line with the breakpoint will
be highlighted. You can install as many breakpoints as you want. This is useful if the
program can take several different paths, depending on the result of if statements or
other branching constructs.
Removing Breakpoints
You can remove a single breakpoint by positioning the cursor on the line with the
breakpoint and selecting Toggle breakpoint from the Debug menu or pressing the [Ctrl]
[F8] combination (just as you did to install the breakpoint). The breakpoint highlight
will vanish.
You can all set Conditional Breakpoints that would break at the specified value only.
Assignments:
1. Type the following program in C Editor and execute it. Mention the Error (if any).
void main(void)
{
printf(“This is my first program in C”);
}
__________________________________________________________________________
_
__________________________________________________________________________
_
__________________________________________________________________________
_
2. Add the following line at the beginning of the above program. Recompile the
program. What is the output?
#include<stdio.h>
__________________________________________________________________________
_
__________________________________________________________________________
_
3. Make the following changes to the program. Mention the Errors observed, in
your own words:
i.Write Void instead of void.
__________________________________________________________________________
_
__________________________________________________________________________
_
__________________________________________________________________________
_
__________________________________________________________________________
_
__________________________________________________________________________
_
4. Write a program to calculate the Area (A= π r2) and circumference of a circle
(C=2πr), where r = radius is taken as input and π is declared as a constant.
Display the result to 4 decimal places.
SET A
SET B
1. WAP to swap two integers –
i) Using temporary variable
ii) Without Using temporary variable
a) Using + and – operator
b) Using / and *
Sr. No. Assignment No. of Slots
02 Assignment on decision making statements (if and if-else, nested 01
Structures
OBJECTIVE
THEORY
Normally, your program flows along line by line in the order in which it appears in your
source code. But, it is sometimes required to execute a particular portion of code only if
certain condition is true; or false i.e. you have to make decision in your program. There
are three major decision making structures. Four decision making structures:
1. If statement
2. If-else statement
3. Switch case
4. Conditional Operator (Rarely used)
The if statement
The if statement enables you to test for a condition (such as whether two variables are
equal) and branch to different parts of your code, depending on the result. The simplest
form of an if statement is:
if (expression)
statement;
The expression may consist of logical or relational operators like (> >= < <= && || )
void main(void)
{
int var;
printf(“Enter any number;”);
scanf(“%d”,&var);
if(var==10)
printf(“The user entered number is Ten”);
}
if (expression)
statement;
else
statement;
Note: To execute multiple statements when a condition is true or false, parentheses are used.
Consider the following example that checks whether the input character is an upper case
or lower case:
void main(void)
{
char ch;
printf(“Enter any character”);
ch=getche();
if(ch>=’A’&&ch<=’Z’)
printf(“%c is an upper case character”,ch); else
printf(“%c is a lower case character”,ch); getch();
}
This line is read as "If expression1 is true, return the value of expression2; otherwise,
return the value of expression3." Typically, this value would be assigned to a variable.
An Example:
void main(void)
{
clrscr();
float per;
printf(“\n Enter your percentage;”);
scanf(“%f”,&per);
printf(“\n you are”);
printf(“%s”, per >= 60 ?“Passed”: ”Failed”); getch();
}
Typecasting
Typecasting allow a variable of one type to act like another for a single operation. In C
typecasting is performed by placing, in front of the value, the type name in parentheses.
EXERCISES
2. The programs given below contain some syntax and/or logical error(s). By
debugging, mention the error(s) along with their categorization into syntactical or
logical error. Also write the correct program statements.
i. // To check whether the number is divisible by 2 or not :
int num;
printf(“enter any number”) ;
scanf(“%f”,num);
if(num%2=0)
printf(“Number is divisible by 2”);
else
printf(“number is not divisible by 2”);
__________________________________________________________________________
_
__________________________________________________________________________
_
__________________________________________________________________________
_
__________________________________________________________________________
_
__________________________________________________________________________
_
__________________________________________________________________________
_
__________________________________________________________________________
_
__________________________________________________________________________
_
__________________________________________________________________________
_
__________________________________________________________________________
_
__________________________________________________________________________
_
Assignments :-
Set A
#include<stdio.h>
void main()
{
int a=100;
if(a>10)
printf("Good");
else if(a>20)
printf("Better");
else if(a>30)
printf("Best");
}
2. WAP that takes a number as input from user and checks whether the
number is even or odd.
a) Using if-else
b) Using conditional operator:
5. WAP that takes a number as input from user and checks whether the
number is even or odd
a) Using if-else
b) Using conditional operator:
6. WAP that takes three numbers as input from user and finds maximum
a) Using if-else
b) Using conditional operator:
7. WAP that takes three numbers as input from user and finds minimum
a) Using if-else
b) Using conditional operator
8. WAP that takes one character as input and checks if it is vowel or a consonant.
Set B
1. WAP to take input student age and check whether given student can vote or not
2. WAP to check whether a given year is leap year or not.
3. WAP to print grade of a student using If Else Ladder Statement
4. WAP to find the roots of quadratic equation.
Sr. No. Assignment No. of Slots
03 Assignment on decision making statements (switch case) 01
OBJECT
THEORY
}
getch();
}
Important Points about Switch Statement
Switch case performs equality check of the value of expression/variable against the list of
case values.
The expression in switch case must evaluates to return an integer, character or
enumerated type.
You can use any number of case statements within a switch. The expression value is
compared with the constant after case.
The data type of the value of expression/variable must be same as the data type of case
constants.
The break statement is optional.The break statement at the end of each case cause switch
statement to exit. If break statement is not used, all statements below that case statement
are also executed until it found a break statement.
The default code block gets executed when none of the case matches with expression.
default case is optional and doesn't require a break statement.
We don't use those expressions to evaluate switch case, which may return floating point
values or strings.
SET A
1. Give the output of following code with explanation
a.
#include <stdio.h>
int main()
{
int num = 2;
switch (num + 2)
{
case 1:
printf("Case 1: ");
case 2:
printf("Case 2: ");
case 3:
printf("Case 3: ");
default:
printf("Default: ");
}
return 0;
}
OBJECTIVE:
Study of Loops
Loop:
THEORY
A loop is used for executing a block of statements repeatedly until a given condition returns
false.
Types of Loops
There are three types of Loops:
for Loop
while Loop
do - while Loop
Flowchart:
Example of while loop
#include <stdio.h>
int main()
{
int count=1;
while (count <= 4)
{
printf("%d ", count);
count++;
}
return 0;
}
Output:
1234
step1: The variable count is initialized with value 1 and then it has been tested for the condition.
step2: If the condition returns true then the statements inside the body of while loop are executed
else control comes out of the loop.
step3: The value of count is incremented using ++ operator then it has been tested again for the
loop condition.
Step 1: First initialization happens and the counter variable gets initialized.
Step 2: In the second step the condition is checked, where the counter variable is tested for the
given condition, if the condition returns true then the C statements inside the body of for loop
gets executed, if the condition returns false then the for loop gets terminated and the control
comes out of the loop.
Step 3: After successful execution of statements inside the body of loop, the counter variable is
incremented or decremented, depending on the operation (++ or –).
Example of For loop
#include <stdio.h>
int main()
{
int i;
for (i=1; i<=3; i++)
{
printf("%d\n", i);
}
return 0;
}
Output:
1
2
3
Various forms of for loop in C
1) Here instead of num++, I’m using num=num+1 which is same as num++.
for (num=10; num<20; num=num+1)
2) Initialization part can be skipped from loop as shown below, the counter variable is declared
before the loop.
int num=10;
for (;num<20;num++)
Note: Even though we can skip initialization part but semicolon (;) before condition is must,
without which you will get compilation error.
3) Like initialization, you can also skip the increment part as we did below. In this case
semicolon (;) is must after condition logic. In this case the increment or decrement part is done
inside the loop.
for (num=10; num<20; )
{
//Statements
num++;
}
4) This is also possible. The counter variable is initialized before the loop and incremented inside
the loop.
int num=10;
for (;num<20;)
{
//Statements
num++;
}
5) As mentioned above, the counter variable can be decremented as well. In the below example
the variable gets decremented each time the loop runs until the condition num>10 returns false.
for(num=20; num>10; num--)
Nested For Loop in C
Nesting of loop is also possible. Lets take an example to understand this:
#include <stdio.h>
int main()
{
for (int i=0; i<2; i++)
{
for (int j=0; j<4; j++)
{
printf("%d, %d\n",i ,j);
}
}
return 0;
}
Output:
0, 0
0, 1
0, 2
0, 3
1, 0
1, 1
1, 2
1, 3
6) Multiple initialization inside for Loop in C
We can have multiple initialization in the for loop as shown below.
for (i=1,j=1;i<10 && j<10; i++, j++)
Exercise as an assignment:-
Solve all programs given for while and do while loops using for loop
SET A
SET B
1. WAP to print following pattern.
a) for example if n=5 then output should be
*
* *
* * *
* * * *
* * * * *
2. WAP to print the square of number(s) repeatedly till 1 is entered by user. Using do-while
loop.
3. WAP to print following series
a) Fibonacci series of n numbers
b) 1+3+5+7+--------+n
Sr. No. Assignment No. of Slots
05 Assignment on nested loop and study of Jump Statements 01
OBJECT
THEORY
C programming allows to use one loop inside another loop.
Syntax
The syntax for a nested for loop statement in C is as follows −
for ( init; condition; increment ) {
while(condition) {
statement(s);
}
statement(s);
}
The syntax for a nested do...while loop statement in C programming language is as follows −
do {
statement(s);
do {
statement(s);
}while( condition );
}while( condition );
A final note on loop nesting is that you can put any type of loop inside any other type of loop.
For example, a 'for' loop can be inside a 'while' loop or vice versa.
Example
The following program uses a nested for loop to find the prime numbers from 2 to 100 −
Live Demo
#include <stdio.h>
int main () {
return 0;
}
Output:
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
Theory
Jump Statements :
C language provides us multiple statements through which we can transfer the control anywhere
in the program.
NOTE: This jump statements always used with the control structure like switch case, while, do
while, for loop etc.
NOTE: As break jump statements ends/terminate loop of one level . so it is refered to use return
or goto jump statements , during more deeply nested loops.
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
for(i=1;i<=10;i++)
{
printf(“Enter ”,i,”no”);
printf(“ \t %d ”,i);
if(i>5)
break;
}
}
Syntax:
continue;
NOTE: This jumping statements always used with the control structure like switch case, while,
do while, for loop etc.
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
for(i=1;i<=10;i++)
{
printf(“Enter ”,i,”no”);
printf(“ \t %d ”,i);
if(i==5 || i==8)
continue;
}
}
NOTE:
· The control will transfer to those label that are part of particular function, where goto is
specified.
· All those labels will not include, that are not the part of a particular function where the
goto is specified.
NOTE:
· It is good programming style to use the break, continue and return instead of goto.
· However, the break may execute from single loop and goto executes from more deeper
loops.
WAP to display the square root of a no, if no. is not positive then re enter the input.
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n;
float s;
start:
printf(“Enter a no.”);
scanf(“%d”,&n);
s=sqrt(n);
if(n<=0)
goto start;
printf(“%f”,s);
}
Exit
#include<stdio.h>
#include<stdlib.h>
int main () {
printf("Start of the main()...\n");
printf("Exiting the main()...\n");
exit(0);
printf("End of the program\n");
return(0);
}
SET A
Give the output of following codes with proper explaination
1. #include <stdio.h>
int main()
{
int a = 0, i = 0, b;
for (i = 0;i < 5; i++)
{
a++;
continue;
}
}
2. #include <stdio.h>
int main()
{
int a = 0, i = 0, b;
for (i = 0;i < 5; i++)
{
a++;
if (i == 3)
break;
}
}
3. #include <stdio.h>
void main()
{
int i = 0, j = 0;
for (i = 0;i < 5; i++)
{
for (j = 0;j < 4; j++)
{
if (i > 1)
break;
}
printf("Hi \n");
}
}
4.
#include <stdio.h>
void main()
{
int i = 0;
int j = 0;
for (i = 0;i < 5; i++)
{
for (j = 0;j < 4; j++)
{
if (i > 1)
continue;
printf("Hi \n");
}
}
}
5.
#include <stdio.h>
int main()
{
int num;
printf("Enter value of num:");
scanf("%d",&num);
switch (num)
{
case 1:
printf("You have entered value 1\n");
break;
case 2:
printf("You have entered value 2\n");
case 3:
printf("You have entered value 3\n");
break;
default:
printf("Input value is other than 1,2 & 3 ");
}
return 0;
}
#include <stdio.h>
int main()
{
int i = 0;
for (i=0; i<20; i++)
{
switch(i)
{
case 0:
i += 5;
case 1:
i += 2;
case 5:
i += 5;
default:
i += 4;
break;
}
printf("%d ", i);
}
return 0;
}
8.
#include <stdio.h>
int main()
{
int i = 0;
do
{
i++;
if (i == 2)
continue;
printf("In while loop ");
} while (i < 2);
printf("%d\n", i);
}
9. #include <stdio.h>
int main()
{
int i = 0, j = 0;
for (i; i < 2; i++){
for (j = 0; j < 3; j++){
printf("1\n");
break;
}
printf("2\n");
}
printf("after loop\n");
}
10.
#include <stdio.h>
int main()
{
int i = 0;
char c = 'a';
while (i < 2){
i++;
switch (c) {
case 'a':
printf("%c ", c);
break;
break;
}
}
printf("after loop\n");
}
11.
#include <stdio.h>
int main()
{
printf("%d ", 1);
goto l1;
printf("%d ", 2);
l1:goto l2;
printf("%d ", 3);
l2:printf("%d ", 4);
}
13.
#include <stdio.h>
int main()
{
printf("%d ", 1);
goto l1;
printf("%d ", 2);
}
void foo()
{
l1 : printf("3 ", 3);
}
14.
#include <stdio.h>
int main()
{
int i = 0, j = 0;
while (i < 2)
{
l1 : i++;
while (j < 3)
{
printf("Loop\n");
goto l1;
}
}
}
15.
#include <stdio.h>
int main()
{
int i = 0, j = 0;
while (l1: i < 2)
{
i++;
while (j < 3)
{
printf("loop\n");
goto l1;
}
}
}
16.
#include <stdio.h>
int main()
{
int i = 0, j = 0;
l1: while (i < 2)
{
i++;
while (j < 3)
{
printf("loop\n");
goto l1;
}
}
}
17.
#include <stdio.h>
void main()
{
int i = 0;
if (i == 0)
{
goto label;
}
label: printf("Hello");
}
18.
#include <stdio.h>
void main()
{
int i = 0, k;
if (i == 0)
goto label;
for (k = 0;k < 3; k++)
{
printf("hi\n");
label: k = printf("%03d", i);
}
}
19.
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("statement-1\n");
printf("statement-2\n");
exit(0);
printf("statement-N\n");
return 0;
}
SET A
*****
****
***
**
*
Sr. No. Assignment No. of Slots
06 Assignment on menu driven programs. 01
OBJECTIVE
Menu driven program using switch statement is preferred because it is faster, more user-friendly
as compare to if-else based menu driven program.
SET A
SET B
1. Write a C program for a menu driven program which has following options:
1. Factorial of a number.
2. Prime or not
3. Odd or even
4. Exit
SET C
THEORY
User-defined functions
There are four types of functions depending on the return type and arguments:
1. Functions that take nothing as argument and return nothing.
2. Functions that take arguments but return nothing.
3. Functions that do not take arguments but return something.
4.Functions that take arguments and return something.
Like any variable or an array, a function must also be declared before its used. Function
declaration informs the compiler about the function name, parameters is accept, and its return
type. The actual body of the function can be defined separately. It's also called as Function
Prototyping. Function declaration consists of 4 parts.
returntype
function name
parameter list
terminating semicolon
returntype
When a function is declared to perform some sort of calculation or any operation and is expected
to provide with some result at the end, in such cases, a return statement is added at the end of
function body. Return type specifies the type of value(int, float, char, double) that function is
expected to return to the program which called the function.
Note: In case your function doesn't return any value, the return type would be void.
functionName
Function name is an identifier and it specifies the name of the function. The function name is any
valid C identifier and therefore must follow the same naming rules like other variables in C
language.
parameter list
The parameter list declares the type and number of arguments that the function expects when it is
called. Also, the parameters in the parameter list receives the argument values when the function
is called. They are often referred as formal parameters.
functionbody
The function body contains the declarations and the statements(algorithm) necessary for
performing the required task. The body is enclosed within curly braces { ... } and consists of
three parts.
local variable declaration(if required).
function statements to perform the task inside the function.
a return statement to return the result evaluated by the function(if return type is void, then no
return statement is required).
Calling a function
When a function is called, control of the program gets transferred to the function.
functionName(argument1, argument2,...);
In the example above, the statement multiply(i, j); inside the main() function is function call.
{
int num1,num2,sum;
printf(“Enter 1st number:”);
scanf(“%d”,&num1);
printf(“Enter 2nd number:”);
scanf(“%d”,&num2);
sum=num1+num2;
printf(“Sum of %d+%d=%d”,num1,num2,sum);
}
call By value
call By Reference
Unlike call by value, in this method, address of actual arguments (or
parameters) is passed to the formal parameters, which means any operation
performed on formal parameters affects the value of actual parameters
Study of Recursive Functions
Recursion
Theory
Recursion is an ability of a function to call itself.
int add(int);
void main(void)
{
int num,ans;
printf(“Enter any number:”);
scanf(“%d”,&num);
ans=add(num);
printf(“Answer=%d”,ans);
getch();
}
int add(int n)
{
int result;
if(n==1)
return 1;
result=add(n-1) + n;
return result;
}
SET A
1. Trace the output
#include<stdio.h>
int i;
int fun();
int main()
{
while(i)
{
fun();
main();
}
printf("Hello\n");
return 0;
}
int fun()
{
printf("Hi");
}
SET A
a) func(int a,int b)
{
int a; a=20; return a;
}
{
int myfunc(int); int b; b=myfunc(20); printf(“%d”,b); return 0;
}
int myfunc(int a)
{
a > 20? return(10): return(20);
}
3. WAP to print your name 10 times. The function can take no arguments and should not
return any value.
SET B
1.WAP to print the GCD of 4 given numbers using function to calculate the GCD of two
numbers*/
2. WAP to find the factorial of an Integer
3. WAP to Calculate the value of nCr
5. main( ) is a function. Write a function which calls main( ). What is the output of this
program?
6. WAP to Find the Sum of Natural Numbers using Recursion
7. WAP to find factorial of a number using Recursion
SET C
1 . WAP that takes a number as input and print its binary equivalent.
Sr. No. Assignment No. of Slots
08 Assignment on arrays 1-D 01
Study of Arrays
THEORY
An array is a collection of data storage locations, each of which holds the same type of
data. Each storage location is called an element of the array. You declare an array by
writing the type, followed by the array name and the subscript. The subscript is the
number of elements in
the array, surrounded by square brackets.
declares an array of 25 integers, named LongArray. When the compiler sees this
declaration, it sets aside enough memory to hold all 25 elements. Because each long
integer requires 2 bytes, this declaration sets aside 50 contiguous bytes of memory.
Consider the following program that take 10 numbers as input in an array and then print
that array.
#include<stdio.h>
void main(void)
{
clrscr();
int arr[10];
for(int i=0;i<10;i++)
{
printf(“\n\tEnter element %d:”,i+1);
scanf(“%d”,&arr[i]);
}
clrscr();
for(int j=0;j<10;j++)
printf(“\n\n\t Element %d is %d”,j+1,arr[j]); getch();
}
Assignments:
SET A
SET B
In C programming, you can create an array of arrays known as multidimensional array. For
example,
float x[3][4];
Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the array
as table with 3 row and each row has 4 column.
Above code are three different ways to initialize a two dimensional arrays.
SET A
1. WAP to store temperature of two cities for a week and display it.
2. WAP to find the sum of two matrices of order 2*2 using multidimensional arrays.
3. WAP to store values entered by the user in a three-dimensional array and display it.
SET B
SET C
int main() {
int ageArray[] = {2, 8, 4, 12};
Output
Here, we have passed array parameters to the display() function in the same way we pass
variables to a function.
#include <stdio.h>
float calculateSum(float num[]);
int main() {
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};
// num array is passed to calculateSum()
result = calculateSum(num);
printf("Result = %.2f", result);
return 0;
}
return sum;
}
Output
Result = 162.50
To pass an entire array to a function, only the name of the array is passed as an argument.
result = calculateSum(num);
To pass multidimensional arrays to a function, only the name of the array is passed to the function
(similar to one-dimensional arrays).
#include <stdio.h>
void displayNumbers(int num[2][2]);
int main() {
int num[2][2];
printf("Enter 4 numbers:\n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
scanf("%d", &num[i][j]);
}
}
return 0;
}
void displayNumbers(int num[2][2]) {
printf("Displaying:\n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
printf("%d\n", num[i][j]);
}
}
}
Output
Enter 4 numbers:
2
3
4
5
Displaying:
2
3
4
5
Notice the parameter int num[2][2] in the function prototype and function definition:
// function prototype
void displayNumbers(int num[2][2]);
This signifies that the function takes a two-dimensional array as an argument. We can also pass
arrays with more than 2 dimensions as a function argument.
When passing two-dimensional arrays, it is not mandatory to specify the number of rows in the
array. However, the number of columns should always be specified.
For example,
Assignments:
SET A
SET B
1. WAP to display the sum of all elements in a 2-D array using function
2. WAP to display the sum of all diagonal elements in a 2-D array using function
3. WAP to display the inverse of a 2-D array using function