KEMBAR78
Basic Computer Programming (4310702) | PDF | Data Type | Computer Program
0% found this document useful (0 votes)
34 views84 pages

Basic Computer Programming (4310702)

Uploaded by

niwikox151
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)
34 views84 pages

Basic Computer Programming (4310702)

Uploaded by

niwikox151
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/ 84

Subject Name: Basic Computer Programming Unit No: 01 Subject Code: 4310702

UNIT: 1
Flowchart and Algorithm
 Flowchart
Definition and Importance of flowchart:
Flowchart: Flowchart is Graphical or Pictorial Representation of problem.

 Importance (Advantages) of Flowchart:


1.Flowcharts are better way of communicating the logic of the system.
2.Using Flowchart it is easy to analyze Problem.
3.The flowcharts are very useful during program development phase.
4.Flowchart represents problem solution using different standard Symbol.
5.It provides a good communication interface between programmer and user.
6.It helps in debugging and testing process.

 Symbols of flowchart:

1.Terminal:
o This Symbol is used for the Starting and Ending Process of Flowchart.

2.Input / Output
o This Symbol is used for Receiving input Data From user and displaying output to the user

3.Process
o This Symbol is used for Computing.
o It is Use for Some Arithmetic Calculation.

4.Decision Making
o This Symbol is used for making decision base on Condition.
o This Symbol has one incoming arrow for entry and Two outgoing arrow.

Prepared By: Department of Computer Engineering Page 1


Subject Name: Basic Computer Programming Unit No: 01 Subject Code: 4310702

5.Subroutine
o This Symbol is used for user defined function or sub program.

6.Flow / Direction
o Flow line Symbol.
o This Symbol Indicates flow of data from one Symbol to Another Symbol.

7.Page Break
o When flowchart is do not fit into single page then Page Break and Page Continue Symbol is
used.
o Page Break Symbol Indicate break in current page.

8.Page Continue
o Page Continue Symbol Indicate Continue flowchart in another page.

 Guidelines for preparing Flowchart:


1. Standard symbols should be used while drawing flowchart.
2. Ensure that flowchart has START (or BEGIN) and STOP (or END).
3. Flowchart should be neat, clean and easy to follow. There should be no any ambiguity.
4. The usual direction of flowchart is from top to bottom or from left to right.
5. The terminal symbol, that is, START/BEGIN or STOP/END should have only one flow line.
6. Only one flow line should come out from process symbol.
7. Only one flow line should enter a decision symbol.

 Flowchart structure: Sequence, selection, repetition:


1. Sequence
Steps that execute in sequence are represented by symbols that follow each other top to
bottom or left to right. Top to bottom is the standard.

Prepared By: Department of Computer Engineering Page 2


Subject Name: Basic Computer Programming Unit No: 01 Subject Code: 4310702

2. Selection
Once the condition is evaluated, the control flows into one of two paths.

3. Repetition
Either the processing repeats or the control leaves the structure.

 Limitation of flowchart:

1.Complex Logic: It is very difficult to draw a flowchart for very hard and complex problem
2.Difficulty in Modifications: If a minor change is required then it is difficult to change flowchart
and may be required to redraw flowchart again.
3.Difficult to understand for people who don't know flowchart symbols.

 Definition and Importance of Algorithm:


Algorithm: Algorithm is stepwise solution of any problem or program.

Prepared By: Department of Computer Engineering Page 3


Subject Name: Basic Computer Programming Unit No: 01 Subject Code: 4310702

Importance (advantages) of Algorithm:


1. It is a step-wise representation of a solution to a given problem, which makes it easy to understand.
2. An algorithm uses a definite procedure.
3. It is not dependent on any programming language, so it is easy to understand for anyone even without
programming knowledge.
4. Every step in an algorithm has its own logical sequence so it is easy to debug.
5. By using algorithm, the problem is broken down into smaller pieces or steps, so it is easier for
programmer to convert it into an actual program.

Limitation of Algorithm
1. An algorithm is Time consuming. Developing algorithm for complex problems would be time
consuming and difficult to understand.
2. Understanding complex logic through algorithms can be very difficult.
3. Difficult to show Branching and Looping in Algorithms.
4. Big tasks are difficult to put in Algorithms.

Examples:
Flowchart and algorithm to calculate area of circle.
Flowchart:

Prepared By: Department of Computer Engineering Page 4


Subject Name: Basic Computer Programming Unit No: 01 Subject Code: 4310702

Algorithm:

1. START
2. INPUT: r
3. Calculate: Area= 3.14 * r *r
4. PRINT: Area
5. STOP

 Developing and writing algorithm using pseudo codes:

Pseudo code:
Pseudo code is not a programming language; it is a simple way of describing a set of instructions that
does not have to use specific syntax.

Example:

If student's grade is greater than or equal to 60

Print "passed"

else

Print "failed"

Prepared By: Department of Computer Engineering Page 5


Subject Name: Basic Computer Programming Unit No: 02 Subject Code: 4310702

UNIT: 2
Basics of ‘C’
 General structure of ‘C’ program:

Documentation section

Header File

Constants and Global variables Declaration

main () function section

Statement(s);

User Defined functions and procedures with their body

Fig:structure of ‘C’ program

Documentation section:

 Documentation consists of a set of comment line(/* */) giving the name of the program.

Header File(Link Section):

 Link section provides instruction to the compiler to link function from the system library(Header
Files like #include<stdio.h>).

Constant Declaration:

 Definition section defines all symbolic constants


Ex: #define PI 3.14

Global declaration section:

 There are some variable that are used more than one function. Such Variables are called global
variable and that is outside all the function.

main () function section:

Prepared By: Department of Computer Engineering Page 1


Subject Name: Basic Computer Programming Unit No: 02 Subject Code: 4310702

 Every c program must have one main () function section.


 This section contains two parts. Declaration part and executable part.
 Declaration part declares all the variables used in the executable part.
 These two parts must be appearing between opening and closing braces.

User Defined functions and procedures:


 The subprogram section contains all the user defines functions that are called in the main function.

Features of C language:

1) C is portable.
„C‟ Program can be run on any hardware.

2) C supports variety of built-in functions.(library functions printf() and scanf() )

3) C supports bitwise operators.


The C support bitwise operator like AND, OR, NOT etc. normally these operations do not supported by
higher level languages.

4) C is modular language.
The program written in from of functions. A C program is group of one or more functions. Dividing the
program into small functions makes it to easy develop and maintain the programs.

5) C is Robust language.

 Character set:
In the C programming language, the character set refers to a set of all the valid characters that we can
use in the source program for forming words, expressions, and numbers.
There are four type of character set in C programming.

 Alphabets - Upper case A-Z , Lower case a-z


 Digit- 0-9
 Special Character - %,&,*,etc.
 White space

 ‘C’ tokens, keyword and identifiers


 C Token : The smallest individual unit in a C program is known as C token.
C has six types of token as given below:
 Keywords (float,while)
 Identifier(main,amount)
 Constants(-15.2, 10)
 String(“abc”, “hello”)
 Special Symbols ([ , ] , *, ! etc)
 Operators (+,-, *,/)

Prepared By: Department of Computer Engineering Page 2


Subject Name: Basic Computer Programming Unit No: 02 Subject Code: 4310702

 Keyword:
Keywords are those words whose meaning is predefined.
 The programmer cannot change the meaning of keywords.
 There are 32 keywords available in c.
 All the keywords must be written in lowercase.
 Examples:

int if float while

 Identifiers:
 Identifier is the words which are defined by the programmer in a program.
 Identifier refers to the name of variable, array, function etc.
 It consists of letters, digits and underscore.
 First character must be an alphabet or underscore.
 Keywords cannot be use as identifier.
 Identifier name are case sensitive.
 The name of identifier should be meaningful.

 Data Types in ‘C’:


Primary (basic) data type with size and range:

Data type is used to specify which type of value to be stored in variable.

Type Size(Bytes) Size(Bits) Range


char 1 8 -128 to +128
int 2 16 -32768 to +32767
float 4 32 3.4 e -38 to 3.4 e +38
double 8 64 1.7 e -308 to 1.7 e +308

 Variable
A variable is a name which is used to store a temporary value.

Rules of variables Naming:


 The variable name may consist of letters (A-Z, a-z), digits (0-9) and underscore symbol ( _ ).
Example: int no_1; int no1; int NO1;
 The variable name must begin with a letter. Some system permits underscore as a first character.
Example: int 1NO; is not valid

 The length should not be more than eight characters.

 Variable name should not be a keyword.


Prepared By: Department of Computer Engineering Page 3
Subject Name: Basic Computer Programming Unit No: 02 Subject Code: 4310702

Example: int case is not valid


 A white space is not allowed in the name of variable.
Example: int NO 1; is not valid.
 Variable is case sensitive. Uppercase and lowercase are different.
Example: int MAX; int max;
Here both MAX and max are treated as different variable.

 constant variable:

 Constant means fixed value.


 If the value of a variable remain constant during the execution of a program, the we can declare the
variable with const at the time of initialization.

Syntax: const DataType ConstantName

Example: const float PI = 3.14;

 Introduction of different types of operators :


Operators in C

1) Arithmetic operator
2) Relational operator
3) Logical operator
4) Assignment operator
5) Increment and decrement operator
6) Conditional (ternary)operator
7) Bitwise operator
8) Special operator

Arithmetic operator :

 +, -, *, /, % are arithmetic operators.


 +, -, *, / are used with any data type.
 % is used only with integer type.

Arithmetic Operators:

1) Binary plus(+):
 It add two operands.
 Example :a+b
2) Binary minus(-):
 It subtracts two operands.
 Example :a-b
3) Multiplication(*):
Prepared By: Department of Computer Engineering Page 4
Subject Name: Basic Computer Programming Unit No: 02 Subject Code: 4310702

 It multipliers two operands


 Example :a*b
4) Division(/) :
 It divides one operand by another operand.
 Example: a/b
5) Modulo operator (%):
 It divides one operand by another operand and produce reminder of the division.
 Example :a%b
Now assume that a=5 and b=2 then

1) a+b =7
2) a-b =3
3) a*b =10
4) a/b =2
5) a%b =1

Relational operator:

Relational operators are used for comparisons.

i) Equal to(= =)
It compares two operands and return TRUE (1) if both operands are equal.
ii) Not equal to (! =)
It compares two operands and return TRUE (1) if both operands are not equal.
iii) Less than(<)
It compares two operands and return TRUE (1) if operand1 is less than operand2.
iv) Less than equal to(<=)
It compares two operands and return TRUE (1) if operand1 is less than or equal to operand2.
v) Greater than(>)
It compares two operands and return TRUE (1) if operand1 is greater than operand2.
vi) Greater than equal to(>=)
It compares two operands and return TRUE (1) if operand1 is greater than or equal to operand2.
Examples:

Suppose a=5, b=7

1) a= =b false
2) a!=b true
3) a<b true
4) a<=b true
5) a>b false
6) a>=b false

Assignment Operator:

Prepared By: Department of Computer Engineering Page 5


Subject Name: Basic Computer Programming Unit No: 02 Subject Code: 4310702

Operator Description Example

= Simple assignment operator. Assigns values from C = A + B will assign


right side operands to left side operand the value of A + B to C

+= Add AND assignment operator. It adds the right


C += A is equivalent to
operand to the left operand and assign the result
C=C+A
to the left operand.

-= Subtract AND assignment operator. It subtracts


C -= A is equivalent to C
the right operand from the left operand and
=C-A
assigns the result to the left operand.

*= Multiply AND assignment operator. It multiplies


C *= A is equivalent to
the right operand with the left operand and
C=C*A
assigns the result to the left operand.

/= Divide AND assignment operator. It divides the


C /= A is equivalent to C
left operand with the right operand and assigns
=C/A
the result to the left operand.

%= Modulus AND assignment operator. It takes


C %= A is equivalent to
modulus using two operands and assigns the
C =C%A
result to the left operand.

Logical operator:

 Logical operators are used when we want to combine more than one condition.

Logical AND &&

Logical OR ||

Logical NOT !
1)

Logical AND(&&)
 The truth table logical AND (&&) operator is given below:
Condition 1 Condition 2 Answer

False False False

False True False

Prepared By: Department of Computer Engineering Page 6


Subject Name: Basic Computer Programming Unit No: 02 Subject Code: 4310702

True False False

True True True

Logical OR( || )
 The truth table logical OR ( || ) operator is given below:
Condition 1 Condition 2 Answer

False False False

False True True

True False True

True True True

Logical NOT (!):


 The truth table logical NOT (!) operator is given below:
Condition Answer

False True

True False

 Examples :
Suppose a=5, b=3, c=6;

1) (a>b) && (a>c) - false


2) (a>b) || (a>c) - true
3) !(a>b) - false

Increment and decrement operator:

Increment Operators are the unary operators used to increment or add 1 to the operand value.
The Increment operand is denoted by the double plus symbol (++).
It has two types, Pre Increment and Post Increment Operators.

Pre-increment Operator:
The pre-increment operator is used to increase the original value of the operand by 1 before assigning it
to the expression.
X = ++A;
In the above example, the value of operand 'A' is increased by 1, and then a new value is assigned to the
variable 'X'.

Post increment Operator:

Prepared By: Department of Computer Engineering Page 7


Subject Name: Basic Computer Programming Unit No: 02 Subject Code: 4310702

The post-increment operator is used to increment the original value of the operand by 1 after assigning it
to the expression.
X = A++;
In the above example, the value of operand 'A' is assigned to the variable 'X'. After that, the value of
variable 'A' is incremented by 1.

Pre- decrement Operator:


The pre- decrement operator is used to decreases the value of the operand by 1 before assigning it to the
expression.
X = --A;
In the above example, the value of operand 'A' is decreased by 1, and then a new value is assigned to the
variable 'X'.
Post decrement Operator:
The post- decrement operator is used to decrement the original value of the operand by 1 after assigning
it to the expression.
X = A++;
In the above example, the value of operand 'A' is assigned to the variable 'X'. After that, the value of
variable 'A' is decrement by 1.

Bitwise operator:

 The bitwise operators are used to manipulate data at bit level.


 These operators are used for testing bits or shifting them left or right.
1) Bitwise AND(&):
2) Bitwise OR(|):
3) Bitwise Exclusive OR(^):
4) Shift left(<<):
5) Shift right(>>):
6) One „s complement(~):

Bit 1 Bit 2 Bit1 & Bit2 Bit1 | Bit2 Bit1 ^ Bit2


0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

Example: Bitwise AND(&)

x=5
y=7
z=x&y

Prepared By: Department of Computer Engineering Page 8


Subject Name: Basic Computer Programming Unit No: 02 Subject Code: 4310702

x - -> 0000 0101


y - -> 0000 0111

z - -> 0000 0101

Example: Bitwise or( | )

x=5, y=7
z=x&y

x - -> 0000 0101


y - -> 0000 0111

z - -> 0000 0111

Example: Bitwise Exclusive OR( ^ )

x=5, y=7
z=x&y

x - -> 0000 0101


y - -> 0000 0111

z - -> 0000 0010

Conditional operator (ternary operator ):

 The conditional operator is also known as ternary operator because it has three operands.
 The general form of ternary operator is follow:
o Syntax: e1 ? e2 : e3 ;

 where e1 is logical expression(condition) , and evaluated first.

 If the condition is true then the statement is followed the? Is executed(e2 is executed) otherwise the
statement followed the : is executed(e3 is executed).

Example:
max=(x>y) ? x : y;

First (x>y ) is checked, if it is true then x is assigned to max , otherwise y is assigned to max.

 Operator precedence and their associativity:


Operator precedence determines the grouping of terms in an expression and decides how an
expression is evaluated.

Prepared By: Department of Computer Engineering Page 9


Subject Name: Basic Computer Programming Unit No: 02 Subject Code: 4310702

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

Evaluation of Expressions:

 The expressions are evaluated by performing one operation at a time. The precedence and
associativity of operators decide the order of the evaluation of individual operations.
 The expressions with parentheses are evaluated first. If two or more parentheses exist in an
expression, the parentheses are evaluated from left to right. In the case of nested parentheses, the
innermost parentheses are evaluated first, while the outermost one is evaluated last.
 If there are no parentheses, the order of evaluation of an expression is based on the operator
precedence and associativity:
Example:
7 * (5 + 15) / (2 * 5) – 3
= 7*20/10−3.
= 140/10−3
=14-3
=11

Prepared By: Department of Computer Engineering Page 10


Subject Name: Basic Computer Programming Unit No: 02 Subject Code: 4310702

 Type casting /Type conversion :

 The type conversion are automatic as part of expression evaluation.


 But some times the user needs explicit type conversion.
 Example, int / int is always int. But, if we need the answer in float , then type casting is used.

Syntax:

Example: (type _ name) expression ;

float average;
int sum=25, n=10;
average = (float) sum / n;

where sum / n results into 2.5 rather than 2, because the division is performed after converting sum in to
float and the result of float / int is always float. So,

average =(float) sum / n;


= (float) 25 / 10;
= 25.0 / 10
= 2.5

 Input and Output statements in ‘C’:

 When we say Input, it means to feed some data into a program. An input can be given in the
form of a file or from the command line. C programming provides a set of built-in functions to
read the given input and feed it to the program as per requirement.

 When we say Output, it means to display some data on screen, printer, or in any file. C
programming provides a set of built-in functions to output the data on the computer screen as
well as to save it in text or binary files.

Formatted input and output in ‘C’:

C provides standard functions scanf() and printf(), to perform formatted inputs and outputs.
scanf() function:
Syntax:
scanf(format_specifiers, &data1, &data2,……);
Example:
scanf(“%d %c”,&data1,&data2);
printf() function:
Syntax:
printf(format_specifiers, data1, data2,……);
Example:
printf(“%d %c”,data1,data2);

Prepared By: Department of Computer Engineering Page 11


Subject Name: Basic Computer Programming Unit No: 03 Subject Code: 4310702

UNIT: 3
Decision Statements and Control Structure
 Decision Statements
 Conditional branching statements:

Simple if statement:

Syntax:
if (condition)
{
Statement (s)
}
If the given condition is true then the statements inside the body of “if” will be executed. If the condition
is false then the statements inside the body of “if” will be skipped.

#include<stdio.h>
#include<conio.h>
void main()
{
int marks=45;
if( marks < 35 )
{
printf(“Student is fail”);
}
getch();
}

Prepared By: Department of Computer Engineering Page 1


Subject Name: Basic Computer Programming Unit No: 03 Subject Code: 4310702

If-else statement:
Syntax:

if(condition)
{
Statement 1;
}
else
{
Statement 2;
}

The if..else statement is executed in the following order:

1. first the condition is checked.


2. if condition is true the statement -1 is executed.
3. if condition is false the statement - 2 is executed.

True False
Condition?

Statement- 1 Statement- 2

Statement - X

Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int marks=45;
if( marks < 35 )
{
printf(“Student is fail”);

Prepared By: Department of Computer Engineering Page 2


Subject Name: Basic Computer Programming Unit No: 03 Subject Code: 4310702

}
else
{
printf( “Student is pass” );
}
getch();
}

Nested If-else statement:


Nested If-else statement means if-else statement within another if-else statement.
Syntax:

if (condition1)
{
if (condition2)
stmt1;
else
stmt2;
}
else
{
if (condition3)
stmt3;
else
stmt4;
}

Prepared By: Department of Computer Engineering Page 3


Subject Name: Basic Computer Programming Unit No: 03 Subject Code: 4310702

Example:

#include<stdio.h>
#include<conio.h>
void main (){
int a,b,c;
printf("Enter the values of a,b,c: ");
scanf("%d,%d,%d",&a,&b,&c);
if((a>b)&&(a>c))
{
if(a>c)
{
printf("%d is the largest",a);
}
else
{
printf("%d is the largest",c);
}
}
else
{
if(b>c)
{
printf("%d is the largest",b);
}
Prepared By: Department of Computer Engineering Page 4
Subject Name: Basic Computer Programming Unit No: 03 Subject Code: 4310702

else
{
printf("%d is the largest",c);
}
}

if else if…ladder

It is used for multiple choice.

Syntax:

if(condition-1)
{
Statement - 1;
}
else if(condition-2)
{
Statement - 2;
}
else if(condition-3)
{
Statement - 3;
}
.
.
.
else if(condition-N)
{
Statement -N;
}
else
{
Default statement;
}

if-else-if ladder is executed in the following order:


1. First condition-1 is executed, if the condition-1 is true then the statement-1 is executed.
2. if the condition-1 is false then condion-2 is checked. If condition-2 is true then statement-2 is
executed.

Prepared By: Department of Computer Engineering Page 5


Subject Name: Basic Computer Programming Unit No: 03 Subject Code: 4310702

3. This procedure repeated until all the condition is checked. if all the condition became false then the
default statement is executed.

Flowchart:

True
Condition 1? Statement - 1

False

True
Condition 2? Statement - 2

True
Condition 3? Statement - 3

.
.

. True
Condition N? Statement - N

Default Statement

Example:

Prepared By: Department of Computer Engineering Page 6


Subject Name: Basic Computer Programming Unit No: 03 Subject Code: 4310702

#include<stdio.h>
#include<conio.h>
void main()
{
int no;
printf(“enter number\n”);
scanf(“%d”,&no);
if( no > 0 )
{
printf(“Number is Positive”);
}
else if (no < 0)
{
printf( “Number is Negative” );
}
else
{
printf( “Number is Zero” );
}
getch();
}

Switch statement:
 It is used to select one among multiple decisions.
 The switch statement is also known as multi-choice or multi decision statement.
 „switch‟ successively tests a value against a list of integers or character constant.
 When a match is found, the statement(s) associated with that value is executed.
 Break statement send the control to the next statement after switch statement.
 If the case not found then the statement associated with the default case is executed.
Syntax:

Prepared By: Department of Computer Engineering Page 7


Subject Name: Basic Computer Programming Unit No: 03 Subject Code: 4310702

switch(variable name or expression)


{
case label1:
statement(s) 1;
break;
case label2:
statement(s) 2;
break;
.
.
case label N:
statement(s) N;
break;
default :
default statement(s);
}

Example:
void main()
{
int a=2;
clrscr();

switch(a)
{

case 1:
printf(“One \n”);
break;
case 2:
printf(“Two”);
break;
case 3:
printf(“Three”);
break;
default:
printf(“Wrong choice”);

getch();
}

O/p: Two

Prepared By: Department of Computer Engineering Page 8


Subject Name: Basic Computer Programming Unit No: 03 Subject Code: 4310702

 Unconditional branching statement: goto


 The go to statement in the c programming is used to transfer the control unconditionally from one part of
the program to other part of the program.
 „c‟ language provide a unconditional branching mechanism called as go to statement.

Syntax:

goto label ;

 Here , label is the label to the statement to which go to transfer control.


 Label must be a valid identifier.

 There are two possible use of goto statement.


1. Forward Reference
2. Backward Reference

Forward reference Backward reference

goto label; Label:

…………. Statement;

…………. ………

Label: ………..

Statement; Goto label;

Target statement comes after the goto. Target statement comes before the goto.

 Control Statements:
When we want to repeatedly run a particular statement until a particular condition is met, then in that case we
use Loop Statements.

There are three types of loop statements in C language:

 While loop

 Do while loop

 For loop

While loop:

Prepared By: Department of Computer Engineering Page 9


Subject Name: Basic Computer Programming Unit No: 03 Subject Code: 4310702

 It is entry control loop.


 In the while loop, first the condition is checked and if the condition is true then the statement inside the
while loop is run.
 As soon as the condition is False, the control is moved out of the while loop, and another statement is
executed.
 At first time, condition is false, then body is not executed.

Syntax:

while (Condition)
{
Statements;
}

Example:
i =1;

while (i < = 10)


{
printf( “% d \n ” , i );
i = i+1;
}

Do-While loop:

 It is exit control loop.


 In do-while loop, first body is executed and then condition is checked and if the condition is true, then
again body of the loop will be executed, otherwise next statement after the loop will be executed.
 At first time, condition is false, at least once the body is executed.

Syntax:

do
{
// statements inside the loop
}
While (condition);

Example:

i =1;
do
{
Prepared By: Department of Computer Engineering Page 10
Subject Name: Basic Computer Programming Unit No: 03 Subject Code: 4310702

printf( “% d \n ” , i );
i = i+1;
} while (i < = 10);

For loop :
 In For Loop, we write both the initialization and control condition of the variable together inside
the parentheses “()”.
 If the condition of For Loop is true, then the statement inside it is run, or else the statement is not
run.
Syntax:

for (Initialization ; Condition ; Increment or decrement)


{
body of the loop;
}
 Initialization: The control variable is initialized in the initialization expression. It executes only once.
 Condition: The condition statement checks the value of the control variable. If the condition statement
is true, the body of the loop is executed.
 Increment/Decrement: The increment/decrement of the control variable is done in this part. After the
incrementing/decrementing the value of control variable, it is tested using condition if condition is true
than again the body of loop is executed and this process is repeated until the condition become false.
Flowchart:

Initialization

False

Condition?

True
Increment/
Decrement Body

Example: Print 1 to 5 numbers using for loop.

Prepared By: Department of Computer Engineering Page 11


Subject Name: Basic Computer Programming Unit No: 03 Subject Code: 4310702

for(i = 1; i < =5 ; i++)


{
printf(“ %d \n “, i ) ;
}

Nested for loop:


Nested for loop means for loop within another for loop.

Syntax:

for (Initialization; condition; increment ) {

for (Initialization; condition; increment ) {


statement(s);
}
statement(s);
}

Example:

for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("%d",i);
}
printf("\n");
}

 Break and continue statements:

Break statement:
 It terminates the loop or switch statement and transfers execution to the statement immediately
following the loop or switch.
 Keyword used is "break".
 Break from loop:

for( ; ; )
{
for( ; ; )
{
Prepared By: Department of Computer Engineering Page 12
Subject Name: Basic Computer Programming Unit No: 03 Subject Code: 4310702

if(condition)
break;
}
--------------------
}

Example;
for(i=1; i<=5 ; i++)
{
if(i==3)
break;
printf("%d\n",i);
}

Output: 1 2

Continue statements :
 It causes the loop to skip the remainder of its body and starts the next iteration.
 Keyword used is "continue".

for( ; ; )
{

--------------
if( condition)
continue;
------------

Example:

Print 1 to 5 number except 3.

for( i=1 ; i <= 5 ; i++)


{
if ( i ==3)
continue;
printf(“%d ” ,i);
}
Output: 1 2 4 5

Prepared By: Department of Computer Engineering Page 13


Subject Name: Basic Computer Programming Unit No: 04 Subject Code: 4310702

UNIT: 4
Array and Pointers

 Introduction of Array:
Definition: Array is a collection of variables of same data type known by same name.
Types of Arrays:
 One-dimensional arrays.
 Two-dimensional arrays.
 Multidimensional arrays.

 Characteristics of an array:
 Array store elements that have same data type.
 Array store elements in subsequent memory location.
 Array size should be mention in the declaration.
 Array name represent the address of starting elements.

 Declaration and initialization of 1- D (One dimensional array):

Declaration of array:

Syntax:
datatype array_name[size];

Data type: it defines the datatype, like int,float,char,double etc.


Array name: it is the name of array.
Size: It represents the size of the array.

Example:
int a[5];
float f[5];

Initialization of array:
(1) Compile time:
datatype arrayname[size]={List of value};
int a[5]={10,20,30,40,50};

Prepared By: Department of Computer Engineering Page 1


Subject Name: Basic Computer Programming Unit No: 04 Subject Code: 4310702

(2) Run time:


for(i=0 ; i<5 ; i++)
{
scanf("%d", &a[i]);
}

Example: Program to read 5 elements of array and print it.


#include<stdio.h>
#include<conio.h>
void main()
{
int a[5],i;
clrscr();
printf("Enter 5 elements of array");
for(i=0;i<5;i++)
{ scanf("%d",&a[i]);
}
printf("The array elements are:\n");

for(i=0;i<5;i++)
{
printf("%d\n",a[i]);
}
getch();
}

 Declaration and initialization of 2- D (Two dimensional array):

Declaration of array:
Syntax:
datatype Arrayname [row size] [column size];
Example:
int a[3][3] ;
where, int is datatype, a is a arrayname , row size is 3 and column size is 3.
float f[5][10];
Initialization of array:
(1) Compile time:
int a[3][3]={ {11,12,13}, {14,15,16}, {17,18,19} } ;
int a[3][3] = {11,12,13,14,15,16,17,18,19};
col 0 col 1 col 2

row 0 11 12 13

Prepared By: Department of Computer Engineering Page 2


Subject Name: Basic Computer Programming Unit No: 04 Subject Code: 4310702

a[0][0] a[0][1] a[0][2]

14 15 16
row 1
a[1][0] a[1][1] a[1][1]
17 18 19
row 2
a[2][0] a[2][1] a[2][2]
(In memory Representation of array)
(2) Run time:
for(i=0 ; i<3 ; i++)
{
for(j=0 ; j<3 ; j++)
{
scanf(" %d ", &a[i][j] );
}
}

Example: Program to read 3X3 matrix (2D array elements) and print it.

#include<stdio.h>
void main()
{
int i,j,a[3][3];
printf("Enter elements of 3X3 matrix\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("The elements of 3X3 matrix\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",a[i][j]);
}
printf(“\n”);
}

Prepared By: Department of Computer Engineering Page 3


Subject Name: Basic Computer Programming Unit No: 04 Subject Code: 4310702

 Introduction to a String:
String:
A string is a sequence of zero or more characters followed by a NULL '\0' character.
String is always terminating with NULL '\0' character.

Declaration and initialization of string:

Syntax:
char stringname[size];
where size is the number of characters.
Example:
char city[10] ;
Initialization of string variable:
(1) Compile time:
char city[9]= " NEW YORK";
(2) Run time:
char city[9];
scanf("%s", city);
OR
char city[9];
gets(ciy);

 gets() and puts() :


gets():
This function read a string from a user. It is defined in the <stdio.h> header file of C.

puts() :
This function prints a string on the console screen. It is also defined in the <stdio.h> header file of C.

Example: Program to read and print a string using gets() and puts().

void main()
{
char day[10];
printf("Enter day: \n");
gets(day);

printf("Today is: ");


puts(day);
}
Output:

Prepared By: Department of Computer Engineering Page 4


Subject Name: Basic Computer Programming Unit No: 04 Subject Code: 4310702

Enter day: TUESDAY


Today is: TUESDAY

 Pointer
 Introduction to Pointer:
Pointer is a variable which store the address of another variable.
Advantage of pointer:
 Pointer reduces the code and improves the performance.
 We can return multiple values from a function using the pointer.
 It makes you able to access any memory location in the computer's memory.

Characteristics of Pointers:

 Pointer is a variable which can hold the address of another variable.


 A pointer is a derived data type.
 It contains memory addresses as their values.
 If a C pointer is assigned to the null value, it points nothing.
 The asterisk symbol, * is used to retrieve the value of the variable
 & ampersand symbol is used for retrieving the address of a variable.

 declaration and initialization of pointer :


Declaration of pointer
Syntax:
Data type *pointer-name

Example:
int *p;
Initialization of pointer:
Syntax:
Pointer variable= &variable-name;
Example:
int price;
int *p;
p=&price;

Prepared By: Department of Computer Engineering Page 5


Subject Name: Basic Computer Programming Unit No: 04 Subject Code: 4310702

Example:

#include<stdio.h>
Void main(){
int number=50;
int *p;
p=&number;//stores the address of number variable
printf("Address of p variable is %x \n",p); // p contains the address of the number
printf("Value of p variable is %d \n",*p); // * is used to dereference a pointer therefore *p means get the
value stored at the address contained by p.
}
 Types of pointer : void and null
void pointer
Syntax:
void *variable name

 Void pointer is a pointer which has no specified data type.


 It is also known as generic pointer.
 Void pointer can be pointed to any data type.
 When void pointer is declared two bytes of memory is assign to it.
 It is used when return type or parameter is unknown.
 void pointers that have addresses, can be further typecast into other data types very easily.
Example:

include<stdio.h>
void main()
{
int a = 10;
void *p;
p = &a;
printf(“%d”, *(int *)p);
}

NULL Pointer:
 A pointer that is not assigned any value but NULL is known as the NULL pointer.
 If you don't have any address to be specified in the pointer at the time of declaration, you can
assign NULL value. It will provide a better approach.

int *p=NULL;

Prepared By: Department of Computer Engineering Page 6


Subject Name: Basic Computer Programming Unit No: 04 Subject Code: 4310702

pointer to pointer:
 Pointer variable may pointes to another pointer variable.
 It is also known as double pointer.
 The first pointer is used to store the address of a variable whereas the second pointer is used to
store the address of the first pointer.

Syntax:
Data type **pointer variable name;
Example:
int **p; // pointer to a pointer which is pointing to an integer.

Example:

int n,*p1,**p2;
n=10;
p1=&n;
p2=&p1;

Example:

#include<stdio.h>
void main ()
{
int a = 10;
int *p;
int **p2;
p = &a; // pointer p is pointing to the address of a
p2 = &p; // pointer p2 is a double pointer pointing to the address of pointer p
printf("address of a: %x\n",p); // Address of a will be printed
printf("address of p: %x\n",p2); // Address of p will be printed
printf("value stored at p: %d\n",*p); // value stoted at the address contained by p i.e. 10 will be
printed
printf("value stored at p2: %d\n",**pp); // value stored at the address contained by pointer
stored at p2
}

Prepared By: Department of Computer Engineering Page 7


Subject Name: Basic Computer Programming Unit No: 05 Subject Code: 4310702

UNIT: 5
Functions
 Introduction to Functions:
Definition of Function: Function is a group of statement to perform a specific task.
Types of functions:
1. Library function
2. User-defined Function

 Advantages of using Functions:

1. By using functions, we can avoid rewriting same logic/code again and again in a program.
2. We can call C functions any number of times in a program and from any place in a program.
3. We can track a large C program easily when it is divided into multiple functions.

 Types of Functions: Built-in and user defined Functions


Library function(Built-in):
 The function which is develop by system itself is known as Library function .
 Example: printf(),scanf(),sqrt(),ceil() etc …
 Library function is all ready exist in system.

User-defined Function:
 The function which is develop by user itself is known as User-defined function.
 Example: main()
 User-defined function is created by the user at the time of writing of program.

Difference between Library function and User-defined Function.

No. Library function User-defined Function


The function which is develop by The function which is develop by
1 system itself is known as Library user itself is known as User-defined
function. function.
Example: printf(),scanf(),sqrt() etc … Example: main(),add()
2.

There no elements in Library function. User-defined function has three


3.
elements.

Prepared By: Department of Computer Engineering Page 1


Subject Name: Basic Computer Programming Unit No: 05 Subject Code: 4310702

 Declaring, Defining and calling user defined Functions


(1) Function declaration
Syntax:
ReturnType FunctionName (Parameter List);
 Function Type is a return type or datatype of a function.
 Function name is the name of the user defined function.
Example:
int sum (int, int);
int sum( int a, int b);
(2) Function call
Syntax:
Identifier = Function name(Argument value);
Where identifier is the name of variable
Example:
a = sum(10,5);
(3) Function definition
Syntax:
ReturnType Function Name(Parameter List)
{
Local variable declaration
Function statement
Return Statement
}

Example:
int sum(int x, int y)
{
int total;
total = x + y;
return total;
}

 Categories of user-defined Functions


A function may or may not accept any argument. It may or may not return any value. Based on these facts,
There are four different categories of function calls.

 function without arguments and without return value


 function without arguments and with return value
 function with arguments and without return value

Prepared By: Department of Computer Engineering Page 2


Subject Name: Basic Computer Programming Unit No: 05 Subject Code: 4310702

 function with arguments and with return value

Example for Function without argument and return value


#include<stdio.h>
void sum();
void main()
{
printf("\n sum of two numbers:");
sum();
}
void sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
printf("The sum is %d",a+b);
}

Example for Function without argument and with return value


#include<stdio.h>
int sum();
void main()
{
int result;
result = sum();
printf("%d",result);
}
int sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}

Prepared By: Department of Computer Engineering Page 3


Subject Name: Basic Computer Programming Unit No: 05 Subject Code: 4310702

Example for Function with argument and without return value


#include<stdio.h>
void sum(int, int);
void main()
{
int a,b,result;
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b)
{
printf("\nThe sum is %d",a+b);
}

Example for Function with argument and with return value


#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
}

 Call by Value and call by Reference


Call By Value with example:

 When a function is called using the value of variables, then it is known as call by value.

Prepared By: Department of Computer Engineering Page 4


Subject Name: Basic Computer Programming Unit No: 05 Subject Code: 4310702

 The value of variables, which are to be passed, will be copied from the variables of the calling functions
to the variables of the called functions.
 All the process done on the duplicate variables rather then actual variables.
Example:

#include <stdio.h>
void swap(int , int); // function prototype
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
swap(a,b); // function call
printf("After swapping values in main a = %d, b = %d\n",a,b); //actual parameters a=10, b=20
}
}
void swap (int a, int b)
{
int temp;
temp = a;
a=b;
b=temp;
printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameters, a=20, b=10
}

Call By Reference with example:

 When a function is called using the address of variables, then it is known as call by reference.
 Instead of passing the value of variables from calling function to the called function, addresses of the
variables are passed.
 All the process done on the actual variables.
Example:

#include <stdio.h>
void swap(int *, int *); // function prototype
void main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);

Prepared By: Department of Computer Engineering Page 5


Subject Name: Basic Computer Programming Unit No: 05 Subject Code: 4310702

swap(&a,&b); // function call


printf("After swapping values in main a = %d, b = %d\n",a,b); // actual parameters a = 20, b = 10
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters a=20, b=10
}

 Recursion

 Function call itself is called Recursion.


 Recursive call to a function may be conditional or unconditional.
 In conditional recursive call, function is terminated when condition is false.
 In unconditional recursive, function is called infinitely.
 It is used to find the factorial of a given number.
 Example :
void main()
{
printf(“Recursion”);
main();
}
 Example :
void main()
{
------------------
function1();
----------------
}
function1()
{
------------------
function1();
----------------
}

Prepared By: Department of Computer Engineering Page 6


Subject Name: Basic Computer Programming Unit No: 05 Subject Code: 4310702

Advantages of Recursion:
 The recursion is very flexible in data structure like stacks.
 Using recursion, the length of the program can be reduced.
Disadvantages of Recursion:
 It requires extra storage space.
 The recursion function is not efficient in execution speed and time.
 Proper termination is required; otherwise it leads to infinite loop.

 Built-in Functions: String and Maths

Built-in Functions:

C Maths Function:
The <math.h> header file contains various methods for performing mathematical operations such as
sqrt(), pow(), ceil(), floor() etc.

ceil(number)
Rounds up the given number.
It returns the integer value which is greater than or equal to given number.

Ex: ceil(3.6)
It returns 4.

floor(number)
Rounds down the given number. It returns the integer value which is less than or equal to given number.

Ex: floor(3.6)
It returns 3.

sqrt(number)
Returns the square root of given number.

Ex: sqrt(16)
It returns 4.

pow(base, exponent)
Returns the power of given number.

Ex pow(2,4)
It returns 16.

Prepared By: Department of Computer Engineering Page 7


Subject Name: Basic Computer Programming Unit No: 05 Subject Code: 4310702

abs(number)
Returns the absolute value of given number.
Ex: abs(-16)
It returns 16.

C String Functions:
There are many important string functions defined in "string.h" library.

No. Function Meaning

1) strlen(string_name) returns the length of string name.

2) strcpy(destination, source) copies the contents of source string to destination


string.

3) strcat(first_string, second_string) concats or joins first string with second string. The
result of the string is stored in first string.

4) strcmp(first_string, compares the first string with second string. If both


second_string) strings are same, it returns 0.

5) strrev(string) returns reverse string.

6) strlwr(string) returns string characters in lowercase.

7) strupr(string) returns string characters in uppercase.

 Storage Classes: -auto, static, register and extern

Storage Classes in C:

Storage classes in C are used to determine the lifetime, visibility, memory location, and initial value of a
variable. There are four types of storage classes in C

 Automatic
 External
 Static
 Register

Prepared By: Department of Computer Engineering Page 8


Subject Name: Basic Computer Programming Unit No: 05 Subject Code: 4310702

Storage Storage Default Scope Lifetime


Classes Place Value

auto RAM Garbage Local Within function


Value

extern RAM Zero Global Till the end of the main program Maybe declared
anywhere in the program

static RAM Zero Local Till the end of the main program, Retains value
between multiple functions call

register Register Garbage Local Within the function


Value

Prepared By: Department of Computer Engineering Page 9


Subject Name: Basic Computer Programming Unit No: 06 Subject Code: 4310702

UNIT: 6
Structure, Union and Files

 Structure
 Introduction to Structures and Declaration, Initialization and accessing of
Structures:
 Structure is a collection of logically related data items with different data type.
 Structure must be defined first, that may be used later to declare structure.
Syntax:
struct structure_name
{
datatype member1;
datatype member2;
---
datatype memberN;
};
 struct is a keyword, it declares structure to hold data.
 Structure_Name is the name of structure (structure tag).
 member1, member2,… are members of structure.

Example:
struct student
{
char name[20];
int roll_no;
float per;
}s1;
Here s1 is a structure variable.

Structure Initialization:
Example:
struct student
{
char name[20];
int roll_no;
float per;
}s1={"Arav",20,85.5};

Example:

#include<stdio.h>
struct student

Prepared By: Department of Computer Engineering Page 1


Subject Name: Basic Computer Programming Unit No: 06 Subject Code: 4310702

{
char name[20];
int roll_no;
float per;
}s1;
void main()
{
struct student s1={"Arav",20,85.5};

printf("\nName : %s",s1.name);
printf("\nRollNo : %d",s1.roll_no);
printf("\nPercent : %f",s1.per);
}

 Introduction to union and Declaration, Initialization and accessing of union:


 Union is a group of memory that is used to store variables of different datatypes.
 Union are same as structure, but main difference between structure and union is in terms of storage.
Syntax :
union union-name
{
datatype member1;
datatype member2;
---
datatype memberN;
};

Example:
union student
{
char name[20];
int roll_no;
float per;
};

Example:

union student
{
char name[20];
int roll_no;
float per;
}u1;

Prepared By: Department of Computer Engineering Page 2


Subject Name: Basic Computer Programming Unit No: 06 Subject Code: 4310702

void main()
{
u1.roll_no=65;
printf("\nRollNo : %d",u11.roll_no);
}

Difference between structure and union


Structure union
In structure, each member has separate In union all member shares common memory.
1
memory allocated.

2. Any member can be accessed at any time. Only one member can be accessed at a time.

struct data union data


{ {
int a; int a;
3. float b; float b;
char c; char c;
}; };
Size of structure is total memory allocated to Size of union is maximum memory allocated to
each member. any member.
4.
Size of student= total sizeof(a,b,c); Size of student= maximum memory from
(a,b,c);
5 Structure is defined using struct keyword. Union is defined using union keyword.

Difference between Array and structure.

Array Structure
An array is a collection of variables of same A structure is a collection of variables of
1
data type known by same name. different data type known by same name.

2. An array is a derived data type. A structure is a programmer defined.

For array we have to declare an array For structure we have to design and declare a
3. variable and use it. data structure before the variables of that type
are declared and used.

Prepared By: Department of Computer Engineering Page 3


Subject Name: Basic Computer Programming Unit No: 06 Subject Code: 4310702

Example: Example:
int a[5]; struct data
{
4. int a;
float b;
char c;
};

 User-defined Data types: enum, typedef


Enumerated Data Type:
 Enumerated data type is user defined data type.
 Using enumerated data type we can create more than one symbolic constant at a time.

Syntax: enum identifier {value1, value2,value3};

Here, enum is a keyword to declare enumerated data type.


Identifier is a user defined enumerated data type.

For Example:

#include<stdio.h>
enum week {Mon=1, Tue, Wed, Thur, Fri, Sat, Sun};
void main()
{
enum week day;
day = Wed;
printf("%d",day);
getch();
}
Output:2

typedef :
The typedef is a keyword that is used in C programming to provide existing data types with a new name.
typedef keyword is used to redefine the name already the existing name.
When names of datatypes become difficult to use in programs, typedef is used with user-defined datatypes.
Syntax:
typedef <existing_name> <alias_name>
Example:
typedef long mylong
Prepared By: Department of Computer Engineering Page 4
Subject Name: Basic Computer Programming Unit No: 06 Subject Code: 4310702

 Files
Introduction to text Files
File:
A file is a group of related data which is stored in a disk.
File operations:
(1) Naming a file
(2) Opening a file
(3) Reading data from a file
(4) Writing data to a file
(5) Closing a file

Basic file operations:

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


fclose() - close 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 beginning point

fopen() and fclose():


fopen(): Create a new file or open an existing file.
Syntax:
FILE *fp;
fp=fopen("filename", "mode");
Here,fp is a file pointer to the datatype FILE.
Second statement open a file named filename and mode specify the opening of this file.
Example:
FILE *fp;
fp=fopen("E:\\abc.txt", "r");
fclose(): Close the file
A file must be closed as soon as all operation on it have been completed.
Syntax:
fclose(file pointer);
Example:
FILE *fp;
Prepared By: Department of Computer Engineering Page 5
Subject Name: Basic Computer Programming Unit No: 06 Subject Code: 4310702

fp=fopen("E:\\abc.txt", "r");
---------------------
fclose();

fgetc() and fputc():


fputc(): Write character to the file
Syntax: fputc(c,fp);
Here c is a character type variable and fp is a file pointer.
This statement write the character stored in variable c to the file.
Example:
void main()
{
char c=’A’;
FILE *fp;
Fp= fopen(“ E:\\ abc.txt”, “w”);
fputc(c,fp);
fclose(fp);
getch();
}

fgetc(): Read character from file


Syntax: c=fgetc(fp);
Here c is a character type variable and fp is a file pointer.
Example:
void main()
{
char c;
FILE *fp;
Fp= fopen(“ E:\\ abc.txt”, “r”);
c = fgetc(fp);
printf(“%c”, c);
fclose(fp);
getch();
}

fscanf() and fprintf():


These functions are used for reading and writing the data to the file.
fprintf() : Write all data written in list to the file.
Syntax: fprintf(fp , “Control String “, List);
Where fp is a file pointer.
List may include variable, constants and string.
Example:
void main()
{

Prepared By: Department of Computer Engineering Page 6


Subject Name: Basic Computer Programming Unit No: 06 Subject Code: 4310702

char name[10]=”abc”;
int id=1;
FILE *fp;
Fp= fopen(“ E:\\ abc.txt”, “w”);
fprintf(fp,”%s %d”, name,id);
fclose(fp);
getch();
}
fscanf() : Read all data written in file and store in variables.
Syntax: fscanf(fp , “Control String “, List);
Where fp is a file pointer.
List may include variable, constants and string.
Example:
void main()
{
char name[10];
int id;
FILE *fp;
Fp= fopen(“ E:\\ abc.txt”, “r”);
fscanf(fp,”%s %d”, name, &id);
printf(“Name : %s and id : %d”, name, id);
fclose(fp);
getch();
}

Example of reading data from a file and writing to it(in text mode):

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
fp = fopen("hello.txt", "w");
printf("Enter data");
while( (ch = getchar()) != EOF) {
putc(ch,fp);
}
fclose(fp);
fp = fopen("hello.txt", "r");

while( (ch = getc(fp)! = EOF)


printf("%c",ch);
Prepared By: Department of Computer Engineering Page 7
Subject Name: Basic Computer Programming Unit No: 06 Subject Code: 4310702

fclose(fp);
}

Prepared By: Department of Computer Engineering Page 8


VPMP Polytechnic
Computer Department

BCP (4310702)

Assignment: 1

1) What is Flow chart? Draw and Explain symbols of Flowchart.


2) Give advantages and disadvantages of flowchart.
3) Explain different structure of Flowchart.
4) What is Algorithm? Give advantages and disadvantages of Algorithm.
5) Draw Flowchart to Calculate the Area of Circle. Write down algorithm for the same.
6) Draw Flowchart to find out Maximum number out of two numbers.
7) Write an Algorithm to find out whether the given number is odd or even.

Assignment: 2

1) List the features of C.(List the advantages of C. )


2) Draw a basic structure of C program and explain in short.
3) Explain C Tokens (with types), keywords and identifiers.
4) Explain Constants with example.
5) Define variable. List out rules for variable naming.
6) List the basic data types with its size and range.
7) List operators available in C. Explain Arithmetic, Relational, Logical operators in C.
8) Explain Conditional and bitwise operators in C.
9) Explain explicit and implicit type casting.
10) Evaluate following arithmetic expression.
(1) x=9-12/3+3*2-1;
(2) y=9-12/(3+3)*(2-1)
(3) z=9-(12/(3+3)*2)-1
11) Convert the following expression into its equivalent C expression.
(1) y = ax2+bx+c
𝑚1+𝑚2
(2) y= 1−𝑚1𝑚2
(3) y = 𝑠(𝑠 − 𝑎)(𝑠 − 𝑏)(𝑠 − 𝑐)
(4) y = 𝑎2 + 𝑏 2
Assignment-3

1) Explain Nested If-else statement with example.


2) Explain If-else-if Ladder statement with example.
3) Explain Switch statement with example.
4) Explain Unconditional branching statement- goto.
5) Explain while loop and do-while loop with example.
6) Compare While loop and do-while loop.( Compare Entry-control loop and Exit-control
loop)
7) Explain for loop with example.
8) Explain Break and continue statements with example.

Assignment-4

1) Define array. Give characteristics of an array.


2) What is an array? How to declare and initialize 1-D array.
3) How to declare and initialize 2-D array.
4) Write a program to read 5 elements of array and display it.
5) Define String. How to declare and initialize string.
6) Explain gets ( ) and puts ( ).
7) Define pointer. How to declare and initialize pointer.
8) Explain void pointer.
9) Explain pointer to pointer.

Assignment-5

1) What is user defined(UDF) and library function? Explain with two example of each.
2) Explain call by value with example.
3) Explain call by reference with example.
4) Explain recursion with example.
5) Explain following string function with example.
(1) strcpy() (2) strcat() (3) strcmp() (4) strlen()
6) List out math in-built functions.
7) List available storage class in C.
Assignment-6

1) Explain enumerated data type with example.


2) How to declare a structure? State the difference between structure and union.
3) Differentiate between array and structure.
4) Define File. List files operations. Explain fscanf() & fprintf () functions with examples.
5) Explain fopen() & fclose() functions with examples.
BASIC OF COMPUTER PROGRAMMING (4310702)
IMP QUESTION WITH ANWSER

1. What is a flowchart ? Limitation of flowchart.


 Flowchart is graphical or diagrammatical representation of sequence of any problem to
be solved by computer programming language.
 Flowchart is a diagrammatic representation of an algorithm.
Limitation
 Complex logic: Sometimes, the program logic is quite complicated. In that case, flowchart
becomes complex and clumsy.
 Alterations and Modifications: If alterations are required the flowchart may require re-
drawing completely.
 Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart
becomes a problem.
 The essentials of what is done can easily be lost in the technical details of how it is done.
 It is the total perception of the designer who draw the flowchart.
 It's working differ from one compiler to another ,one language to another in sometime.
 It need well-defined requirements.

2. Define Algorithm with example.


 An algorithm is a finite sequence of well defined steps or operations for solving a problem in
systematic manner.
 These are rules for solving any problems in proper manner.
 Instructions are written in the natural language.
 It is also called step by step solution.

Example: Write an algorithm to find area of circle.


Step 1: Input R
Step 2: Compute A = 3.14 * R * R
Step 3: Print A
Step 4: Stop

3. List the Feature of C language.


 C is portable.: ‘C’ Program can be run on any hardware.
 C does not support input/output statements.: ‘C’ does not support input/output statement
like input and print, but support library functions printf( ) and scanf( ).
 C supports bitwise operators.: The C support bitwise operator like AND, OR, NOT etc.
1
normally these operations do not supported by higher level languages..
 C is modular language.: The program written in from of functions. A C program is group of
one or more functions. Dividing the program into small functions makes it to easy develop and
maintain the programs. Each function is easy to understand as it is small. The method of
dividing a program into small functions is called modularity.

4. List out C Token.


 The smallest individual unit in a C program is known as C token.
 C has six types of token as given below:
1. Keywords (float,while)
2. Identifier(main,amount)
3. Constants(-15.2, 10)
4. String(“abc”, “hello”)
5. Special Symbols ([ , ] , *, ! etc)
6. Operators (+,-, *,/)

5. Explain keyword.
 Keywords are those words whose meaning is predefined.
 The programmer cannot change the meaning of keywords.
 There are 32 keywords available in c.
 All the keywords must be written in lowercase.
 Following is the list of keywords:
Int char float double
Long short signed unsigned
If else do while
For break continue switch
Case default consulting goto
Struct union void return
Static extern volatile register
Auto enum sizeof typedef

6. Explain identifier.
 Identifier is are the words which are defined by the programmer in a program.
 Identifier refers to the name of variable, array, function etc.
 It consists of letters, digits and underscore.
 First character must be an alphabet or underscore.
 Keywords cannot be use as identifier.
 Identifier name are case sensitive.
 The name of identifier should be meaningful.

2
7. Write the Basic Structure of C Program.
 Documentation section:
Documentation consists of a set of comment line(/* */) giving the name of the
program.
 Header File(Link Section):
Link section provides instruction to the compiler to link function from the system
library(Header Files like #include<stdio.h>).
 Constant Declaration:
Definition section defines all symbolic constants(e.g.-#define pi 3.14).
 Global declaration section:
There are some variable that are used more than one function. Such Variables are called global
variable and that is outside all the function. This section also declares the entire user define
functions.
 Main () function section:
Every c program must have one main () function section. This section contains
twoparts. Declaration part and executable part. Declaration part declares all the
variables used in the executable part. These two parts must be appearing
between opening and closing braces.

8. List out Advantages of ‘C’ language.


 C language contains rich set of built in functions.
 ‘C’ operators can be used to write any complex program.
 ‘C’ is a middle level language, which combines the capabilities of an assembly language
and higher level language.
 Programs written in c are efficient and fast, because it contains variety of data types and
powerful operators.
 ‘C’ is highly portable, means c program written for one computer can be run onanother with
little or no modification.

9. Explain constant in detail.


 Constant means fixed value.
 The value of the constant cannot change during execution of the program.
 C supports following types of constant:
1. Integer
2. Real
3. Character
4. String
1. Integer constant: Integer constant is a sequence of digits.
 Integer constant can be +ve or –ve number.
 Special symbols such as space, comma, currency etc are not allowed.

3
 There are three types of integer.
Decimal: A decimal integer constant consist of any combination of digits from 0to 9.Example
123,-345,001.
Octal: An octal integer constant consists of any combination of digits from 0 to 7with a leading
0.Example:01234, 0564.
2. Real constant: Real constant is a sequence of digits with decimal points. Such aconstant are
used to represent weight, height etc.
3. Character constant: Character constant is a single character enclosed in a singlequotation
mark.
 Example: ‘a’
 Back slash constants are the special type of character constants which actuallyconsists of
two characters. These are known as escape sequences.
 The combination of backslash and a character is known as escape sequence.
 Escape sequence start with back slash ‘\’ character.
Escape Sequence Meaning
‘\0’ End of string
‘\n’ End of line
‘\t’ Horizontal tab
4. String Constant: String constant is a sequence enclosed in a double quotationmark.
Example: ‘’Hello’’
Constant can be declared in a program using count keyword.For
Example: const PIE = 3.14;

10. Define Variable & explain its rules.


 A variable is a name which is used to store a temporary value.
 The value of the variable may changes during execution of the program.
 Rules for naming variable:
 The variable name may consist of letters (A-Z, a-z), digits (0-9) and underscoresymbol ( _ ).
Example: int no_1; / int no1; / int NO1;

 The variable name must begin with a letter. Some system permit underscore as a first
character.
Example: int 1NO; is not valid
 The length should not be more than eight characters.
 Variable name should not be a keyword.
Example: int case is not valid
 A white space is not allowed in the name of variable.
Example: int NO 1; is not valid.
 Variable is case sensitive. Uppercase and lowercase are different.
 Example: int MAX;int max;
Here both MAX and max are treated as different variable.

11. Define Data Type and their types.


 Data type is used to specify which type of value to be stored in variable.
4
 There are four basic data types supported by C.

Type Size(Bytes) Size(Bits) Range Control String

char 1 8 -128 to +128 %c

int 2 16 -32768 to +32767 %d


float 4 32 3.4 e -38 to 3.4 e +38 %f
double 8 64 1.7 e -308 to 1.7 e +308 %ld

12. Define symbolic constants & list out Rules of defining symbolic constant.
 #define is a preprocessor directive which is used to defined symbolic constant.
 Symbolic name is a name of the constant, which we want to define.
 Value of the constant represents the value, which we want to assign to the constant.
Rules of defining symbolic constant
 The rules for naming symbolic constant are same as the rules for naming variables. Symbolic
names are written in capital letters to distinguish them from the normal variable.
 There should be no blank space between the pound sign ‘#’ and the word defines.
 ‘#’ must be the first character in the line.
1. A blank space is required between #define and symbolic name and between the symbolic
name and the value.
2. #define statement must not end with a semicolon.
3. After defining the symbolic constant they should not be assigned any other valuein the
program.
4. There is no need to declare data type for the symbolic constant.

13. Define Operator. & explain Arithmetic Operators with example.


 An operator is a some special characters (symbol) that tells the computer to perform
certain mathematical or logical manipulations.
Arithmetic Operators
Operator Meaning

+ Addition

- Subtraction

* Multiplication

/ Division
% modulo

5
Ex: a+b, a-b, a*b, a%b, a/b
where a & b variables & known as Operand (variable).
Example:
int a,b,sum,sub,div,mul,mod;a =
15;
b = 3;
sum = a+b; // sum = 18
sub = a-b; // sub = 12
mul = a*b; // mul = 45
div = a / b; // div = 5
mod = a%b; // mod = 0

14. Explain Relational Operator with example.


 Compare two quantities & depending on their relation.

Operator Meaning
< Is less than
<= Is less than or equal to
> Is greater than

>= Is greater than or equal to

== Is equal to
!= Is not equal to
 Relational operators are used in decision statements.
 Such as while & if to decide the course of action of a running program.
 Example:
int a = 15, b = 12;

Expression Result
a>b True
a<b False
a>=b True
a<=b False

a==b False

a!=b True

6
15. Explain Increment & Decrement Operators in detail.
 Increment Operator ++
 Decrement operator --
 The increment operator ++ adds 1 to the operand, while decrement operator --subtracts 1.
 We use the increment and decrement statements in for and while loops.
 A prefix operator first adds 1 to the operand and then the result is assigned to thevariable on
the left.
 A postfix operator first assigns the value to the variable on the left and then increment
the operand.
 Postfix Increment Operator
Example:
int a,b;
a=10;
b = a++;
printf(“a = %d”,a);
printf(“b = %d”,b);
Output:
a=11
b=10
 Prefix Increment Operator
Example:
int a,b;
a=10;
b = ++a;
printf(“a = %d”,a);
printf(“b = %d”,b);
Output:
a=11
b=11

 Postfix Decrement Operator


 Example:
int a,b;
a=10;
b = a--;
printf(“a = %d”,a);
printf(“b = %d”,b);
Output:
a=9
b=10
 Prefix Decrement Operator
 Example:
int a,b;
a=10;
b = --a;
printf(“a = %d”,a);
printf(“b = %d”,b);
7
Output:
a=9
b=9

16. Explain Conditional Operators (Turnery Operator) in detail.


 Syntax: exp1 ? exp2:exp3
 where, exp1,exp2 & exp3 are expressions.
 exp1 is evaluated first.
 If it is true then the expression exp2 is evaluated & becomes the value of anexpression.
 If exp1 is false, then exp3 is evaluated and its value becomes the value of theexpressions.
 Example:
a=25;
b=32;
ans=(a>b)?a:b;
In above example the answer is 35.

17. Explain the if….else statement with example.


 If the test expression is true then the true-clock statement are executed otherwisethe false-
clock statement are executed.
General Form :

Flowchart of if….else :

8
Example:
if(n%2==0)
{

printf(“ n is even ”);

}
else
{

printf(“ n is odd ”);

}
18. Explain the else if ladder with example.
 Used when we need multipath decisions.
General Form:
if(condition1)
statement1;
else if(condition2)
statement2;
else if(condition3)
statement3;
else
default-statement;
statement-x;

 In this, the condition are evaluated from top to downwards.


 When all the n conditions are become false, then the final else containing thedefault
9
statement will be executed.

19. Explain SWITCH Statement with example.


 We uses an if statement to control the selection. However, the complexity ofsuch a
program increases when the number of alternatives increases.
 And the program becomes more difficult to read and follow.
 The switch statement tests the value of a given variable against a list of case values and when a
match is found, a block of statements associated with that caseis executed.

 General Form
switch (expression)
{
case value1:
block-1;
break;
casevalue2:
block-2;
break;

default:
default-block;
break;
}
statement-x;
 Where, the expression is an integer expression or characters.
 Value1, value2….. Are constants or constant expression and are known as case
labels.
 Case labels end with a colon(:)
 When the switch is executed, the value of the expression is successfully comparedagainst the
values. If a case is found whose value matches with the value of the expression, then the block
of statement that follows the case are executed.

10
Example
switch( op)
{
case +:
ans = a + b;
break;

case -:
ans = a - b;
break;
default:
printf(“ wrong choice ”);
break;
}
printf(“ Answer is : %d”, ans);

20. Explain while loop with example.


 While loop is the entry control loop. Because in while loop first the condition ischecked.
 Syntax:
while (condition)
{
Body of the loop;
}

 {} is known as body of the loop. If body contain one statement then it is notnecessary to
enclose body of the loop in the pair of brace {}.
 In while loop, the condition is evaluated first and if it is true then the statement inthe body of
the loop is executed.
 After executing body , the condition is evaluated again and if it is true body isexecuted
again. This process is repeated as long as the condition is true. The control move out once
the condition is false.
 Flowchart:

11
Example: Print 1 to 10 numbers using while loop.
i =1;
while (i < = 10)
{
printf( “% d \n ” , i );i =
i+1;
}

21. Explain Do-while loop with example.


 Do..while loop is a exit control loop. Because after the executing the body of theloop the
condition is checked.
 Syntax:
Do
{
Body of the loop
}while(condition);

 In do..while loop the body is executed and then the condition is checked.
 If the condition is true the body is executed again and again, as long as thecondition is
true.
 The control moves out of loop once, the condition become false.
 The body of the loop is executed at least once even if the condition is false firsttime.
 Flowchart:

Example: Print 1 to 10 numbers using do---while loop.


i =1;
do{
printf( “% d \n ” , i );i =
i+1;
} while (i < = 10);

12
22. Give differences between While & Do-while loop.

While Do--while

It is entry control loop, means first condition is It is exit control loop, first body is executedand
checked, and if it is true thenbody of the loop then condition is checked and if the condition is
executes, otherwise nextstatement after the loop
true, then again body of the loop will be executed,
will be executed.
otherwise next statement after the loop will be
executed
At first time, condition is false, thenbody At first time, condition is false, at least oncethe
is not executed. body is executed.

Syntax: Syntax:
while (condition) Do
{ {
Body of the loop; Body of the loop
} }while(condition);

Example: Example:
i =1; i =1;
do do
{ {
printf( “% d \n ” , i );i = printf( “% d \n ” , i );i =
i+1; i+1;
} while (i < = 10); } while (i < = 10);

23. Explain for loop with example.


 Syntax:
For(Initialization ; Condition ; Increment or decrement)
{
Body of the loop;
}
 Initialization: We require one variable which is used to control the loop, which is called as
control variable. It executes only once. The control variable is initialized in the initialization
expression.
 Condition: The condition statement checks the value of the control variable. Ifthe condition
statement is true, the body of the loop is executed.
 Increment/Decrement: The increment/decrement of the control variable is done in this part.
After the incrementing/decrementing the value of control variable, it is tested using condition
if condition is true than again the body of loop is executed and this process is repeated until the
condition become false.
 If the body of the loop contains only one statement, then { } is not required.

13
Example: Print 1 to 10 numbers using for loop.

for(i = 1; i < =10 ; i++)


{
printf(“ %d \n “, i ) ;
}

24. Define Arrays with Syntax & example.


 An array is a collection of variables of same data type known by a same name.
Syntax:
 Data type arrayname [size] ;
 Data type: it defines the type of the array element, like int, float, char,double etc.
 Array name: it is the name of variable which represent array.
 Size: which is represents within[ ] symbol represent the size of the array.

The above array is declared as int a[5];a[0] =


4;
a[1] = 5;
a[2] = 33;
a[3] = 13;
a[4] = 1;
4,5,33,13,1 are actual data items … ( in our case Roll numbers )
0,1,2,3,4 are index variables ..( similar to ‘i’ in for loop / Subscript variable )
14
25. How to Declaration Array.
 Array has to be declared before using it in C Program. Array is nothing but thecollection of
elements of similar data types.
 Syntax
 <data_type> array_name [size1][size2] .............. [sizen];
Syntax Parameter Significance
data_type Data Type of Each Element of the array
Array_name Valid variable name
size Dimensions of the Array
Examples : Declaring 1D array
int roll[10]; // Array of 10 integer roll numbers
In the above example we are declaring the integer array of size 10. Array is singledimensional

26. Explain Advantage & disadvantage of Array.


Advantages of Array
1. We can use one name for similar objects and save them with same name butdifferent
indexes.
2. 2- D array are used to represent matrices.
3. It can be used to implement other data structure like linked list, stack, queue , tree, graph etc.
Disadvantages of Array
1. We must know in advance how many elements are to be stored in array.
2. If we allocate more memory than requirement than the memory space will bewasted.

27. Explain Accessing an array with example.


 Array elements are randomly accessed using the subscript variable.
 Array can be accessed using array-name and subscript variable written inside pairof square
brackets [ ].
int mark[5] = {19, 10, 8, 17, 9};
 mark[0] is equal to 19
 mark[1] is equal to 10
 mark[2] is equal to 8
 mark[3] is equal to 17
 mark[4] is equal to 9

15
 Introduction to a String:
String:
A string is a sequence of zero or more characters followed by a NULL '\0'
character. String is always terminating with NULL '\0' character.

Declaration and initialization of string:

Syntax:
char stringname[size];
where size is the number of characters.
Example:
char city[10] ;
Initialization of string variable:
(1) Compile time:
char city[9]= " NEW YORK";
(2) Run time:
char city[9];
scanf("%s", city);
OR
char city[9];
gets(y);

 Pointer
Introduction to Pointer:
Pointer is a variable which store the address of another variable.
Advantage of pointer:
 Pointer reduces the code and improves the performance.
 We can return multiple values from a function using the pointer.
 It makes you able to access any memory location in the computer's memory.

Characteristics of Pointers:

 Pointer is a variable which can hold the address of another variable.


 A pointer is a derived data type.
 It contains memory addresses as their values.
 If a C pointer is assigned to the null value, it points nothing.
 The asterisk symbol, * is used to retrieve the value of the variable
 & ampersand symbol is used for retrieving the address of a variable.

16
 Types of pointer :
void pointer
Syntax:
void *variable name

 Void pointer is a pointer which has no specified data type.


 It is also known as generic pointer.
 Void pointer can be pointed to any data type.
 When void pointer is declared two bytes of memory is assign to it.
 It is used when return type or parameter is unknown.
 void pointers that have addresses, can be further typecast into other data types very easily.
Example:

include<stdio.h
>void main()
{
int a = 10;
void *p;
p = &a;
printf(“%d”, *(int *)p);
}

NULL Pointer:
 A pointer that is not assigned any value but NULL is known as the NULL pointer.
 If you don't have any address to be specified in the pointer at the time of declaration, you
canassign NULL value. It will provide a better approach.

int *p=NULL;

 Introduction to Functions:
Definition of Function: Function is a group of statement to perform a specific task.
Types of functions:
1. Library function
2. User-defined Function

 Types of Functions: Built-in and user defined Functions


Library function(Built-in):
 The function which is develop by system itself is known as Library function .
 Example: printf(),scanf(),sqrt(),ceil() etc …
 Library function is all ready exist in system.

17
User-defined Function:
 The function which is develop by user itself is known as User-defined function.
 Example: main()
 User-defined function is created by the user at the time of writing of program.

 Call by Value and call by Reference


Call By Value with example:

When a function is called using the value of variables, then it is known as call by
value.
 The value of variables, which are to be passed, will be copied from the variables of the calling functions
to the variables of the called functions.
 All the process done on the duplicate variables rather then actual variables.
Example:

#include <stdio.h>
void swap(int , int); // function prototype
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
swap(a,b); // function call
printf("After swapping values in main a = %d, b = %d\n",a,b); //actual parameters a=10, b=20
}
}
void swap (int a, int b)
{
int temp;
temp = a;
a=b;
b=temp;
printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameters, a=20, b=10
}

Call By Reference with example:

 When a function is called using the address of variables, then it is known as call by reference.
 Instead of passing the value of variables from calling function to the called function, addresses of the
variables are passed.

18
 All the process done on the actual variables.
Example:

#include <stdio.h>
void swap(int *, int *); // function prototype
void main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
swap(&a,&b); // function call
printf("After swapping values in main a = %d, b = %d\n",a,b); // actual parameters a = 20, b = 10
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters a=20, b=10
}

 Recursion

 Function call itself is called Recursion.


 Recursive call to a function may be conditional or unconditional.
 In conditional recursive call, function is terminated when condition is false.
 In unconditional recursive, function is called infinitely.

 It is used to find the factorial of a given number.


 Example :
 void main()
 {
 printf(“Recursion”);
 main();

 }
 Example :

19
void main()
{

function1();

}
function1()
{

function1();

Advantages of Recursion:
 The recursion is very flexible in data structure like stacks.
 Using recursion, the length of the program can be reduced.
Disadvantages of Recursion:
 It requires extra storage space.
 The recursion function is not efficient in execution speed and time.
 Proper termination is required; otherwise it leads to infinite loop.

 Storage Classes: -auto, static, register and extern

Storage Classes in C:

Storage classes in C are used to determine the lifetime, visibility, memory location, and initial value of
avariable. There are four types of storage classes in C

 Automatic

 External

 Static

 Register

Storage Storag Default Scope Lifetime


Classes ePlace Value

auto RAM Garbage Local Within function


Value

extern RAM Zero Global Till the end of the main program Maybe
declaredanywhere in the program

20
static RAM Zero Local Till the end of the main program, Retains
value between multiple functions call

register Register Garbage Local Within the function


Value

 Introduction to Structures and Declaration, Initialization and


accessing of Structures:
 Structure is a collection of logically related data items with different datatype.
 Structure must be defined first, that may be used later to declare structure.
Syntax:
Struct structure_name
{
Data type
member1;
data type
member2;
---
Data type member N;
};
 Struct is a keyword, it declares structure to hold data.
 Structure_Name is the name of structure(structure tag).
 member1,member2,…are members of structure.

Example:
Struct student
{
Char name[20];
int roll_no;
float per;
}s1;
Here s1 is a structure variable.

Structure
initialization:
Example:
struct student
{
char name[20];
int roll_no;
float per;
}s1={"Arav",20,85.5};

21
 User-defined Datatypes: enum, typedef

Enumerated Data Type:


 Enumerated data type is user defined data type.
 Using enumerated data type we can create more than one symbolic constant at a time.

Syntax: enum identifier{ value1, value2,value3};

Here, enum is a keyword to declare enumerated data


type. Identifier is a user defined enumerated data type.

Fo rExample:

#include<stdio.h>
enum week{Mon=1,Tue,Wed,Thur,Fri,Sat,Sun};
void main()
{
enum week day;
day = Wed;
printf("%d",day);
getch();
}
Output:2

Typedef:
The typedef is a keyword that is used in C programming to provide existing data types with a new
name. typedef keyword is used to redefine the name already the existing name.
When names of data types become difficult to use in programs, typedef is used with user-defined data
types.
Syntax:
typedef<existing_name><alias_name>
Example:
typede flong mylong

 Files
Introduction to text Files
File:
A file is a group of related data which is stored in a
disk. File operations:
(1) Naming a file
(2) Opening a file

22
(3) Reading data from a file
(4) Writing data to a file
(5) Closing a file

fopen() and fclose():


fopen():
Create a new file or open an existing file.
Syntax:
FILE *fp;
fp=fopen("filename","mode");
Here, fp is a file pointer to the data type FILE.
Second statement open a file named file name and mode specify the opening of this file.
Example:
FILE *fp;
fp=fopen("E:\\abc.txt","r");
fclose():
Close the file
A file must be closed as soon as all operation on it have been completed.
Syntax:
fclose(filepointer);
Example:
FILE *fp;
fp=fopen("E:\\abc.txt","r");

fclose();

23
Seat No.: ________ Enrolment No.______________

GUJARAT TECHNOLOGICAL UNIVERSITY


DIPLOMA ENGINEERING – SEMESTER –1 • EXAMINATION – WINTER - 2021

Subject Code:4310702 Date :22-03-2022


Subject Name: Basic Computer Programming
Time:10:30 AM TO 1:00 PM Total Marks:70
Instructions:
1. Attempt all questions.
2. Make Suitable assumptions wherever necessary.
3. Figures to the right indicate full marks.
4. Use of programmable & Communication aids are strictly prohibited.
5. Use of non-programmable scientific calculator is permitted.
6. English version is authentic.

Q.1 Answer any seven out of ten. દશમ ાંથી કોઇપણ સ તન જવ બ આપો. 14
1. State TRUE or FALSE
a) C is a low level language.
b) # symbol is used to denote preprocessor statement.
૧. સ ચાં છે કે ખોટાં તે જણ વો.
a) C એક નીચ લેવલની ભ ષ છે .
b) # નનશ ની નિિોસેસર ને બત વવ વપર ય છે .
2. Define algorithm. Write advantages of algorithm. (write at least two
advantages)
૨. અલગોરીધમ ની વ્ય ખ્ય આપો. તેન ફ યદ લખો. (ઓછ મ ાં ઓછ બે ફ યદ લખવ )
3. State TRUE or FALSE
a) main( ) is inbuilt function in C.
b) global variable automatically initialized by 0.
૩. સ ચાં છે કે ખોટાં તે જણ વો.
a) main( ) એ C મ ાં રહેલ ઇનનબલ્ટ ફાંક્શન છે .
b) ગ્લોબલ વેરીએબલ આપમેળે 0 થી િ રાંનભત થ ય છે .
4. Define data type. List different derived data types.
૪. ડેટ ટ ઈપને વ્ય ખ્ય ઇત કરો. ત રવેલ ડેટ ટ ઈપની ય દી લખો.
5. Fill in the blanks by selecting proper option.
a) Array name represents the address of __________ element.
i. last ii. first
iii. middle iv. highest

b) To find the total numbers of characters in the string, __________


function is used.
i. strchar( ) ii. strlength( )
iii. strlen( ) iv. strstr( )
૫. સ ચો નવકલ્પ પસાંદ કરી ખ લી જગ્ય પૂરો.
a) એરેનાં ન મ __________ ઘટકનાં સરન માં બત વે છે .
i. છે લ્લ ii. પહેલ
iii. વચ્ચેન iv. મહત્તમ

b) સ્ટ્રીંગમ ાં રહેલ કલ અક્ષરોને ગણવ મ ટે __________ ફાંક્શન ઉપયોગમ ાં લેવ ય છે .


i. strchar( ) ii. strlength( )
1/4
iii. strlen( ) iv. strstr( )
6. Define recursion. Write one advantage and one disadvantage of recursion.
૬. રીકરશનની વ્ય ખ્ય આપો. તેનો એક ફ યદો અને એક ગેરફ યદો લખો.
7. Write a C program to add two integer values using pointers.
૭. પોઈન્ટરનો ઉપયોગ કરી બે ઇન્ટીજર કકમતોનો સરવ ળો લરવ નો C િોગ્ર મ લખો.
8. Write any four characteristics of an array.
૮. એરે ની કોઈ પણ ચ ર લ ક્ષનણકત ઓ લખો.
9. Give the definition of function. List the categories of function.
૯. ફાંક્શનની વ્ય ખ્ય આપો. તેન િક રની ય દી તૈય ર કરો.
10. List four operations that can be performed on file.
૧૦. ફ ઇલ પર થઈ શકત કોઈ પણ ચ ર ક યોની ય દી લખો.
Q.2 (a) Explain while loop with example. 03
િશ્ન. ર (અ) while loop નાં વણણન ઉદ હરણ સ થે કરો. ૦૩
OR
(a) Explain pointer to pointer with example. 03
(અ) પોઈન્ટર થી પોઈન્ટર નાં વણણન ઉદ હરણ સ થે કરો. ૦૩
(b) Explain scanf( ) with example. 03
(બ) scanf( ) નાં વણણન ઉદ હરણ સ થે કરો. ૦૩
OR
(b) Explain function with no argument and no return type with example. 03
(બ) કોઈ પણ આગ્યણમેન્ટ તથ રીટનણ ટ ઈપ વગરન ફાંક્શનનાં વણણન ઉદ રણ સ થે કરો. ૦૩
(c) List different relational operators. Explain any one with example. 04
(ક) રીલેશનલ ઓપરેટર ની ય દી બન વો. તેમ ાંથી કોઈ પણ એકનાં વણણન ઉદ રણ સ થે કરો. ૦૪
OR
(c) List different logical operators. Explain any one with example. 04
(ક) લોજીકલ ઓપરેટર ની ય દી બન વો. તેમ ાંથી કોઈ પણ એકનાં વણણન ઉદ રણ સ થે કરો. ૦૪
(d) Write a C program to find the area of a circle. (Note: take radius from user) 04
(ડ) વતણળનાં ક્ષેત્રફળ શોધવ મ ટેનો C િોગ્ર મ લખો. ૦૪
OR
(d) Write a C program to find the maximum number out of given three numbers. 04
(ડ) આપેલ ત્રણ અાંકો મ ાંથી મહત્તમ શોધવ મ ટેનો C િોગ્ર મ લખો. ૦૪

Q.3 (a) Give the differences between BREAK and CONTINUE. (write at least three 03
differences)
િશ્ન. 3 (અ) BREAK અને CONTINUE વચ્ચેનો તફ વત લખો. (ઓછ મ ાં ઓછ ત્રણ તફ વત લખવ ) ૦૩
OR
(a) Differentiate between structure and union. (write minimum three points) 03
(અ) structure અને union વચ્ચેનો તફ વત લખો. (ઓછ મ ાં ઓછ ત્રણ તફ વત લખવ ) ૦૩
(b) Write a short note on flow chart. 03
(બ) ફ્લો ચ ટણ પર ટૂાંકનોંધ લખો. ૦૩
OR
(b) Explain entry controlled loop with an example. 03
(બ) entry controlled loop ઉદ હરણ સ થે સમજાવો. ૦૩
(c) Explain call by value with example. 04

2/4
(ક) call by value ઉદ હરણ સ થે સમજાવો. ૦૪
OR
(c) Explain call by reference with example. 04
(ક) call by reference ઉદ હરણ સ થે સમજાવો. ૦૪
(d) Write a C program using loop to print the following output pattern. 04
1
21
321
4321
(ડ) લૂપ નો ઉપયોગ કરી નીચેની આઉટપૂટ પેટનણ છ પવ મ ટેનો C િોગ્ર મ લખો. ૦૪
1
21
321
4321
OR
(d) Write a C program using loop to print the following output pattern. 04
1
23
456
7 8 9 10
(ડ) લૂપ નો ઉપયોગ કરી નીચેની આઉટપૂટ પેટનણ છ પવ મ ટેનો C િોગ્ર મ લખો. ૦૪
1
23
456
7 8 9 10
Q.4 (a) Write a C program to copy the content of a string STR1 into another string 03
STR2. (Note: take two string variables as STR1 and STR2. STR1 = ‘AABU’
િશ્ન. ૪ (અ) એક સ્ટ્રીંગ STR1 મ ાંન ઘટકોને બીજી સ્ટ્રીંગ STR2 મ ાં નકલ કરવ મ ટેનો C િોગ્ર મ લખો. ૦૩
(નોંધ: બે સ્ટ્રીંગ વેરીએબલ STR1 તથ STR2 લેવ . તેમજ STR1 = ‘AABU’ લેવ.ાં )
OR
(a) Write a C program to check whether the entered string is palindrome or not. 03
(અ) દ ખલ કરેલ સ્ટ્રીંગ પેલીન્રોમ (મરજબાંધ) છે કે નહીં તે તપ સતો C િોગ્ર મ લખો. ૦૩
(b) Explain 1-D array with example. 04
(બ) 1-D એરે ઉદ હરણ સ થે સમજાવો. ૦૪
OR
(b) Explain UDF with example. 04
(બ) UDF ઉદ હરણ સ થે સમજાવો. ૦૪
(c) Define pointer. 07
Write advantages and disadvantages of pointer.
Write a C program to swap the values of two integer variables using pointer.
(ક) પોઈન્ટરની વ્ય ખ્ય આપો. ૦૭
પોઈન્ટરન ફ યદ અને ગેરફ યદ લખો.
બે ઇન્ટીજર વેરીએબલ ને અદલ બદલ કરવ મ ટેનો C િોગ્ર મ પોઇન્ટર નો ઉપયોગ કરી લખો.
Q.5 (a) Write a C program to find the sum of all the numbers entered in array. (Note: 04
take single dimensional array of size 10)
િશ્ન. ૫ (અ) એરેમ ાં દ ખલ કરેલ તમ મ અાંકોનો સરવ ળો કરવ નો C િોગ્ર મ લખો. (નોંધ: 10 ન મ પનો એક ૦૪
પ કરમ નણક એરે લેવો)
(b) Explain fprintf( ) with example. 04

3/4
(બ) fprintf( ) ઉદ હરણ સ થે સમજાવો. ૦૪
(c) Write a C program to print the numbers in reverse manner on the screen using 03
for loop. (Note: 20 will be the first number and 0 will be the last number to
print in the screen)
(ક) લૂપની મદદથી અાંકોને ઉલટ ક્રમમ ાં સ્ટ્ક્રીન પર છ પવ નો લખવ નો C િોગ્ર મ લખો. (નોંધ: સ્ટ્ક્રીન ૦૩
પર િથમ અાંક 20 તથ છે લ્લો અાંક 0 છ પવો)
(d) Differentiate between array and structure. (write at least three points) 03
(ડ) એરે અને સ્ટ્રક્ચર ને જદ ત રવો. (ઓછ મ ાં ઓછ ત્રણ મદ્દ લખવ ) ૦૩

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

4/4
Seat No.: ________ Enrolment No.______________

GUJARAT TECHNOLOGICAL UNIVERSITY


DIPLOMA ENGINEERING – SEMESTER – 1 - EXAMINATION – SUMMER-2022

Subject Code:4310702 Date :01-09-2022


Subject Name:Basic Computer Programming
Time:02:30 PM TO 05:00 PM Total Marks:70
Instructions:
1. Attempt all questions.
2. Make Suitable assumptions wherever necessary.
3. Figures to the right indicate full marks.
4. Use of simple calculators and non-programmable scientific calculators are permitted.
5. English version is authentic.

Q.1 (a) Draw and Explain Symbols of flowchart. 03


(અ) ફ્લોચાર્ટના સિમ્બોલ દોરો અને િમજાવો. ૦૩
(b) Explain C Data types in detail 04
(બ) C ડેર્ા typeસવષે સવસ્ત્રુતા માાં િમજાવો. ૦૪
(c) Write difference between algorithm and flowchart? 07
(ક) અલગોરરધમ અને ફ્લોચાર્ટ વચ્ચેનો તફાવત િમજાવો. ૦૭
OR
(c) Explain basic structure of C program. 07
(ક) C પ્રોગ્રામ નુાં બેિીક સ્ત્રક્ચર િમજાવો. ૦૭
Q.2 (a) Write an algorithm to check even and odd number. 03
(અ) એકી અને બેકી નાંબર ચેક કરવાનો અલગોરરધમ લખો. ૦૩
(b) List available storage class in C. 04
(બ) C ના સ્ત્ર્ોરેજ ક્લાિ ના નામ જણાવો. ૦૪
(c) Explain Different types of Operators in C 07
(ક) જુ દા જુ દા ઓપેરેર્ેર ના નામ આપીને િમજાવો. ૦૭
OR
Q.2 (a) Explain feature of C language. 03
(અ) C ભાષા ની વિવિષ્ટતા સમજાિો. ૦૩
(b) Write a program to calculate area of triangle. 04
(બ) વિકોણ નું ક્ષેિફળ િોધિાનો પ્રોગ્રામ લખો. ૦૪
(c) Explain switch statement 07
(ક) સ્િીચ સ્ટે ટમેન્ટ સમજાિો. ૦૭
Q.3 (a) Explain else if ladder with example. 03
(અ) Else if ladderઉદાહરણ આપી િમજાવો. ૦૩
(b) Explain call by value with example. 04
(બ) Call by valueઉદાહરણ આપી િમજાવો. ૦૪
(c) Compare entry controlled and exit controlled loop with example. 07
(ક) Entry controlled and exit controlled loop નો તફાવત ઉદાહરણ આપી ૦૭
િમજાવો.
OR
Q.3 (a) Define Constants. Explain constants in C with example. 03
(અ) Constant ની વ્યાખ્યા લખી. C માાં આવેલ Constant સવષે િમજાવો. ૦૩
(b) Explain enumerated data type with example 04

1
(બ) Enumerated data type ઉદાહરણ આપી િમજાવો. ૦૪
(c) Draw flowchart and explain for loop with example. 07
(ક)for લૂપ નો ફલોચાર્ટ ડ્રો કરો અને ઉદાહરણ આપી િમજાવો. ૦૭
Q.4 (a) Define Array. Explain initialization of two dimensional array. 03
(અ) Array ની વ્યાખ્યા આપી. Two dimensional array નુાં ૦૩
initializationસમજાિો.
(b) State the difference between structure and union. 04
(બ) Structure and union નોતફાવત િમજાવો. ૦૪
(c) Explain recursion with example. 07
(ક) Recursion ઉદાહરણ આપી િમજાવો. ૦૭
OR
Q.4 (a) Explain following string function with example. (1) strcpy (2) strcat 03
(3) strcmp (4) strlen
(અ) ઉપર ના ફાંક્શન ઉદાહરણ આપી િમજાવો ૦૩
(1) strcpy (2)strcat (3) strcmp (4)strlen
(b) Explain gets( ) and puts( ) functions. 04
(બ) gets( ) and puts( ) ફાંક્શન િમજાવો. ૦૪
(c) What is user defined and library function? Explain with two 07
example of each.
(ક) User defined and library ફાંક્શન શુાં છે .બે ઉદાહરણ આપી િમજાવો. ૦૭
Q.5 (a) Explain ?: operator with example. 03
(અ) ?: ઓપેરેર્ર ઉદાહરણ આપી િમજાવો. ૦૩
(b) Define pointer. Explain how pointers are declared and initialized. 04
(બ) પોઈન્ર્ર શુાં છે . પોઇન્ર્રને declared and initialized કરી ને િમજાવો. ૦૪
(c) Write a program to find average of 1 to 10. 07
(ક) ૧ થી ૧૦ િુધીની િાંખ્યાનો એવરેજ શોધવાનો પ્રોગ્રામ લખો. ૦૭
OR
Q.5 (a) Explain fscanf() & fprintf () functions with examples. 03
(અ) fscanf() & fprintf() ફાંક્શન ઉદાહરણ આપી િમજાવો. ૦૩
(b) Explain one dimensional array with example. 04
(બ) સિાંગલ ડાઇમેન્શન array ઉદાહરણ આપી િમજાવો. ૦૪
(c) Write a program to insert and display element in 2*2 matrixes 07
(ક) 2*2 મેરરક્ષ માાં એલીમેન્ર્ ઇન્િર્ટ અને રડસ્ત્્લેકરવાનો પ્રોગ્રામ લખો. ૦૭

You might also like