0% found this document useful (0 votes)
8 views

DECAP172 Programming Methodology

Uploaded by

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

DECAP172 Programming Methodology

Uploaded by

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

Doric Multimedia Pvt. Ltd.

Branch I: 1st Floor, Gulati Market, Near CMC Chowk,


Ludhiana

Contact: 7696100090

Branch II: 1st Floor, Arora Tower, Jamalpur Chowk,


Chandigarh Road, Ludhiana

Contact: 8054100099
IMPORTANT QUESTIONS

DCAP 102/DCAP 401

BASIC PROGRAMMING
SKILLS/
FOUNDATIONS OF
COMPUTER
PROGRAMMING

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
2Marks Questions:-
1:-Programming Language:- A programming language is an artificial language designed to express
computations that can be performed by a machine. Programming language can be used to create programs
that control the behaviour of a computer. Programming language is the problem solving and writing
instructions for a computer.

2:-Character Set:- Character set means that the characters and symbols that a C program can understand
and accept. These are grouped to form the commands,expressions,words and other tokens etc. For eg:-
A,a,1,<,{

3:-Keywords:- keywords are the reserve words which cannot be used as variables or identifiers. They are
part of c tokens. Eg:- double,int,union,struct,while,switch

4:-Identifiers:- Identifiers or symbols are the names you suppy for variables,types,functions and labels in
program. Identifiers names must be spelling case from any keywords. it helps to identify constants and
variables.

5:- Variables:- Variables are those quantities whose values can vary during execution of a program.
These are basically a memory locations which are given names and these locations are referred in the
program by variable name to read and write data.

6:-Enumerated datatype:-this type of datatype is user defined. It allows theuser to define a variable or
an identifier which is used for representing of existing data types. It stores data in memory,it gives output
in numerical forms.
For eg:- enum identifier{v1,v2,v3,.....,vn}

7:-Operator:-An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulation. C has a wide range of operators. Operators aren used for comparison of values,
combination of logical states and manipulations of individual binary digits. Operators are perform on
operands. Eg:- Arithmetic operators(+.-,*,%),logical operators(&&,||,!),increment(++),decrement(--).

8:-Stream:- A stream is a sequence of characters. It is a sequence of bytes of data. The program sees
input/output as a continuos stream of bytes no matter where the input is coming from and going to. Every
stream is connected to a file.

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
9:-Prototype:- In computer programming, a function prototype or function interface is a declaration of a
function that specifies the function's name and type signature (arity, data types of parameters, and return
type), but omits the function body.
10:-C PREPROCESSOR DIRECTIVES: Before a C program is compiled in a compiler, source code is
processed by a program called preprocessor. This process is called preprocessing. Commands used in
preprocessor are called preprocessor directives and they begin with “#” symbol.

11:-Branching statements if,ifelse,nested if

12:-looping statement/decision making statement:- for, while,do while(diff between while and do while)

13:-Arrays:-A array is a series of elements of the same type palace in contiguous memory locations that
can be individually referenced by adding an index toa unique identifier. An array is a particular method of
storing elements of indexed data. Array is similar type of data collection name i.e.it is a collection of
same data type elements. A array is a group of related data items,which share common name.

14:-Strings:- Strings are defined as an array of characters or a pointer to a portion of memory containing
ASCII characters. A string in C is a sequence of zero or more characters followed by a NULL '\0'
character: It is important to preserve the NULL terminating character as it is how C defines and manages
variable length strings. All the C standard library functions require this for successful operation.
Example:- char *string_1 = "Hello";
char string_2[] = "Hello";
char string_3[6] = "HELLO";

15:-FUNCTION IN C:- A function in C language is a block of code that performs a specific task. It has a
name and it is reusable i.e it can be executed from many different parts in C program as required. It is a
set of independent statements, which can be utilised whenever it is required.
Features of functions are:- 1) Functions has unique name.
2) a function is independent and can be reused.
3)a function performs specific task.
4)a function returns value to the calling programs.
5) functions are more flexible than library functions.
6)Functions increased program speed.

16:-Recursion:- Recursion is the process of repeating items in a self-similar way. In programming


languages, if a program allows you to call a function inside the same function, then it is called
a recursive call of the function. this takes the form of a function that calls itself.

17:-Pointers:-A pointer is a programming language data type whose value refers directly to another value
stored elsewhere in computer memory using address. Pointers are memory addresses variables i.e

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
variables, which have addresses of variables having some values, stored in the memory. A pointer
references a location in memory and obtaining the value at the location a pointer refers to is known as
derefrencing the pointers.

18:Structure in c:- structure is another user defined data type available in C that allows to combine data
items of different kinds. To define a structure, you must use the struct statement. The struct statement
defines a new data type, with more than one member.
struct[structure tag]{

member definition;
member definition;
...
member definition;
}[one or more structure variables];
it is a complex data type declaration that defines a physically grouped list of variables to be placed under
one name in a block of memory, allowing the different variables to be accessed via a single pointer, or the
struct declared name which returns the same address.

19:-Unions:- A union is a special data type available in C that allows to store different data types in the
same memory location. You can define a union with many members, but only one member can contain a
value at any given time. Unions provide an efficient way of using the same memory location for
multiple-purpose. To define a union, you must use the union statement in the same way as you did while
defining a structure. The union statement defines a new data type with more than one member for your
program. The format of the union statement is as follows −

union[union tag]{
member definition;
member definition;
...
member definition;
}[one or more union variables];

You can define a union with many members, but only one member can contain a value at any given
time. Unions provide an efficient way of using the same memory location for multiple-purpose.

20:-File handling:-
File:-A file represents a sequence of bytes on the disk where a group of related data is stored. File is
created for permanent storage of data. It is a ready made structure.
C provides a number of functions that helps to perform basic file operations. Following are the functions,
DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
Function description

fopen() create a new file or open a existing file

fclose() closes a file

getc() reads a character from a file

putc() writes a character to a file

fscanf() reads a set of data from a file

fprintf() writes a set of data to a file

getw() reads a integer from a file

putw() writes a integer to a file

fseek() set the position to desire point

ftell() gives current position in the file

rewind() set the position to the begining point

Operations on file:-
1)Naming a file
2) Opening a file
3) reading data from file,writing data to file,
4) Closing a file
5)Updating a file

10Marks Questions:-

Q1:- Difference Between Compiler and Interpreter?


DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
No Compiler Interpreter

Interpreter
Compiler Takes Entireprogram
1 Takes Singleinstruction as
as input
input .

Intermediate Object Code No Intermediate Object Code


2
is Generated is Generated

Conditional Control
Conditional Control Statements
3 Statements are
are Executes faster
Executes slower

Memory
Memory
4 Requirement : More (Since
Requirement is Less
Object Code is Generated)

Every time higher level


Program need not
5 program is converted into
be compiled every time
lower level program

Errors are displayed


Errors are displayed after entire for every
6
program is checked instructioninterpreted (if
any)

7 Example : C Compiler Example : BASIC

Q2:- Explain datatypes in C? Explain its types?


Ans:-C data types are defined as the data storage format that a variable can store a data to perform a
specific operation. Data types are used to define a variable before to use in a program.

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
Character type

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
Character types are used to store characters value.
Size and range of Integer type on 16-bit machine

Type Size(bytes) Range

char or signed char 1 -128 to 127

unsigned char 1 0 to 255

void type
void type means no value. This is usually used to specify the type of functions.

Q3:-Define Operators? Explain its types along with example?


Ans:-Operators are the symbols which tell the computer to execute certain mathematical or logical
operations. A mathematical or logical expression is generally formed with the help of an operator.

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators

Arithmetic operators

The Arithmetic operators perform Arithmetic operations. The arithmetic operators can operate on any
built in data types. A list of arithmetic operator and their meaning are given below.

Operator Meaning
+ Addition or Unary plus
- Subtraction or Unary minus
* Multiplication

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
/ Division
% Modulo Division

Suppose that a and b are integer variables whose values are 100 and 4, respectively. Several arithmetic
expressions involving these variables are shown below, together with their resulting values.

Expression Value
a+b 104
a-b 96
a*b 400
a/b 25
a%b 0

Relational operators

Relational operators are used to compare, logical, arithmetic and character expression. Each of these six
relational operators takes two operands. Each of these operators compares their left side with their right
side.

Operator Meaning
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to

Suppose that a and b are integer variables whose values are 100 and 4, respectively. Several arithmetic
expressions involving these variables are shown below, together with their resulting values.

Expression Interpretation Value


a<b False 0
a>b True 1
a<=b False 0
a>=b True 1
a==b False 0
a!=b True 1

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
Logical operators

A Logical operator is used to compare or evaluate logical and relational expression. There are three
logical operators in C language. They are

Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT

Suppose that a and b are integer variables whose values are 100 and 4, respectively. Several arithmetic
expressions involving these variables are shown below, together with their resulting values.

Expression Interpretation Value


(a>b)&&(a==100) True 1
(b>a)||(a>b) True 1
!(a>b) False 0

Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ is as
follows −

p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume A = 60 and B = 13 in binary format, they will be as follows −

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011

Operator Description Example

& Binary AND Operator copies a bit to the result if it (A & B) =


exists in both operands. 12, i.e.,
0000 1100

| Binary OR Operator copies a bit if it exists in either (A | B) =


operand. 61, i.e.,
0011 1101

^ Binary XOR Operator copies the bit if it is set in one (A ^ B) =


operand but not both. 49, i.e.,
0011 0001

~ Binary Ones Complement Operator is unary and has (~A ) = -61,


the effect of 'flipping' bits. i.e,. 1100
0011 in 2's
complement
form.

<< Binary Left Shift Operator. The left operands value is A << 2 =
moved left by the number of bits specified by the 240 i.e.,
right operand. 1111 0000

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
>> Binary Right Shift Operator. The left operands value A >> 2 = 15
is moved right by the number of bits specified by the i.e., 0000
right operand. 1111

Assignment operator

An Assignment operator is used to form an assignment expression, which assigns the value to an
identifier.

The most commonly used assignment operator is = . Assignment expressions that make use of this
operator are written in the form <
Identifier=expression;
Example:
i=100;
j=200;

Other forms of assignment operator exist that are obtaining various operators such as +,-,*,/,% etc with
the = sign.

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
Q4:- Explain Decision statements with example?

Ans:-if - statements

If statement is a conditional branching statement. In conditional branching statement a


condition is evaluated, if it is evaluate true a group of statement is executed. The simple format of an if
statement is as follows:

if (expression)
statement;

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
If the expression is evaluated and found to be true, the single statement following the "if" is
executed. If false, the following statement is skipped.

if else statement:

This feature permits the programmer to write a single comparison, and then execute one of
the two statements depending upon whether the test expression is true or false. The general form of the if-
else statement is

if(expression)
statement1
else
statement2

Here also expression in parentheses must evaluate to (a boolean) true or false.

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
The syntax is

if(condition)
statement 1;
else if (condition)
statement 2;
.....................
.....................
else if(condition)
statement n-1;
else
statemens n ;

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
Q5:-Explain Switch Statement?
Ans:- Switch statement is used to solve multiple option type problems for menu like program, where one
value is associated with each option.

When the switch statement is executed, the expression in the switch statement is evaluated and the control
is transferred directly to the group of statements whose case label value matches the value of the
expression. Each group of statement ends with a break statement. The execution of break statement
causes immediate exit from the switch statement. if there is no match, then default block is executed.

Syntax of c switch statement is

Switch(expression)
case constant1:
statements 1;
break;
case constant2:
statements 2;
DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
break;
…………………..
default:
statements n;
break;
}

Program:

Q6:- Explain Jumping statements?


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

There are basically 3 Jumping statements:


1. break jumping statements.
2. continue jumping statements.
3. goto jumping statements.

1. break jumping 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.

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
WAP to display the following output:
1 2 3 4 5 . . . . .
#include<stdio.h>
#include<conio.h>
void main()
{
inti=1;
for(i=1;i<=10;i++)
{
printf(“Enter ”,i,”no”);
printf(“ \t %d ”,i);
if(i>5)
break;
}
}

continue jumping statements.

By using this jumping statement, we can terminate the further execution of the program and transfer the
control to the begining of any immediate loop.
WAP to display the following output:
1 2 3 4 . 6 7 . 9 10
#include<stdio.h>
#include<conio.h>
void main()
{
inti=1;
for(i=1;i<=10;i++)
{
printf(“Enter ”,i,”no”);
printf(“ \t %d ”,i);
if(i==5 || i==8)
continue;
}
}
goto jumping statements.
By using this jumping statements we can transfer the control from current location to anywhere in the
program.
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()
{
inti,n;
float s;
start:
printf(“Enter a no.”);
DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
scanf(“%d”,&n);
s=sqrt(n);
if(n<=0)
goto start;
printf(“%f”,s);
}

Q7:- Explain iteration/looping statements?

Ans:-For loop in C is the most general looping construct.

The loop header contains three parts: an initialization, a continuation condition, and step.

Syntax:
for (initialization, condition, step)
{
Statement 1;
Statement 2;
…………...
Statement n;
}

Example: The following example executes 10 times by counting


0………..9
#include<conio.h>
#include<conio.h>
Void main()
{
inti;
for (i = 0; i< 10; i++);
{ printf(“/n %d”,i);
i++;
}
getch();}

While loop

The while statement is also a looping statement. The while loop evaluates the test expression before every
loop, so it can execute zero times if the condition is initially false. It has the following syntax.

while (expression)
{
DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
Statement 1;
Statement 2;
…………...
Statement n;
}

do-while loop

This construct is also used for looping. In this case the loop condition is tested at the end of the body of
the loop. Hence the loop is executed at least one.

Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in C
programming checks its condition at the bottom of the loop.
Syntax

The syntax of a do...while loop in C programming language is −

do {
statement(s);
} while( condition );

Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop
executes once before the condition is tested.

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop executes
again. This process repeats until the given condition becomes false.

Program:-

#include<conio.h>

#include<stdio.h>

Void main()

{
inti=1;

Do

printf(“\n %d”,i);

i++;

}while(i<=10);

getch();}

Q8:- What are arrays? Give its advantages? Explain its types?
Ans:- Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the
same type. An array is used to store a collection of data, but it is often more useful to think of an array as
a collection of variables of the same type. All arrays consist of contiguous memory locations. The lowest
address corresponds to the first element and the highest address to the last element.

Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of elements
required by an array as follows −

type arrayName [ arraySize ];

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
Initializing Arrays
You can initialize an array in C either one by one or using a single statement as follows −

double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};

Advantages of arrays:

It is capable of storing many elements at a time

It allows random accessing of elements i.e. any element of the array can be randomly accessed
using indexes.

TYPES OF C ARRAYS:

There are 2 types of C arrays:-

1.One dimensional array


2.Two dimensional array

One D-Array:-
Example:-
#include<stdio.h>
#include<conio.h>
Void main()
{
int a[10],n;
printf(“enter the number of elements”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
Printf(“enter element”);
Scanf(“%d”,&a[i]);
}
Printf(“\n Entered Array is:-“);
for(i=1;i<=n;i++)
{
printf(“ \n %d”,a[i]);
}
getch();
}

Two D-array:-

Initialization of 2-D arrays:


intdisp[2][4] = {
{10, 11, 12, 13},
{14, 15, 16, 17}
};
DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
#include<stdio.h>
#include<conio.h>
Void main()
{
intr,c,i,j,a[10][10];

printf(“ Enter the number of rows and columns”);


scanf(“%d%d”,&r,&c);

for(i=1;i<=r;i++)
{
for(j=1;j<=c;j++)
{
printf(“enter the element”);
scanf(“%d”,&a[i][j]);
}
}
for(i=1;i<=r;i++)
{
for(j=1;j<=c;j++)
{
printf(“entered elements are:- %d ”, a[i][j]);
}
Printf(“\n”);
}
getch();
}

Q9:-Expalin Strings? Explain manipulate string function in the form of arrays?

Ans:- Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus a
null-terminated string contains the characters that comprise the string followed by a null.
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

Following is the memory presentation of the above defined string in C. −

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
Example Program:-
#include <stdio.h>

int main () {

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};


printf("Greeting message: %s\n", greeting );
return 0;
}

String Functions:-

S.N. Function & Purpose

1
strcpy(s1, s2);

Copies string s2 into string s1.

2
strcat(s1, s2);

Concatenates string s2 onto the end of string s1.

3
strlen(s1);

Returns the length of string s1.

4
strcmp(s1, s2);

Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
s1>s2.

5
strchr(s1, ch);

Returns a pointer to the first occurrence of character ch in string s1.

6
strstr(s1, s2);

Returns a pointer to the first occurrence of string s2 in string s1.

Example:-

#include <stdio.h>
#include <string.h>

int main () {
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12];
intlen ;

/* copy str1 into str3 */


strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );

/* concatenates str1 and str2 */


strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );

/* total lenghth of str1 after concatenation */


len = strlen(str1);
printf("strlen(str1) : %d\n", len );
return 0;
}

Q10:- Explain the concept of pointers? How to initialize and declare pointers? Explain null
pointer?

Ans:-Pointers in C are easy and fun to learn. Some C programming tasks are performed more easily with
pointers, and other tasks, such as dynamic memory allocation, cannot be performed without using
DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
pointers. So it becomes necessary to learn pointers to become a perfect C programmer. Let's start learning
them in simple and easy steps.As you know, every variable is a memory location and every memory
location has its address defined which can be accessed using ampersand (&) operator, which denotes an
address in memory.

The general form of a pointer variable declaration is –

type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the
pointer variable. The asterisk * used to declare a pointer is the same asterisk used for multiplication.
However, in this statement the asterisk is being used to designate a variable as a pointer.

Example:-
int *ip;

Example Program:-
#include <stdio.h>

int main () {

intvar = 20; /* actual variable declaration */


int *ip; /* pointer variable declaration */

ip = &var; /* store address of var in pointer variable*/

printf("Address of var variable: %x\n", &var );

/* address stored in pointer variable */


printf("Address stored in ip variable: %x\n", ip );

/* access the value using the pointer */


printf("Value of *ip variable: %d\n", *ip );

return 0;
}
NULL Pointers
It is always a good practice to assign a NULL value to a pointer variable in case you do not have an
exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned
NULL is called a null pointer.The NULL pointer is a constant with a value of zero defined in several
standard libraries. Consider the following program –

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

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr );
return 0;
}
OUTPUT:- The value of ptr is 0

Q11Explain function in C? Explain its types?

Ans:-A function is a group of statements that together perform a task. Every C program has at least one
function, which is main(), and all the most trivial programs can define additional functions. A
function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function.
A function can also be referred as a method or a sub-routine or a procedure, etc.
Defining a Function
The general form of a function definition in C programming language is as follows −

return_typefunction_name( parameter list ){


body of the function
}

Function Declarations
A function declaration tells the compiler about a function name and how to call the function. A function
declaration has the following parts:-

return_typefunction_name( parameter list );

Categories of Functions:-

 Function with no arguments and no return value


 Function with no arguments and a return value
 Function with arguments and no return value
 Function with arguments and a return value.

1)Functions with no argument and no return value:-

Sub function does not have any parameters and they do not return any value to main function.

#include<conio.h>
#include<stdio.h>
#void Add();
Void main()
DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
{
Clrscr();
Add();
getch();
}

Void Add()
{
Inta,b,c;
printf(“enter the value of a and b”);
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“the sum of two numbers = %d”,c);
}

2)Function with no arguments and a return value

Sub function does not have any parameters and they return value to main function.

#include<conio.h>
#include<stdio.h>
#int Add();
Void main()
{ int z;
Clrscr();
z=Add();
printf(“the sum of two numbers = %d”,z);
getch();
}

int Add()
{
Inta,b,c;
printf(“enter the value of a and b”);
scanf(“%d%d”,&a,&b);
c=a+b;
return(c);
}

3)Function with arguments and no return value

Sub function has list of parameters and they do not return any value to main function.

#include<conio.h>
#include<stdio.h>
#void Add(int,int);
DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
Void main()
{
inta,b;
Clrscr();
printf(“enter the value of a and b”);
scanf(“%d%d”,&a,&b);
Add(a,b);
getch();
}

Void Add(int x, int y)


{
int c;
c=x+y;
printf(“the sum of two numbers = %d”,c);
}

4)Function with arguments and a return value.

Sub function has list of parameters and they return a value to main function.

#include<conio.h>
#include<stdio.h>
#int Add(int,int);
Void main()
{
inta,b,z;
Clrscr();
printf(“enter the value of a and b”);
scanf(“%d%d”,&a,&b);
z=Add(a,b);
printf(“the sum of two numbers = %d”, z);
getch();
}

Void Add(int x,int y)


{
int c;
c=x+y;
return(c);
}

Q12:- Explain structures in C?

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
Ans:-A struct in the C programming language (and many derivatives) is a complex data type declaration
that defines a physically grouped list of variables to be placed under one name in a block of memory,
allowing the different variables to be accessed via a single pointer, or the struct declared name which
returns the same address. The struct can contain many other complex and simple data types in an
association, so is a natural organizing type for records like the mixed data types in lists of directory
entries reading a hard drive (file length, name, extension, physical (cylinder, disk, head indexes) address,
etc.), or other mixed record type (patient names, address, telephone... insurance codes, balance, etc.).
Defining a Structure
struct [structure tag] {

member definition;
member definition;
...
member definition;
} [one or more structure variables];

#include <stdio.h>
#include <string.h>

struct Books {
char title[50];
char author[50];
char subject[100];
intbook_id;
};

int main( ) {

struct Books Book1; /* Declare Book1 of type Book */


struct Books Book2; /* Declare Book2 of type Book */

/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;

/* print Book1 info */


printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 subject : %s\n", Book1.subject);
printf( "Book 1 book_id : %d\n", Book1.book_id);

/* print Book2 info */


printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
printf( "Book 2 subject : %s\n", Book2.subject);
printf( "Book 2 book_id : %d\n", Book2.book_id);

return 0;
}

OUTPUT:-

Book 1 title : C Programming


Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700

Q13:-Explain Unions in C? Difference between Structure and Union?

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
Ans:-A union is a special data type available in C that allows to store different data types in the same
memory location. You can define a union with many members, but only one member can contain a value
at any given time. Unions provide an efficient way of using the same memory location for multiple-
purpose.
Defining a Union
union[union tag]{
member definition;
member definition;
...
member definition;
}[one or more union variables];

#include <stdio.h>
#include <conio.h>

union item
{
int a;
float b;
char ch;
};

int main( )
{
union item it;
it.a = 12;
it.b = 20.2;
it.ch='z';
clrscr();
printf("%d\n",it.a);
printf("%f\n",it.b);
printf("%c\n",it.ch);
getch();
return 0;
}

OUTPUT:-
-26426
20.1999
z
DIFFERENCE BETWEEN STRUCTURE AND UNION IN C:
C Structure C Union

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
Union allocates one common storage
space for all its members.
Structure allocates Union finds that which of its
storage space for all its member needs high storage space
members separately. over other members and allocates
that much space

Structure occupies Union occupies lower memory space


higher memory space. over structure.

We can access all


members of structure at We can access only one member of
a time. union at a time.

Structure example: Union example:


struct student union student
{ {
int mark; int mark;
char name[6]; char name[6];
double average; double average;
}; };

Q14:-Explain the concept of Recursion? WAP for factorial with recursion?

Ans:-Recursion is the process of repeating items in a self-similar way. In programming languages, if a


program allows you to call a function inside the same function, then it is called a recursive call of the
function. this takes the form of a function that calls itself.
Program to find factorial of a number using recursion:-

#include<stdio.h>
int fact(int);
int main(){
int num,f;
printf("\nEnter a number: ");
scanf("%d",&num);
f=fact(num);
printf("\nFactorial of %d is: %d",num,f);
return 0;
}

int fact(int n){


if(n==1)
return 1;
else
return(n*fact(n-1));
}

Q15:- Explain the concept of File Handling in C along with example?

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
Ans:- File:-A file represents a sequence of bytes on the disk where a group of related data is stored. File
is created for permanent storage of data. It is a ready made structure.
C provides a number of functions that helps to perform basic file operations. Following are the functions,

Function description

fopen() create a new file or open a existing file

fclose() closes a file

getc() reads a character from a file

putc() writes a character to a file

fscanf() reads a set of data from a file

fprintf() writes a set of data to a file

getw() reads a integer from a file

putw() writes a integer to a file

fseek() set the position to desire point

ftell() gives current position in the file

rewind() set the position to the begining point

Operations on file:-
1)Naming a file
2) Opening a file
3) reading data from file,writing data to file,

Writing to a text file

#include<stdio.h>
int main()
DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
{
intnum;
FILE *fptr;
fptr = fopen("C:\\program.txt","w");

if(fptr == NULL)
{
printf("Error!");
exit(1);
}

printf("Enter num: ");


scanf("%d",&num);

fprintf(fptr,"%d",num);
fclose(fptr);

return0;
}

This program takes a number from user and stores in the file program.txt.After you compile and run this
program, you can see a text file program.txt created in C drive of your computer. When you open the file,
you can see the integer you entered.

Reading from a text file

#include<stdio.h>
int main()
{
intnum;
FILE *fptr;

if ((fptr = fopen("C:\\program.txt","r")) == NULL){


printf("Error! opening file");

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
// Program exits if the file pointer returns NULL.
exit(1);
}

fscanf(fptr,"%d",&num);

printf("Value of n=%d",num);
fclose(fptr);

return0;
}

This program reads the integer present in the program.txt file and prints it onto the screen.

Q16:- Explain the concept of Daynamic Memory Allocation?

Ans:- In C, the exact size of array is unknown until compile time, i.e., the time when a compiler compiles
your code into a computer understandable language. So, sometimes the size of the array can be
insufficient or more than required. Dynamic memory allocation allows your program to obtain more
memory space while running, or to release it if it's not required. Dynamic memory allocation allows you
to manually handle memory space for your program.

Function Use of Function

malloc() Allocates requested size of bytes and returns a pointer first byte of allocated space

calloc() Allocates space for an array elements, initializes to zero and then returns a pointer to memory

free() deallocate the previously allocated space

realloc() Change the size of previously allocated space

malloc()
malloc stands for "memory allocation". The function malloc() reserves a block of memory of specified
size and return a pointer of type void which can be casted into pointer of any form.
DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
Syntax:-

ptr = (cast-type*) malloc(byte-size)

Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size of
byte size. If the space is insufficient, allocation fails and returns NULL pointer.
Example:-ptr = (int*) malloc(100 * sizeof(int));

calloc()
calloc stands for "contiguous allocation". The only difference between malloc() and calloc() is that,
malloc() allocates single block of memory whereas calloc() allocates multiple blocks of memory each of
same size and sets all bytes to zero.
Syntax

ptr = (cast-type*)calloc(n, element-size);

This statement will allocate contiguous space in memory for an array of nelements. For example:

ptr = (float*) calloc(25, sizeof(float));

free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on its own. You
must explicitly use free() to release the space.
Syntax:-

free(ptr);

realloc()
If the previously allocated memory is insufficient or more than required, you can change the previously
allocated memory size using realloc().

Syntax

ptr = realloc(ptr, newsize);

Here, ptr is reallocated with size of newsize.


DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
Example:-

#include<stdio.h>
#include<stdlib.h>

int main()
{
intnum, i, *ptr, sum = 0;

printf("Enter number of elements: ");


scanf("%d", &num);

ptr = (int*) malloc(num * sizeof(int)); //memory allocated using malloc


if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}

printf("Enter elements of array: ");


for(i = 0; i<num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}

printf("Sum = %d", sum);


free(ptr);
return0;
}

Q17:- Expalin storage classes in c?

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
Ans:- Every C variable has a storage class and a scope. The storage class determines the part of memory
where storage is allocated for an object and how long the storage allocation continues to exist. It also
determines the scope which specifies the part of the program over which a variable name is visible, i.e.
the variable is accessible by name. The are four storage classes in C are automatic, register, external, and
static.In C language, each variable has a storage class which decides scope, visibility and lifetime of that
variable. The following storage classes are most oftenly used in C programming,
1)Automatic variables:- A variable declared inside a function without any storage class specification, is
by default an automatic variable. They are created when a function is called and are
destroyed automatically when the function exits. Automatic variables can also be called local variables
because they are local to a function. By default they are assigned garbage value by the compiler.
void main()
{
int detail;
or
auto int detail; //Both are same
}

2)External variables:-
A variable that is declared outside any function is a Global variable. Global variables remain available
throughout the entire program. One important thing to remember about global variable is that their values
can be changed by any function in the program.
int number;
void main()
{
number=10;
}
fun1()
{
number=20;
}
fun2()
{
number=30;
}

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
3)Static variables:-
A static variable tells the compiler to persist the variable until the end of program. Instead of creating and
destroying a variable every time when it comes into and goes out of scope, static is initialized only once
and remains into existence till the end of program. A static variable can either be internal or external
depending upon the place of declaraction. Scope of internal static variable remains inside the function in
which it is defined. External static variables remain restricted to scope of file in each they are declared.
They are assigned 0 (zero) as default value by the compiler.
void test(); //Function declaration (discussed in next topic)

main()
{
test();
test();
test();
}
void test()
{
static int a = 0; //Static variable
a = a+1;
printf("%d\t",a);
}
output :
1 23

4)Register variables:-Register variable inform the compiler to store the variable in register instead
of memory. Register variable has faster access than normal variable. Frequently used variables are
kept in register. Only few variables can be placed inside register.
Syntax :
register int number;

Q18:- Explain Linked List? Explain its Traversal?


DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
Ans:-A linked list is a sequence of data structures, which are connected together via links. Linked List is a

sequence of links which contains items. Each link contains a connection to another link. Linked list is the

second most-used data structure after array.


Linked lists have a few advantages over arrays:

1. Items can be added or removed from the middle of the list


2. There is no need to define an initial size

Code for traversal in linked list..

void traverseList(Node *head){


Node * current = head;
while(current){
printf("%d", current->data);
current = current->next;
}
}

Q19 Difference between Call By Value and Call by Refrence?


Ans:-
No. Call by value Call by reference

1 A copy of value is passed to the function An address of value is passed to the function

2 Changes made inside the function is not Changes made inside the function is
reflected on other functions reflected outside the function also

3 Actual and formal arguments will be created Actual and formal arguments will be created
in different memory location in same memory location

4 In this method the value of variable is passed In this method the address of variable is
as an argument. passed as an argument.

5 It is a default method of argument passing. Programmer has to specify this method.

6 This method is slow. This method is fast.

7 Arguments are received in simple variable in Arguments are received in pointer type
function. variable in function.

8 Example:- int swap(int x, int y) Example:- int add(int * x, int *y)

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
{ { body of function”
Body of function}

Programs:-

C program to check odd or even


include <stdio.h>

int main()
{
int n;

printf("Enter an integer\n");
scanf("%d", &n);

if (n%2 == 0)
printf("Even\n");
else
printf("Odd\n");

return 0;
}

C program to perform addition, subtraction, multiplication and division


#include <stdio.h>

int main()
{
int first, second, add, subtract, multiply;
float divide;

printf("Enter two integers\n");


scanf("%d%d", &first, &second);

add = first + second;


subtract = first - second;
multiply = first * second;
divide = first / (float)second; //typecasting

printf("Sum = %d\n",add);
printf("Difference = %d\n",subtract);
printf("Multiplication = %d\n",multiply);
printf("Division = %.2f\n",divide);

return 0;
DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
}

C program to check leap year


#include <stdio.h>

int main()
{
int year;

printf("Enter a year to check if it is a leap year\n");


scanf("%d", &year);

if ( year%4 == 0)
printf("%d is a leap year.\n", year);
else
printf("%d is not a leap year.\n", year);

return 0;
}

Add digits of number in c

#include <stdio.h>

int main()
{
int n, t, sum = 0, remainder;

printf("Enter an integer\n");
scanf("%d", &n);

t = n;

while (t != 0)
{
remainder = t % 10;
sum = sum + remainder;
t = t / 10;
}

printf("Sum of digits of %d = %d\n", n, sum);

return 0;
}

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
Swapping of two numbers using 3rd variable in c

#include <stdio.h>

int main()
{
int x, y, temp;

printf("Enter the value of x and y\n");


scanf("%d%d", &x, &y);

printf("Before Swapping\nx = %d\ny = %d\n",x,y);

temp = x;
x = y;
y = temp;

printf("After Swapping\nx = %d\ny = %d\n",x,y);

return 0;
}

Swapping of two numbers without third variable


#include <stdio.h>

int main()
{
int a, b;

printf("Enter two integers to swap\n");


scanf("%d%d", &a, &b);

a = a + b;
b = a - b;
a = a - b;

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


return 0;
}

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
C program to reverse a number

#include <stdio.h>

int main()
{
int n, reverse = 0;

printf("Enter a number to reverse\n");


scanf("%d", &n);

while (n != 0)
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}

printf("Reverse of entered number is = %d\n", reverse);

return 0;
}

Palindrome number program c

#include <stdio.h>

int main()
{
int n, reverse = 0, temp;

printf("Enter a number to check if it is a palindrome or not\n");


scanf("%d",&n);

temp = n;

while( temp != 0 )
{
reverse = reverse * 10;
reverse = reverse + temp%10;
temp = temp/10;
}

if ( n == reverse )
printf("%d is a palindrome number.\n", n);
else
printf("%d is not a palindrome number.\n", n);

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
return 0;
}

C program to print first 10 prime number

#include<stdio.h>

int main()
{
int n, i = 3, count, c;

printf("Enter the number of prime numbers required\n");


scanf("%d",&n);

if ( n >= 1 )
{
printf("First %d prime numbers are :\n",n);
printf("2\n");
}

for ( count = 2 ; count <= n ; )


{
for ( c = 2 ; c <= i - 1 ; c++ )
{
if ( i%c == 0 )
break;
}
if ( c == i )
{
printf("%d\n",i);
count++;
}
i++;
}

return 0;
}

C program for prime number or not

main()
{
int n, c = 2;

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
printf("Enter a number to check if it is prime\n");
scanf("%d",&n);

for ( c = 2 ; c <= n - 1 ; c++ )


{
if ( n%c == 0 )
{
printf("%d is not prime.\n", n);
break;
}
}
if ( c == n )
printf("%d is prime.\n", n);

return 0;
}

Fibonacci series in c using for loop

#include<stdio.h>

int main()
{
int n, first = 0, second = 1, next, c;

printf("Enter the number of terms\n");


scanf("%d",&n);

printf("First %d terms of Fibonacci series are :-\n",n);

for ( c = 0 ; c < n ; c++ )


{
if ( c <= 1 )
next = c;
else
{
next = first + second;
first = second;
second = next;
}
printf("%d\n",next);
}

return 0;
}

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
C program to find maximum element in array

#include <stdio.h>

int main()
{
int array[100], maximum, size, c, location = 1;

printf("Enter the number of elements in array\n");


scanf("%d", &size);

printf("Enter %d integers\n", size);

for (c = 0; c < size; c++)


scanf("%d", &array[c]);

maximum = array[0];

for (c = 1; c < size; c++)


{
if (array[c] > maximum)
{
maximum = array[c];
location = c+1;
}
}

printf("Maximum element is present at location %d and it's value is %d.\n", location, maximum);
return 0;
}

C program to find minimum element in array

#include <stdio.h>

int main()
{
int array[100], minimum, size, c, location = 1;

printf("Enter the number of elements in array\n");


scanf("%d",&size);

printf("Enter %d integers\n", size);


DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
for ( c = 0 ; c < size ; c++ )
scanf("%d", &array[c]);

minimum = array[0];

for ( c = 1 ; c < size ; c++ )


{
if ( array[c] < minimum )
{
minimum = array[c];
location = c+1;
}
}

printf("Minimum element is present at location %d and it's value is %d.\n", location, minimum);
return 0;
}

C program to calculate net salary from basic salary

#include <stdio.h>

#include<conio.h>

main()

clrscr();

float basic_salry, da, hra, pf, gross_salry, net_salry;

printf("\nEnter the Basic Salary of the Employee: Rs. = ");

scanf("%f" , &basic_salry);

da = (basic_salry * 25)/100;

hra = (basic_salry * 15)/100;

gross_salry = basic_salry + da + hra;

pf = (gross_salry * 10)/100;

net_salry = gross_salry - pf;

printf("\n\nNet Salary: Rs. = %.2f", net_salry);

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
getch();

C program to enter 5 digit number reverse the number and find its sum

# include <stdio.h>

# include <conio.h>

main()

intn,m;

int sum=0;

int rev=0;

clrscr();

printf("Enter 5 digit no");

scanf("%d",&n);

while(n>0)

m = n%10;

sum+=m;

rev=rev*10+m;

n=n/10;

printf("The sum of the digits is :%d",sum);

printf("the reverse of the no is %d",rev);

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400
getch();

DORIC MULTIMEDIA PVT LTD BRANCH JAMALPUR Ph.No. 0161-5044300 CMC BRANCH Ph.No. 0161-5050400

You might also like