0% found this document useful (0 votes)
27 views64 pages

F.Y. Cloud Computing Workbook

The Practical Workbook provides an introduction to programming concepts using C language and covers both basic and advanced topics. It includes ten lab assignments focusing on various programming constructs such as data types, loops, and functions, along with a structured approach to writing, compiling, and executing C programs. The workbook is designed for students in the Center for Advanced Studies in Applied Sciences and is intended to complement theoretical classes.

Uploaded by

pathakpritee20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views64 pages

F.Y. Cloud Computing Workbook

The Practical Workbook provides an introduction to programming concepts using C language and covers both basic and advanced topics. It includes ten lab assignments focusing on various programming constructs such as data types, loops, and functions, along with a structured approach to writing, compiling, and executing C programs. The workbook is designed for students in the Center for Advanced Studies in Applied Sciences and is intended to complement theoretical classes.

Uploaded by

pathakpritee20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 64

Practical Workbook

Name : _____________________________
Year : _____________________________
Batch : _____________________________
Roll No : _____________________________
Department: __________________________
Teacher : __________________________

Center For Advanced Studies in Applied Sciences

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

Sr. No. Assignment No. of Slots


1. Familiarization with Programming Environment using Turbo C and 01
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 01
Structures
3. Assignment on decision making statements (switch case) 01
4. Assignment on use of loops 01
5. Assignment on nested loop and study of Jump Statements 01
6. Assignment on menu driven programs. 01
7. Assignment on Functions (user defined) 01
8. Assignment on Arrays 1-D 01
9. 01
Assignment on Arrays 2-D
01
10. Assignment on Arrays and Functions 01
Total slots Required 10

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)

Sr. No. Assignment No. of Slots


01 Familiarization with Programming Environment using Turbo C 01
and Fundamentals of Programming Language
Assignment on use of data types, simple operators (expressions)
Debugging and Single-Stepping of Programs

OBJECTIVE:

Familiarization with Programming Environment using Turbo C and Fundamentals


of Programming Language

THEORY

The Development Environment - Integrated Development Environment (IDE):


The C compiler has its own built-in text editor. You may also use a commercial text
editor or word processor that can produce text files. The important thing is that
whatever you write your program in, it must save simple, plain-text files, with no word
processing commands embedded in the text. The files you create with your editor are
called source files, and for C++ they typically are named with the extension .CPP, .CP,
or .C.

The C Developing Environment, also called as Programmers’ Platform, is a screen


display with windows and pull-down menus. Code of the program, error messages and
other information are displayed in separate windows. The menus may be used to invoke
the operations necessary to develop the program, debug and execute the program.

Invoking the IDE


To invoke the IDE from the windows you need to double click the TC icon.

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.

Opening New Window


To type a program, you need to open an Edit Window. For this, open file menu and
click “new”. A window will appear on the screen where the program may be typed.

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

Making an Executable File


The source file is required to be turned into an executable file. This is called “Making” of the
.exe file. The steps required to create an executable file are:
1. Create a source file, with a .c extension.
2. Compile the source code into a file with the .obj extension.
3. Link your .obj file with any needed libraries to produce an executable program.

Compiling the Source Code


Although the source code in your file is somewhat cryptic, and anyone who doesn't
know C will struggle to understand what it is for, it is still in what we call human-
readable form. But, for the computer to understand this source code, it must be
converted into machine-readable form. This is done by using a compiler. Hence,
compiling is the process in which source code is translated into machine understandable
language.

Creating an Executable File with the Linker


After your source code is compiled, an object file is produced. This file is often named
with the extension .OBJ. This is still not an executable program, however. To turn this
into an executable program, you must run your linker. C programs are typically created
by linking together one or more OBJ files with one or more libraries. A library is a
collection of linkable files that were supplied with your compiler.

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.

Compiling and linking in the IDE


In the Turbo C IDE, compiling and linking can be performed together in one step. There
are two ways to do this: you can select Make EXE from the compile menu, or you can
press the [F9] key.

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.

The Development Cycle


If every program worked the first time you tried it, that would be the complete
development cycle: Write the program, compile the source code, link the program, and
run it. Unfortunately, almost every program, no matter how trivial, can and will have
errors, or bugs, in the program. Some bugs will cause the compile to fail, some will
cause the link to fail, and some will only show up when you run the program.Whatever
type of bug you find, you must fix it, and that involves editing your source code,
recompiling and relinking, and then rerunning the program.

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.

C Program Structure – First C Program

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.

STEPS TO WRITE C PROGRAMS AND GET THE OUTPUT:


Below are the steps to be followed for any C program to create and get the output. This
is common to all C program and there is no exception whether its a very small C
program or very large C program.
1. Create
2. Compile
3. Execute or Run
4. Get the Output

CREATION, COMPILATION AND EXECUTION OF A 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.

BASIC STRUCTURE OF A C PROGRAM:


Structure of C program is defined by set of rules called protocol, to be followed by
programmer while writing C program. All C programs are having sections/parts which
are mentioned below.
1. Documentation section
2. Link Section
3. Definition Section
4. Global declaration section
5. Function prototype declaration section
6. Main function
7. User defined function definition section

EXAMPLE C PROGRAM TO COMPARE ALL THE SECTIONS:


You can compare all the sections of a C program with the below C program.

/*
Documentation section
C programming basics & structure of C programs
Author: New Author
Date :01/01/2018
*/

#include <stdio.h> /* Link section */


int total = 0; /* Global declaration, definition section */
int sum (int, int); /* Function declaration section */
int main () /* Main function */
{
printf ("This is a C basic program \n");
total = sum (1, 1);
printf ("Sum of two numbers : %d \n", total);
return 0;
}

int sum (int a, int b) /* User defined function */


{
return a + b; /* definition section */
}
OUTPUT:
This is a C basic program
Sum of two numbers : 2
DESCRIPTION FOR EACH SECTION OF THE C PROGRAM:
 Let us see about each section of a C basic program in detail below.
 Please note that a C program mayn’t have all below mentioned sections except main
function and link sections.
 Also, a C program structure mayn’t be in below mentioned order.
Sections Description

We can give comments about the program, creation or modified date,


author name etc in this section. The characters or words or anything which
are given between “/*” and “*/”, won’t be considered by C compiler for
compilation process.These will be ignored by C compiler during
Documentation compilation.
section Example : /* comment line1 comment line2 comment 3 */

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!

OBJECTIVE:- Understanding data types and simple operators

C Keywords – Reserved Words

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.

break – Used with any loop OR switch case.

int, float, char, double, long – These are the data types and used during variable declaration.

for, while, do – types of loop structures in C.

void – One of the return type.

goto – Used for redirecting the flow of execution.

auto, signed, const, extern, register, unsigned – defines a variable.

return – This keyword is used for returning a value.

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.

sizeof – It is used to know the size.

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.

Building Blocks of Programming Language:


In any language there are certain building blocks:
 Constants
 Variables
 Operators
Methods to get input from user (scanf( ), getch( ) etc.)
Methods to display output (Format Specifier, Escape Sequences etc.) and so on.

Variables and Constants


If the value of an item can be changed in the program then it is a variable. If it will not
change then that item is a constant. The various variable types (also called data type) in
C are: int, float, char, long etc. For constants, the keyword const is added before
declaration.

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

Operator Meaning of Operator


+ addition or unary plus

- subtraction or unary minus

* Multiplication

/ division

% remainder after division( modulo division)

II. Increment and Decrement Operators

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 – – ;

Difference between pre/post increment & decrement operators in C:


Below table will explain the difference between pre/post increment and decrement
operators in C programming language

Operator Operator Description


Pre increment operator (++i) value of i is incremented before
assigning it to the variable i

Post increment operator (i++) value of i is incremented after


assigning it to the variable i

Pre decrement operator (- -i) value of i is decremented before


assigning it to the variable I

value of i is decremented after


Post decrement operator (i- -) assigning it to variable i

Example program for pre – increment operators in C:

//Example for increment operators

#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”.

Example program for post – increment operators in C:

#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”.

Example program for pre – decrement operators in C:


#include <stdio.h>
int main()
{
int i=10;
while(--i > 5 )
{
printf("%d ",i);
}
return 0;
}

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”.

Example program for post – decrement operators in C:


#include <stdio.h>
int main()
{
int i=10;
while(i-- > 5 )
{
printf("%d ",i);
}
return 0;
}

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”.

III. Assignment Operators


In C programs, values for the variables are assigned using assignment operators.
For example, if the value “10” is to be assigned for the variable “sum”, it can be
assigned as “sum = 10;”
There are 2 categories of assignment operators in C language. They are,
1. Simple assignment operator ( Example: = )
2. Compound assignment operators ( Example: +=, -=, *=, /=, %=, &=, ^= )

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

IV. Relational Operators


Relational operators are used to find the relation between two variables. i.e. to compare
the values of two variables in a C program

Operators
Example/Description

>
x > y (x is greater than y)

< x < y (x is less than y)

>= x >= y (x is greater than or equal


to 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)

Example program for relational operators in C:


In this program, relational operator (==) is used to compare 2 values whether they are
equal are not.
If both values are equal, output is displayed as ” values are equal”. Else, output is
displayed as “values are not equal”.
Note : double equal sign (==) should be used to compare 2 values. We should not single
equal sign (=).

#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

Example program for conditional/ternary operators in C:

#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

VII. Bitwise Operators


These operators are used to perform bit operations. Decimal values are converted into binary
values which are the sequence of bits and bit wise operators work on these bits.
Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise OR), ^
(XOR), << (left shift) and >> (right shift).

TRUTH TABLE FOR BIT WISE OPERATION & BIT WISE OPERATORS:

Below are the bit-wise operators and their name in C language.


& – Bitwise AND
| – Bitwise OR
~ – Bitwise NOT
^ – XOR
<< – Left Shift
>> – Right Shift
Consider x=40 and y=80. Binary form of these values are given below.
x = 00101000
y= 01010000

All bit wise operations for x and y are given below.


x&y = 00000000 (binary) = 0 (decimal)
x|y = 01111000 (binary) = 120 (decimal)
~x = 11111111111111111111111111 11111111111111111111111111111111010111 = -41
(decimal)
x^y = 01111000 (binary) = 120 (decimal)
x << 1 = 01010000 (binary) = 80 (decimal)
x >> 1 = 00010100 (binary) = 20 (decimal)

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.

Example program for bit wise operators in C:


In this example program, bit wise operations are performed as shown above and output is
displayed in decimal format.

#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

This is used to get the address of the variable.


& Example : &a will give address of a.

This is used as pointer to a variable.


Example : * a where, * is pointer to the variable
* a.

This gives the size of the variable.


Sizeof () Example : size of (char) will give us 1.

printf format identifiers.

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

Required Optional Optional Optional Optional Required

Format Specifiers
Format Specifiers tell the printf statement where to put the text and how to display the text.
The various format specifiers are:

Format specifier Description Supported data types

char
%c Character
unsigned char

short
unsigned short
%d Signed Integer
int
long

float
%e or %E Scientific notation of float values
double

%f Floating point float


float
%g or %G Similar as %e or %E
double

%hi Signed Integer(Short) short

%hu Unsigned Integer(Short) unsigned short

short
unsigned short
%i Signed Integer
int
long

%l or %ld or %li Signed Integer long

%lf Floating point double

%Lf Floating point long double

unsigned int
%lu Unsigned integer
unsigned long

%lli, %lld Signed Integer long long

%llu Unsigned Integer unsigned long long

short
unsigned short
%o Octal representation of Integer. int
unsigned int
long

%p Address of pointer to void void * void *

%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.

Field Width Specifiers


this is “n is printed right-justified in a field width of 5". “Right-justify" means that the number is
placed as far right as possible in the field and spaces added in front of it to make up the field
width. If the number is placed as far left as possible and spaces are added after it to make up the
field width, the number is left-justified. The minus sign can be used to specify left-justification;

They are used with % to limit precision in floating point number. The number showing
limit follows the radix point.

Field Width Example


A field width is useful when we want to line up numbers one below the other. Suppose
we have three int variables a, b and c with values 9876, -3 and 501, respectively. The
statements
printf("%d\n", a);
printf("%d\n", b);
printf("%d\n", c);
output will print
9876
-3
501

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);

output will print (◊ denotes a space)


◊9876
◊◊◊-3
◊◊501

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();
}

2. Demonstrating the fundamentals of C Language

#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

Debugging and Single-Stepping of Programs

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.

One Step at a Time


The first thing that the debugger can do for you is slow down the operation of the
program. One trouble with finding errors is that a typical program executes in a few
milliseconds, so all you can see is its final state. By invoking C++’s single-stepping
capability, you can execute just one line of the program at a time. This way you can
follow where the program is going.
Consider the following program:
void main(void)
{
int number, answer=-1;
number = -50;
if(number < 100)
if(number > 0)
answer = 1;
else
answer = 0;
printf(“answer is %d\n”, answer);
}

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:

if( num > 0)

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.

Resetting the Debugger


Suppose you’ve single stepped part way through a program, and want to start over at the
beginning. How do you place the run bar at the top of the listing? You can reset the
debugging process and initialize the run bar by selecting the Program Reset option from
the Run menu.

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.

__________________________________________________________________________
_

__________________________________________________________________________
_

ii. Remove the semi colon ‘;’.

__________________________________________________________________________
_

__________________________________________________________________________
_

iii. Erase any one of brace ‘{’ or ‘}’ .


__________________________________________________________________________
_

__________________________________________________________________________
_

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

1. WAP to find sum of two numbers


2. WAP to find simple interest
3. WAP to convert temperature from degree centigrade to Fahrenheit
4. WAP to calculate sum of 5 subjects and find percentage
5. WAP to find gross salary
D.A= 10 % of basic
T.A= 12 % basic
Gross salary = basic+ D.A.+ T.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

Decision Making Statements (if and if-else, nested structures)

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 (> >= < <= && || )

An understanding of if statement is demonstrated with the following example:

void main(void)
{
int var;
printf(“Enter any number;”);
scanf(“%d”,&var);
if(var==10)
printf(“The user entered number is Ten”);
}

The if-else statement


Often your program will want to take one branch if your condition is true, another if it is
false.
The keyword else can be used to perform this functionality:

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();
}

Conditional (Ternary) Operator


The conditional operator (?:) is C’s only ternary operator; that is, it is the only operator
to take three terms.
The conditional operator takes three expressions and returns a value:
(expression1) ? (expression2) : (expression3);

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”);
__________________________________________________________________________
_

__________________________________________________________________________
_

__________________________________________________________________________
_

__________________________________________________________________________
_

__________________________________________________________________________
_

ii. // To print your batch


int x =Your_batch;
if (x==2016)
printf(“Your batch is 2010”)
else
printf(“Your batch is %d”,x);

__________________________________________________________________________
_

__________________________________________________________________________
_

__________________________________________________________________________
_

__________________________________________________________________________
_

__________________________________________________________________________
_

__________________________________________________________________________
_
Assignments :-
Set A

1. Mention the output for the following program :

#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:

3. WAP to print the ASCII value of any given character


4. WAP to print character value corresponding to any ASCII value

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

Decision Making Statements(Switch Case)

THEORY

The switch Statement


Unlike if, which evaluates one value, switch statements allow you to branch on any of a
number of different values. The general form of the switch statement is:
switch (expression)
{
case valueOne: statement;
break;
case valueTwo: statement;
break;
....
case valueN: statement;
break;
default: statement;
}
An Example:
void main(void)
{
clrscr();
char grade;
printf(“\n Enter your Grade: ”);
grade=getche();
switch(grade)
{
case ‘A’:
case ‘a’:
printf(“\n Your percentage is 80 or above 80 ”); break;
case ‘B’:
case ‘b’:
printf(“\n Your percentage is in 70-80 ”); break;
default:
printf(“\n Your percentage is below 70 ”);

}
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;
}

2 .WAP to print grade of a student using switch case


3. WAP to accept the week day as number from user and display Monday to Sunday.

4. WAP to check whether a given character is VOWEL or CONSONANT using switch-case


5. WAP to find number of days in a month using switch -case
Sr. No. Assignment No. of Slots
04 Assignment on use of loops 01

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

The while Loop


while(condition is true)
{
Do this;
}
This loop runs as long as the condition in the parenthesis is true. Note that there is no
semicolon after the “while” statement. If there is only one statement in the “while” loop
then the braces may be removed.

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.

Examples of infinite while loop


Example 1:
#include <stdio.h>
int main()
{
int var = 6;
while (var >=5)
{
printf("%d", var);
var++;
}
return 0;
}
Infinite loop: var will always have value >=5 so the loop would never end.

The do-while Loop


do
{
this;
}
while(condition is true);
This loop runs as long as the condition in the parenthesis is true. Note that there is a
semicolon after the “while” statement. The difference between the “while” and the “do-
while” statements is that in the “while” loop the test condition is evaluated before the
loop is executed, while in the “do” loop the test condition is evaluated after the loop is
executed. This implies that statements in a “do” loop are executed at least once.
However, the statements in the “while” loop are not necessarily executed.
Flowchart:

Example of do while loop


#include <stdio.h>
int main()
{
int j=0;
do
{
printf("Value of variable j is: %d\n", j);
j++;
}while (j<=3);
return 0;
}
Output:

Value of variable j is: 0


Value of variable j is: 1
Value of variable j is: 2
Value of variable j is: 3
For loop :
THEORY

This is one of the most frequently used loop in C programming.

Syntax of for loop:


for (initialization; condition test; increment or decrement)
{
//Statements to be executed repeatedly
}

Flow Diagram of For loop

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

1. WAP to add first 10 numbers.


2. WAP to add first n numbers.
3. WAP to add any 10 numbers.
4. WAP to print reverse of any number.
5. WAP to add first 10 numbers.
6. WAP to find factorial of a given number
7. WAP to print table of any given number

Solve the following using for loop


1. WAP to print table of first n numbers in proper format.
2. WAP to check whether a given number is perfect number
3. WAP to check whether a given number is prime number

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

Study of Loops(nested loops)

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 ) {

for ( init; condition; increment ) {


statement(s);
}
statement(s);
}
The syntax for a nested while loop statement in C programming language is as follows −
while(condition) {

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 () {

/* local variable definition */


int i, j;

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

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


if(!(i%j)) break; // if factor found, not prime
if(j > (i/j)) printf("%d is prime\n", i);
}

return 0;
}
Output:
2 is 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

Study of Jump statements


(exit, goto , continue , break)

Theory

Jump Statements :
C language provides us multiple statements through which we can transfer the control anywhere
in the program.

1. break jump statements.


· By using this jumping statement, we can terminate the further execution of the program
and transfer the control to the end of any immediate loop.
· To do all this we have to specify a break jumping statements whenever we want to
terminate from the loop.
Syntax: break;

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.

Example: Program based upon break jump statements:

WAP to display the following output:


1 2 3 4 5

#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;
}
}

2. continue jump statements.


· By using this jump statement, we can terminate the further execution of the program and
transfer the control to the beginning of any immediate loop.
· To do all this we have to specify a continue jumping statements whenever we want to
terminate terminate any particular condition and restart/continue our execution.

Syntax:
continue;

NOTE: This jumping statements always used with the control structure like switch case, while,
do while, for loop etc.

Example: Program based upon continue jumping statements:

WAP to display the following output:


1 2 3 4 . 6 7 . 9 10

#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;
}
}

3. goto jump statements.


· By using this jump statements we can transfer the control from current location to
anywhere in the program.
· To do all this we have to specify a label with goto and the control will transfer to the
location where the label is specified.

Syntax: goto <label>;

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.

Example: Program based upon continue jumping statements:

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

The exit() function:


In C exit() is a predefined/ library function used to terminate the currently running
program(process) immediately.
Syntax: void exit(int status);
status -> The status in an integer value returned to the parent process.
Here 0 usually means program completed successfully, and nonzero values are used as error
codes. e.g exit(0);
There are also predefined macros EXIT_SUCCESS and EXIT_FAILURE, e.g.
exit(EXIT_SUCCESS);
In the C Language, the required header for the exit( ) function is stdlib.h.

#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);
}

Output Start of the main()… Exiting the main()

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;
}

Show the output when num=1 ,num=2,num=4


6. #include <stdio.h>
int main()
{
int var;
for (var =100; var>=10; var --)
{
printf("var: %d\n", var);
if (var==99)
{
break;
}
}
printf("Out of for-loop");
return 0;
}
7.

#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);
}

12. #include <stdio.h>


int main()
{
printf("%d ", 1);
l1:l2:
printf("%d ", 2);
printf("%d\n", 3);
}

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

1. WAP to print the number pattern.


1
12
123
1234
1 2345
2. WAP to inverted half pyramid using * and numbers

*****
****
***
**
*
Sr. No. Assignment No. of Slots
06 Assignment on menu driven programs. 01

OBJECTIVE

Study of Menu driven Programs

To write a menu driven program in C you can do it in two ways.


1. Using an if-else construct.
2. switch statements.

Menu driven program using switch statement is preferred because it is faster, more user-friendly
as compare to if-else based menu driven program.

But there are some pitfalls for both the methods:


If you use if-else to make to make a menu driven program then your program will become hard
to read (not user friendly).
And if you use switch statements to make a menu-driven program then you program will be user
friendly but the switch keyword is followed by an integer or an expression which evaluates to an
integer.

SET A

1. Write a menu-driven program using Switch case to calculate the following:


1. Area of circle
2. Area of square
3. Area of sphere

2. Write a menu driven program to create a simple calculator


(Performs addition, subtraction, multiplication or division depending the input from user)

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

2. Write a menu driven C program using switch-case to find:


(a) Sum of the digits of number
(b) product of the digits of number.

SET C

1. Write a menu driven C program using switch-case to perform following operations


A. bitwise and (&)
B. bitwise or( | )

Sr. No. Assignment No. of Slots


07 Assignment on Functions (user defined) 01
Study of Functions
(User defined)

THEORY

A function is a block of code that performs a particular task.


There are many situations where we might need to write same line of code for more than
once in a program. This may lead to unnecessary repetition of code, bugs and even becomes
boring for the programmer. So, C language provides an approach in which you can declare and
define a group of statements once in the form of a function and it can be called and used
whenever required.
These functions defined by the user are also known as User-defined Functions

C functions can be classified into two categories,


Library functions
User-defined functions

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.

General syntax for function declaration is,

returntype functionName(type1 parameter1, type2 parameter2,...);

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.

Function definition Syntax


Just like in the example above, the general syntax of function definition is,
returntype functionName(type1 parameter1, type2 parameter2,...)
{
// function body goes here
}
The first line returntype functionName(type1 parameter1, type2 parameter2,...) is known as
function header and the statement(s) within curly braces is called function body.
Note: While defining a function, there is no semicolon(;) after the parenthesis in the function
header, unlike while declaring the function or calling the function.

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.

Passing Arguments to a function


Arguments are the values specified during the function call, for which the formal parameters are
declared while defining the function.

Returning a value from function


A function may or may not return a result. But if it does, we must use the return statement to
output the result. return statement also ends the function execution, hence it must be the last
statement of any function. If you write any statement after the return statement, it won't be
executed. The datatype of the value returned using the return statement should be same as the
return type mentioned at function declaration and definition. If any of it mismatches, you will get
compilation error.

Consider a simple example of function declaration, definition and call.


void function1(void);
void function2(void)
{
printf("Writing in Function2\n");
}
void main(void)
{
printf("Writing in main\n");
function1( );
}
void function1(void)
{
printf("Writing in Function1\n");
function2( );
}
Consider another example that adds two numbers using a function sum() .
void sum(void);
void main(void)
{
printf(“\nProgram to print sum of two numbers\n”); sum(void);
}
void sum(void)

{
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

Function call by value is the default way of calling a function in C programming


Important terms:-
What is Function Call By value?
When we pass the actual parameters while calling a function then this is known as function call
by value. In this case the values of actual parameters are copied to the formal parameters. Thus
operations performed on the formal parameters don’t reflect in the actual parameters.
Actual parameters: The parameters that appear in function calls.
Formal parameters: The parameters that appear in function declarations.

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.

An example: A program that calculates the following series using recursion.

n + (n-1) + (n-2) + ………… + 3 +2 + 1

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");
}

Solve Set A ,B and C using user defined functions

SET A

1. Identify the errors (if any) in the following code:

a) func(int a,int b)
{
int a; a=20; return a;
}

b) #include<stdio.h> int main()

{
int myfunc(int); int b; b=myfunc(20); printf(“%d”,b); return 0;

}
int myfunc(int a)
{
a > 20? return(10): return(20);
}

2. WAP to calculate cube of a number

3. WAP to print your name 10 times. The function can take no arguments and should not
return any value.

4. WAP to print Table of an Integer Number.


5. WAP to find SUM and AVERAGE of two integer Numbers .

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.

For example , int LongArray[25];

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.

Elements of an Array and How to access them?


You can access elements of an array by indices.
Suppose you declared an array mark as above. The first element is mark[0], second
element is mark[1] and so on.

Few key notes:


Arrays have 0 as the first index not 1. In this example, mark[0]
If the size of an array is n, to access the last element, (n-1) index is used. In this
example, mark[4]
Suppose the starting address of mark[0] is 2120d. Then, the next address, a[1], will be
2124d, address of a[2] will be 2128d and so on. It's because the size of a float is 4 bytes.

How to initialize an array in C programming?


It's possible to initialize an array during declaration. For example,
int mark[5] = {19, 10, 8, 17, 9};

Another method to initialize array during declaration:


int mark[] = {19, 10, 8, 17, 9};
How to insert and print array elements

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

1. WAP to Calculate Sum & Average of an Array of size 20


2. WAP to Find the Largest Number in an Array
3. WAP to Find the Largest Two Numbers in a given Array
4. WAP to Put Even & Odd Elements of an Array in 2 Separate Arrays
5. WAP to Insert an Element in a Specified Position in a given Array

SET B

1. WAP to Sort the Array in an Ascending Order


2. WAP Input an Array, Store the Squares of these Elements in an Array & Print it.
3. WAP Increment every Element of the Array by one & Print Incremented Array.
4.WAP to find 2 Elements in the Array such that Difference between them is Largest
Sr. No. Assignment No. of Slots
09 Assignment on arrays 2-D 01

Study of Multidimensional Arrays

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.

Similarly, you can declare a three-dimensional (3d) array. For example,


float y[2][4][3];
Here,The array y can hold 24 elements.
You can think this example as: Each 2 elements have 4 elements, which makes 8 elements and
each 8 elements can have 3 elements. Hence, the total number of elements is 24.

How to initialize a multidimensional array?


There is more than one way to initialize a multidimensional array.

Initialization of a two dimensional array


// Different ways to initialize two dimensional array

int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};

int c[][3] = {{1, 3, 0}, {-1, 5, 9}};

int c[2][3] = {1, 3, 0, -1, 5, 9};

Above code are three different ways to initialize a two dimensional arrays.

Initialization of a three dimensional array.


You can initialize a three dimensional array in a similar way like a two dimensional array. Here's
an example,
int test[2][3][4] = {
{ {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },
{ {13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9} }
};

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

1. WAP to multiply two matrices of size m and n.


2. WAP to find the transpose of a matrix
3. WAP find addition of any given row number.

SET C

1. WAP to add the diagonal elements


2. WAP to find the sum all the elements
Sr. No. Assignment No. of Slots
10 Assignment on Arrays and Functions 01

Pass arrays to a function in C

I.Pass Individual Array Elements


Passing array elements to a function is similar to passing variables to a function

Example 1: Pass Individual Array Elements


#include <stdio.h>
void display(int age1, int age2) {
printf("%d\n", age1);
printf("%d\n", age2);
}

int main() {
int ageArray[] = {2, 8, 4, 12};

// pass second and third elements to display()


display(ageArray[1], ageArray[2]);
return 0;
}

Output

Here, we have passed array parameters to the display() function in the same way we pass
variables to a function.

II. Pass Arrays to Functions

// Program to calculate the sum of array elements by passing 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;
}

float calculateSum(float num[]) {


float sum = 0.0;

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


sum += num[i];
}

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);

However, notice the use of [] in the function definition.

float calculateSum(float num[]) {


... ..
}
This informs the compiler that you are passing a one-dimensional array to the function.

III. Pass Multidimensional Arrays to a Function

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]);
}
}

// pass multi-dimensional array to a function


displayNumbers(num);

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,

void displayNumbers(int num[][2]) {


// code
}

Assignments:

SET A

1. WAP to display sum and average of an array using function


2.WAP to Accept a number and a array and display the number of occurrences of the number in
the array using function.
3.WAP to sort an array using function

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy