BCA 1st Programming in Caaa
BCA 1st Programming in Caaa
Syllabus
Unit-I
Unit-II
Unit-III
Unit-IV
INDEX
S. No Contents Page No
5 Functions 73-87
6 Arrays 88-99
7 Strings 100-112
9 Pointers 123-126
2
BCA 1st Sem ( Programming In C)
UNIT –I
3
BCA 1st Sem ( Programming In C)
Data Representation
•Data refers to the symbols that represent people, events, things, and ideas. Data
can be a name, a number, the colors in a photograph, or the notes in a musical
composition.
•Data Representation refers to the form in which data is stored, processed, and
transmitted.
Number systems are the technique to represent numbers in the computer system
architecture, every value that you are saving or getting into/from computer
memory has a defined number system.
A Binary number system has only two digits that are 0 and 1. Every number
(value) represents with 0 and 1 in this number system. The base of binary number
system is 2, because it has only two digits.
4
BCA 1st Sem ( Programming In C)
Octal number system has only eight (8) digits from 0 to 7. Every number (value)
represents with 0,1,2,3,4,5,6 and 7 in this number system. The base of octal
number system is 8, because it has only 8 digits.
5
BCA 1st Sem ( Programming In C)
Decimal number system has only ten (10) digits from 0 to 9. Every number (value)
represents with 0,1,2,3,4,5,6, 7,8 and 9 in this number system. The base of decimal
number system is 10, because it has only 10 digits.
6
BCA 1st Sem ( Programming In C)
Flowchart
The flowchart shows the steps as boxes of various kinds, and their order by
connecting the boxes with arrows. This diagrammatic representation illustrates a
solution model to a given problem. Flowcharts are used in analyzing, designing,
documenting or managing a process or program in various fields.
ANSI/ISO
Name Description
Shape
"receive product".
8
BCA 1st Sem ( Programming In C)
9
BCA 1st Sem ( Programming In C)
Problem Analysis
10
BCA 1st Sem ( Programming In C)
11
BCA 1st Sem ( Programming In C)
2. Algorithm Development
3. Flow Chart
4. Program Coding
Compilation
First, the source ‘.java’ file is passed through the compiler, which then
encodes the source code into a machine independent encoding, known
as Bytecode. The content of each class contained in the source file is
stored in a separate ‘.class’ file. While converting the source code into
the bytecode.
Execution
the JVM, and then goes through three main stages before the final
machine code is executed.
7. Documentation
The documentation section contains a set of comment including the
name of the program other necessary details. Comments are ignored
by compiler and are used to provide documentation to people who
reads that code.
Decision tree
13
BCA 1st Sem ( Programming In C)
A decision tree is a decision support tool that uses a tree-like model of decisions
and their possible consequences, including chance event outcomes, resource
costs, and utility. It is one way to display an algorithm that only contains
conditional control statements.
Decision trees are commonly used in operations research, specifically in decision
analysis, to help identify a strategy most likely to reach a goal, but are also a
popular tool in machine learning.
Decision tree algorithm falls under the category of supervised learning. They
can be used to solve both regression and classification problems.
Decision tree uses the tree representation to solve the problem in which each
leaf node corresponds to a class label and attributes are represented on the
internal node of the tree.
We can represent any Boolean function on discrete attributes using the
decision tree.
14
BCA 1st Sem ( Programming In C)
Below are some assumptions that we made while using decision tree:
As you can see from the above image that Decision Tree works on the Sum of
Product form which is also known as Disjunctive Normal Form. In the above
image, we are predicting the use of computer in the daily life of the people.
In Decision Tree the major challenge is to identification of the attribute for the root
node in each level. This process is known as attribute selection.
Pseudo code
15
BCA 1st Sem ( Programming In C)
Advantages of pseudocode –
• It enables the programmer to concentrate only on the algorithm part of the code
development.
Start Program
Enter two number A,B
Add the number together
Print add
End program
16
BCA 1st Sem ( Programming In C)
Now, let's look at a few more simple examples of pseudo code. Here is a
pseudocode to compute the area of a rectangle:
Enter length, l
Enter width, w
Compute Perimeter = 2*l + 2*w
Display Perimeter of a rectangle Remember, writing basic pseudocode is not like
writing an actual coding language. It cannot be compiled or run like a regular
program. Pseudocode can be written how you want. But some companies use
specific pseudocode syntax to keep everyone in the company on the same page.
Syntax is a set of rules on how to use and organize statements in a programming
language. By adhering to specific syntax, everyone in the company can read and
understand the flow of a program. This becomes cost effective and there is less
time spent finding and correcting errors.
Advantages of Pseudocode
Disadvantages of Pseudocode
17
BCA 1st Sem ( Programming In C)
Algorithm in Programming
Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 5: Display sum
Step 6: Stop
Step 1: Start
Step 2: Declare variables a,b and c.
Step 3: Read variables a,b and c.
Step 4: If a>b
If a>c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b>c
Display b is the largest number.
Else
Display c is the greatest number.
Step 5: Stop
Advantages of Algorithms:
Disadvantages of Algorithms:
Characteristics of Algorithms:
Introduction to C
Historical development of C
By 1960’s many computer language exist but each has been developed for a
specific purpose. Eg. COBOL for business and commercial applications,
FORTRAN for engineering and scientific purposes etc.
The C language derives its name from the fact that it is based on a language
developed by ken Thompson, another programmer at Bell laboratories . He
adapted it from a language known as basic combined programming
language(BCPL). To distinguish his version of language from BCPL, Thompson
named it B language , which was the first letter of BCPL. When the language was
modified and improved to its present state, the second letter of BCPL, C was
chosen to represent the new version by Dennis Ritchie.
Merits of C
Like every other language 'C' also has its own character set. A program is a set of
instructions that when executed, generate an output. The data that is processed by a
20
BCA 1st Sem ( Programming In C)
program consists of various characters and symbols. The output generated is also a
combination of characters and symbols.
Letters
Numbers
Special characters
White spaces (blank spaces)
A compiler always ignores the use of characters, but it is widely used for
formatting the data. Following is the character set in 'C' programming:
1. Letters
o Uppercase characters (A-Z)
o Lowercase characters (a-z)
2. Numbers
o All the digits from 0 to 9
3. White spaces
o Blank space
o New line
o Carriage return
o Horizontal tab
4. Special characters
o Special characters in 'C' are shown in the given table,
Token
A token is the smallest unit in a 'C' program. A token is divided into six different
types as follows,
Tokens in C
Keywords have fixed meanings, and the meaning cannot be changed. They act as a
building block of a 'C' program. There are total 32 keywords in 'C'. Keywords are
written in lowercase letters.
What is a Variable?
A variable is an identifier which is used to store some value. Constants can never
change at the time of execution. Variables can change during the execution of a
program and update the value stored inside it.
Example: Height, age, are the meaningful variables that represent the purpose it is
being used for. Height variable can be used to store a height value. Age variable
can be used to store the age of a person
Following are the rules that must be followed while creating a variable:
height or HEIGHT
23
BCA 1st Sem ( Programming In C)
_height
_height1
My_name
1height
Hei$ght
My name
For example, we declare an integer variable my_variable and assign it the value
48:
int my_variable;
my_variable = 48;
By the way, we can both declare and initialize (assign an initial value) a variable in
a single statement:
Global variables are the variables which are declared or defined below the header
files inclusion section or before the main () function. These variables have global
scope to the program in which they are declared. They can be accessed or modified
in any function of the program.
Global variable can also be accessed in another files too (for this, we have to
declare these variables as extern in associate header file and header file needs to be
included within particular file).#include <stdio.h>
#include<stdio.h>
/*global variables*/
24
BCA 1st Sem ( Programming In C)
int a,b;
int main()
/*local variables*/
int x,y;
x=10;
y=20;
setValues();
printf("a=%d, b=%d\n",a,b);
printf("x=%d, y=%d\n",x,y);
return 0;
Constants
Constants are the fixed values that never change during the execution of a
program. Following are the various types of constants:
I. Integer constants
25
BCA 1st Sem ( Programming In C)
2. Octal constant contains digits from 0-7, and these types of constants are
always preceded by 0.
The octal and hexadecimal integer constants are very rarely used in programming
with 'C'.
Like integer constants that always contains an integer value. 'C' also provides real
constants that contain a decimal point or a fraction value. The real constants are
also called as floating point constants. The real constant contains a decimal point
and a fractional value.
26
BCA 1st Sem ( Programming In C)
V. Symbolic Constants
Expressions
An expression is a formula in which operands are linked to each other by the use of
operators to compute a value. An operand can be a function reference, a variable,
an array element or a constant.
o Arithmetic expressions
o Relational expressions
o Logical expressions
o Conditional expressions
Each type of expression takes certain types of operands and uses a specific set of
operators. Evaluation of a particular expression produces a specific value.
Statement
1. IF statement
2. IF Else Statement
3. Break statement
4. Goto statement
5. Switch statement
6. Continue statement
Data types
'C' provides various data types to make it easy for a programmer to select a suitable
data type as per the requirements of an application. Following are the three data
types:
Size in
Data type Range
bytes
29
BCA 1st Sem ( Programming In C)
Integer is nothing but a whole number. The range for an integer data type varies
from machine to machine. The standard range for an integer data type is -32768 to
32767.
Each data type differs in range even though it belongs to the integer data type
family. The size may not change for each data type of integer family.
The short int is mostly used for storing small numbers, int is used for storing
averagely sized integer values, and long int is used for storing large integer values.
Whenever we want to use an integer data type, we have place int before the
identifier such as,
int age;
Here, age is a variable of an integer data type which can be used to store integer
values.
Like integers, in 'C' program we can also make use of floating point data types.
The 'float' keyword is used to represent the floating point data type. It can hold a
floating point value which means a number is having a fraction and a decimal part.
A floating point value is a real number that contains a decimal point. Integer data
type doesn't store the decimal part hence we can use floats to store decimal part of
a value.
Generally, a float can hold up to 6 precision values. If the float is not sufficient,
then we can make use of other data types that can hold large floating point values.
The data type double and long double are used to store real numbers with precision
up to 14 and 80 bits respectively.
float division;
double BankBalance;
Character data types are used to store a single character value enclosed in single
quotes.
Example,
Char letter;
A void data type doesn't contain or return any value. It is mostly used for defining
functions in 'C'.
Example,
int main()
{
int x, y;
float salary = 13.48;
char letter = 'K';
x = 25;
y = 34;
int z = x+y;
printf("%d \n", z);
printf("%f \n", salary);
printf("%c \n", letter);
return 0;}
Output: 59
13.480000
K
31
BCA 1st Sem ( Programming In C)
We can declare multiple variables with the same data type on a single line by
separating them with a comma. Also, notice the use of format specifiers in printf
output function float (%f) and char (%c) and int (%d).
C allows the feature called type definition which allows programmers to define
their identifier that would represent an existing data type. There are three such
types:
32
BCA 1st Sem ( Programming In C)
values.
C Operators
Operators are used in c for manipulating the data store into the variables .
Types of Operators
I. Arithmetic
II. Relational
III. Logical
IV. Bitwise
I. C Arithmetic Operators
* multiplication
/ division
Output
a+b = 13
a-b = 5
a*b = 36
a/b = 2
34
BCA 1st Sem ( Programming In C)
A relational operator checks the relationship between two operands. If the relation
is true, it returns 1; if the relation is false, it returns value 0.
== Equal to 5 == 3 is evaluated to 0
#include<stdio.h>
int main()
return0;
Output
5 == 5 is 1
5 == 10 is 0
5 > 5 is 0
5 > 10 is 0
5 < 5 is 0
5 < 10 is 1
5 != 5 is 0
5 != 10 is 1
5 >= 5 is 1
5 >= 10 is 0
5 <= 5 is 1
5 <= 10 is 1
36
BCA 1st Sem ( Programming In C)
#include<stdio.h>
int main()
return0;
Output
(a == b) && (c > b) is 1
(a == b) && (c < b) is 0
(a == b) || (c < b) is 1
(a != b) || (c < b) is 0
!(a != b) is 1
!(a == b) is 0
38
BCA 1st Sem ( Programming In C)
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
V. Other Operators
Comma Operator
Comma operators are used to link related expressions together. For example:
1. int a, c =5, d;
The sizeof is a unary operator that returns the size of data (constants, variables,
array, structure, etc).
#include<stdio.h>
int main()
int a;
float b;
double c;
39
BCA 1st Sem ( Programming In C)
char d;
return0;
Output
#include<stdio.h>
int main()
40
BCA 1st Sem ( Programming In C)
printf("++a = %d \n",++a);
printf("--b = %d \n",--b);
printf("++c = %f \n",++c);
printf("--d = %f \n",--d);
return0;
Output
++a = 11
--b = 99
++c = 11.500000
--d = 99.500000
Here, the operators ++ and -- are used as prefixes. These two operators can also be
used as postfixes like a++ and a--. Visit this page to learn more about how
increment and decrement operators work when used as postfix.
C Assignment Operators
= a=b a=b
+= a += b a = a+b
-= a -= b a = a-b
41
BCA 1st Sem ( Programming In C)
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b
Conditional Operator
The behavior of the conditional operator is similar to the 'if-else' statement as 'if-
else' statement is also a decision-making statement.
In this tutorial, you'll learn about the standard library functions in C. More
specifically, what are they, different library functions in C and how to use them in
your program.
C Standard library functions or simply C Library functions are inbuilt functions in
C programming.
43
BCA 1st Sem ( Programming In C)
The prototype and data definitions of these functions are present in their respective
header files. To use these functions we need to include the header file in our
program. For example,
If you want to use the printf() function, the header file <stdio.h> should be
included.
#include <stdio.h>
int ma in()
{
printf("Catch me if you can.");
}
If you try to use printf() without including the stdio.h header file, you will get an
error.
1. They work
One of the most important reasons you should use library functions is simply
because they work. These functions have gone through multiple rigorous testing
and are easy to use.
2. The functions are optimized for performance
Since, the functions are "standard library" functions, a dedicated group of
developers constantly make them better. In the process, they are able to create the
most efficient code optimized for maximum performance.
3. It saves considerable development time
Since the general functions like printing to a screen, calculating the square root,
and many more are already written. You shouldn't worry about creating them once
again.
4. The functions are portable
With ever-changing real-world needs, your application is expected to work every
time, everywhere. And, these library functions help you in that they do the same
thing on every computer.
Library Functions in Different Header Files
C Header Files
44
BCA 1st Sem ( Programming In C)
C Header Files
45
BCA 1st Sem ( Programming In C)
UNIT-II
46
BCA 1st Sem ( Programming In C)
I. getchar()
II. putchar()
III. getch()
IV. putch()
V. gets()
VI. puts()
VII. prinf()
VIII. scanf()
#include<stdio.h>
void main()
char c;
printf(“enter a character”);
c=getchar();
printf(“c = %c ”,c);
}
II.putchar() : This function prints one character on the screen at a time which is
read by standard input.
47
BCA 1st Sem ( Programming In C)
putchar (c);
#include<stdio.h>
void main()
char ch;
scanf(“%c”, ch);
putchar(ch);
enter a character: r
III. getch() & getche():These functions read any alphanumeric character from the
standard input device The character entered is not displayed by the getch()
function until enter is pressed .The getche() accepts and displays the character.
#include
void main()
getche();
getch();
48
BCA 1st Sem ( Programming In C)
Example:
#include<stdio.h>
void main()
char ch;
ch = getch();
putch(ch);
You pressed : e
V. gets():This function is used for accepting any string until enter key is pressed
(string will be covered later).
#include <stdio.h>
#include <string.h>
void main()
char ch[30];
49
BCA 1st Sem ( Programming In C)
gets(ch);
VI.puts() :This function prints the string or character array. It is opposite to gets().
#include <stdio.h>
#include <string.h>
void main()
char string[40];
puts(string);
VII.printf():
int a=10;
50
BCA 1st Sem ( Programming In C)
double d=13.4;
printf("%f%d",d,a);
Then, user enters a string and this value is assigned to the variable “str” and
then displayed.
int a;
float b;
scanf("%d%f",&a,&b);
#include <stdio.h>
int main()
{
char ch;
char str[100];
printf("Enter any character \n");
scanf("%c", &ch);
printf("Entered character is %c \n", ch);
printf("Enter any string ( upto 100 character ) \n");
scanf("%s", &str);
printf("Entered string is %s \n", str);
}
51
BCA 1st Sem ( Programming In C)
Control Statements:
Control statements enable us to specify the flow of program control; ie, the order in
which the instructions in a program must be executed. They make it possible to
make decisions, to perform tasks repeatedly or to jump from one section of code to
another.
I. Decision Making
II. Case
III. Looping
There are 3 types of decision making control statements in C language. They are,
if statements
if else statements
else if ladder
52
BCA 1st Sem ( Programming In C)
Syntax
If(Condition)
{
Block1;
}
Example:
Program check number is Positive
#include<stdio.h>
void main()
{
int a;
a=1;
53
BCA 1st Sem ( Programming In C)
if(a>0)
{
printf(“number is positive”);
}
}
Output
number is positive
if else statements :In the “if” statement seen earlier, we can take some
action if expression is true. But if expression is false there is no action. We
can include an action for both conditions (i.e. true or false) by using if-else
statement. If condition is true block1 is executed otherwise block2.
Syntax
If(Condition)
Block1;
54
BCA 1st Sem ( Programming In C)
else
Block2;
Example:
#include<stdio.h>
void main()
int a;
a=1;
if(a>0)
printf(“number is positive”);
else
Output
number is positive
55
BCA 1st Sem ( Programming In C)
else if ladder
The evolutions of if-else –if ladder or multiple alternative if statement is
carried out from top to bottom. Each conditional expression is tested and if
found true only then its corresponding statements is executed. In a situation
where none of the nested conditions is found true then the final else part is
executed.
Syntax
if (condition 1)
Block
else if (condition 2)
Block
else if (condition 3)
Block
#include<stdio.h>
int main()
int day;
scanf("%d", &day);
if(day==1)
printf("Today is Monday");
else if(day==2)
56
BCA 1st Sem ( Programming In C)
printf("Today is Tuesday");
else if(day==3)
printf("Today is Wednesday");
else if(day==4)
printf("Today is thursday");
else if(day==5)
printf("Today is Friday");
else if(day==6)
printf("Today is Saturday");
else if(day==7)
printf("Today is Sunday");
else
printf("wrong input");
jump: Java supports three jump statement: break, continue and goto. These three
statements transfer control to other part of the program.
#include <stdio.h>
57
BCA 1st Sem ( Programming In C)
int main () {
int a = 10;
/* do loop execution */
do {
if( a == 15) {
a = a + 1;
break;
a++;
} while( a < 20 );
return 0;
58
BCA 1st Sem ( Programming In C)
Output:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
For the for loop, continue statement causes the conditional test and
increment portions of the loop to execute. For
the while and do...while loops, continue statement causes the program
control to pass to the conditional tests.
#include <stdio.h>
int main () {
/* do loop execution */
do {
if( a == 15) {
/* skip the iteration */
a = a + 1;
continue;
}
a++;
} while( a < 20 );
return 0;
}
Output:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
60
BCA 1st Sem ( Programming In C)
Example
#include <stdio.h>
int main()
int number=1;
while(number<=10)
if(number==4)
goto end;
end:
return 0;
Output
First run:
Number is : 1 2 3
61
BCA 1st Sem ( Programming In C)
switch (expression)
Statement;
switch (expression)
statement 2;
break;
62
BCA 1st Sem ( Programming In C)
statement 2;
break;
default :
statement 1;
statement 2;
The expression should result in an integer value or character value. First the
expression following switch is solved.
#include<stdio.h>
void main ( )
int j = 2;
switch ( j )
case 1 :
break;
case 2:
break;
case 3:
default:
III. Looping: Sometimes we want some part of our code to be executed more
than once. We can either repeat the code in our program or use loops
instead. It is obvious that if for example we need to execute some part of
code for a hundred times it is not practical to repeat the code. Alternatively
we can use our repeating code inside a loop.
Types of Loops in C
while
do-while
for
while: The statements within the while loop would keep on getting executed till
the condition being tested remains true. When the condition becomes false, the
control passes to the first statement that follows the body of the while loop. It is
entry control loop.
Syntax
Initialization;
While(condition)
Block;
Increment/decrement;
64
BCA 1st Sem ( Programming In C)
Example:
#include <stdio.h>
int main ()
int a = 10;
while( a < 14 ) {
a++;
return 0;
output
value of a:10
value of a:11
value of a:12
value of a:13
65
BCA 1st Sem ( Programming In C)
do while:The while and for loops test the termination condition at the top. By
contrast, the third loop in C, the do-while, tests at the bottom after making each
pass through the loop body; the body is always executed at least once.
Syntax
Initialization;
do
Block;
Increment/decrement ;
}while (condition);
Example
#include <stdio.h>
int main () {
int a = 10;
do
a + +;
while( a < 14 );
return 0;
output
66
BCA 1st Sem ( Programming In C)
value of a:10
value of a:11
value of a:12
value of a:13
for loop: for loop is something similar to while loop but it is more
complex. for loop is constructed from a control statement that determines how
many times the loop will run and a command section. Command section is
either a single command or a block of commands.
Syntax
Block;
Example
#include <stdio.h>
int main ()
int a;
67
BCA 1st Sem ( Programming In C)
return 0;
output
value of a:10
value of a:11
value of a:12
value of a:13
BASIS FOR
WHILE DO-WHILE
COMPARISON
General Form while ( condition) { do{
statements; //body of loop .
} statements; // body of loop.
.
} while( Condition );
68
BCA 1st Sem ( Programming In C)
UNIT-III
69
BCA 1st Sem ( Programming In C)
Function
Syntax
70
BCA 1st Sem ( Programming In C)
Return Type − A function may return a value. The return_type is the data
type of the value the function returns. Some functions perform the desired
operations without returning a value. In this case, the return_type is the
keyword void.
Function Name − This is the actual name of the function. The function
name and the parameter list together constitute the function signature.
Parameters − A parameter is like a placeholder. When a function is
invoked, you pass a value to the parameter. This value is referred to as actual
parameter or argument. The parameter list refers to the type, order, and
number of the parameters of a function. Parameters are optional; that is, a
function may contain no parameters
Syntax
Returntype Functionname(parameterlist)
Statements;
Syntax
Functionname();
Types of Function in C
71
BCA 1st Sem ( Programming In C)
Syntax:
Void functionname (void);
Example:
#include<stdio.h>
void sum(void); //function declaration
72
BCA 1st Sem ( Programming In C)
void sum(void)
{
int a,b,c;
printf(“enter two number\n”); //function defination
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“sum is %d”,c);
}
void main()
{
sum(); //function call
}
Output
enter two number
10 20
sum is 30
Syntax:
returnvalue functionname (void);
Example:
#include<stdio.h>
int sum(void); //function declaration
int sum(void)
73
BCA 1st Sem ( Programming In C)
{
int a,b,c;
printf(“enter two number\n”); //function defination
scanf(“%d%d”,&a,&b);
c=a+b;
return(c);
}
void main()
{
int c;
c=sum(); //function call
printf(“sum is %d”,c);
}
Output
enter two number
10 20
sum is 30
3) Function with arguments and No return value:This Type of Function
have arguments that are the value which is enter from the main(), the
arguments have datatype and every argument separated by commas(,). These
have no any return value .
Syntax:
void functionname (parameter list);
Example:
#include<stdio.h>
void sum(int a,int b); //function declaration
void sum(int a,int b)
{
74
BCA 1st Sem ( Programming In C)
int a,b,c;
c=a+b; //function defination
printf(“sum is %d”,c);
}
void main()
{
int a,b;
printf(“enter two number\n”);
scanf(“%d%d”,&a,&b);
Syntax:
void functionname (parameter list);
Example:
#include<stdio.h>
int sum(int a,int b); //function declaration
int sum(int a,int b)
{
75
BCA 1st Sem ( Programming In C)
int a,b,c;
c=a+b; //function defination
return ( c );
}
void main()
{
Int a,b, c;
printf(“enter two number\n”);
scanf(“%d%d”,&a,&b);
{
int a,b,c;
c=a+b; //function definition
return ( c );
}
void main()
{
Int a,b, c;
printf(“enter two number\n”);
scanf(“%d%d”,&a,&b);
t = a;
a = b;
b = t;
printf(" Values In user define a: %d, b: %d\n", a,b);
}
int main() /* Main function */
{
int a1 = 10;
int b1 = 20;
Call by Reference
In call by reference, to pass a variable n as a reference parameter, the
programmer must pass a pointer to n instead of n itself. The formal parameter
will be a pointer to the value of interest. The calling function will need to
use & to compute the pointer of actual parameter. The called function will
need to dereference the pointer with *where appropriate to access the value of
interest. Here is an example of a correct swap swapByReference() function.
So, now you got the difference between call by value and call by reference!
#include <stdio.h>
void swapByValue(int *a, int *b); /* Prototype */
78
BCA 1st Sem ( Programming In C)
}
int main() /* Main function */
{
int a1 = 10;
int b1 = 20;
79
BCA 1st Sem ( Programming In C)
“Call By References.
In this method, the value of each In this method, the address of actual
to the dummy variables in the called With this method, using addresses we
function have no effect on the values would have an access to the actual
return 0; return 0;
} }
t = x; t = *x;
x = y; *x = *y;
y = t; *y = t;
Output: Output:
x=20 y=10 x=20 y=10
a=10 b=20 a=20 b=10
81
BCA 1st Sem ( Programming In C)
Thus actual values of a and b remain Thus actual values of a and b get
In call by values we cannot alter the In call by reference we can alter the
Syntax Syntax
Returntype Returntype
functioname(parameterlist) functioname(*parameterlist)
{ {
Body; Body;
} }
Recursion
What is Recursion?
The process in which a function calls itself directly or indirectly is called
82
BCA 1st Sem ( Programming In C)
return 0;
}
/**
* Recursively prints all natural number between the given range.
*/
void printNaturalNumbers(int lowerLimit, int upperLimit)
83
BCA 1st Sem ( Programming In C)
{
if(lowerLimit > upperLimit)
return;
84
BCA 1st Sem ( Programming In C)
85
BCA 1st Sem ( Programming In C)
Syntax
86
BCA 1st Sem ( Programming In C)
Datatype arrayname[size];
Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the
number of elements required by an array as follows −
double balance[10];
Initializing Arrays
You can initialize an array in C either one by one or using a single statement as
follows −
The number of values between braces { } cannot be larger than the number of
elements that we declare for the array between square brackets [ ].
#include<stdio.h>
87
BCA 1st Sem ( Programming In C)
void main()
{
int a[5];
int i;
printf(“enter the number atleast 5\n”);
for(i=0;i<5;i++)
{
scanf(“%d”,&a[i]);
}
printf(“elements you enter are\n”);
for(i=0;i<5;i++)
{
printf(“%d\n”,a[i]);
}}
Output
enter the number atleast 5
10 20 30 40 50
elements you enter are
10
20
30
40
50
Two dimensional array:
o Array having more than one subscript variable is called Multi-
dimensional array.
o Multi Dimensional Array is also called as Matrix.
Declaration of 2D Array
88
BCA 1st Sem ( Programming In C)
Syntax:
Datatype Arrayname[rowsize][columnsize];
Initialization of 2D Array
There are two ways to initialize a two Dimensional arrays during declaration.
int disp[2][4] = {
};
Example of 2D Array
#include<stdio.h>
89
BCA 1st Sem ( Programming In C)
int main()
/* 2D array declaration*/
int disp[2][3];
int i, j;
for(j=0;j<3;j++) {
scanf("%d", &disp[i][j]);
for(j=0;j<3;j++) {
if(j==2){
printf("\n");
90
BCA 1st Sem ( Programming In C)
return 0;
Output:
123
456
data_type array_name[size1][size2]....[sizeN];
Examples:
91
BCA 1st Sem ( Programming In C)
int two_d[10][20];
int three_d[10][20][30];
int x[2][3][4] =
};
// Array
#include<stdio.h>
int main()
int x[2][3][2] =
};
93
BCA 1st Sem ( Programming In C)
printf(“%d”, x[i][j][k]);
printf(“\n”);
return 0;
Example
#include <stdio.h>
94
BCA 1st Sem ( Programming In C)
int i;
sum += age[i];
return avg;
int main()
return 0;
95
BCA 1st Sem ( Programming In C)
Output
Advantages of Arrays
It is better and convenient way of storing the data of same datatype with
same size.
Iterating the arrays using their index is faster compared to any other methods
like linked list etc.
Disadvantages of Arrays
It allows us to enter only fixed number of elements into it. We cannot alter
the size of the array once array is declared. Hence if we need to insert more
number of records than declared then it is not possible. We should know
array size at the compile time itself.
96
BCA 1st Sem ( Programming In C)
Inserting and deleting the records from the array would be costly since we
add / delete the elements from the array, we need to manage memory space
too.
It does not verify the indexes while compiling the array. In case there is any
indexes pointed which is more than the dimension specified, then we will get
run time errors rather than identifying them at compile time.
Strings: String declaration, string functions and string manipulation Program
Structure Storage Class: Automatic, external and static variables.
int a[3];
char name[5]={‘R’,’A’,’H’,’U’,’L’};
#include<stdio.h>
int main()
97
BCA 1st Sem ( Programming In C)
char name[5]={‘R’,’A’,’H’,’U’,’L’};
// print string
printf("%c",str);
return 0;
Output:
RAHUL
#include<stdio.h>
int main()
char name[5]=”RAHUL”;
// print string
printf("%s",str);
return 0;
98
BCA 1st Sem ( Programming In C)
Output:
RAHUL
Here (“ “)Double quotes is used while initializing the string instead of(‘
‘)Single quotes.
1)strlen():The function takes a single argument, i.e, the string variable whose
length is to be found, and returns the length of the string passed.
Syntax:
99
BCA 1st Sem ( Programming In C)
Example:
#include <stdio.h>
#include <string.h>
int main()
char a[20];
gets(c);
return 0;
Output
Length of string a = 5
2)strcpy():The strcpy() function copies the string pointed by source (including the
null character) to the character array destination.This function returns character
array destination.
Syntax:
Example
#include <stdio.h>
#include <string.h>
int main()
char str2[10];
strcpy(str2, str1);
printf(“str2= %s”,str2);
return 0;
Output
101
BCA 1st Sem ( Programming In C)
str2=awesome
3)strcat():It takes two arguments, i.e, two strings or character arrays, and stores
the resultant concatenated string in the first string specified in the argument.
Syntax
Example:
#include <stdio.h>
#include <string.h>
int main()
strcat(str1,str2);
return 0;
Output:
The strcmp() compares two strings character by character. If the first character of
two strings are equal, next character of two strings are compared. This continues
until the corresponding characters of two strings are different or a null character '\0'
is reached.
#include <stdio.h>
#include <string.h>
int main()
int result;
return 0;
Output
strcmp(str1, str2) = 32
strcmp(str1, str3) = 0
The first unmatched character between string str1 and str2 is third character.
The ASCII value of 'c' is 99 and the ASCII value of 'C' is 67. Hence, when
strings str1 and str2 are compared, the return value is 32.
When strings str1 and str3 are compared, the result is 0 because both strings are
identical.
Syntax:
Example:
// c program to demonstrate
#include<stdio.h>
#include<string.h>
int main()
104
BCA 1st Sem ( Programming In C)
return 0;
Output:
HELLO
Syntax:
Example:
// c program to demonstrate
#include<stdio.h>
#include<string.h>
int main()
return 0;
Output:
hello
1)auto :This is the default storage class for all the variables declared inside a
function or a block. Hence, the keyword auto is rarely used while writing programs
in C language. Auto variables can be only accessed within the block/function they
have been declared and not outside them (which defines their scope).
Syntax
Example:
#include <stdio.h>
void main()
{
106
BCA 1st Sem ( Programming In C)
Output
2)extern :Extern storage class simply tells us that the variable is defined elsewhere
and not within the same block where it is used. Basically, the value is assigned to it
in a different block and this can be overwritten/changed in a different block as
well. Hence, the keyword extern is rarely used while writing programs in C
language.
Syntax
Example:
#include <stdio.h>
void main()
extern int a ;
a=34;
}
107
BCA 1st Sem ( Programming In C)
Output
3)static:This storage class is used to declare static variables which are popularly
used while writing programs in C language. Static variables have a property of
preserving their value even after they are out of their scope! Hence, static variables
preserve the value of their last use in their scope. So we can say that they are
initialized only once and exist till the termination of the program. Hence, the
keyword static is rarely used while writing programs in C language.
Syntax
Example:
#include <stdio.h>
void main()
printf("value of a %d”,a);
printf("value of b %d”,b);
Output
value of a10
value of b20
108
BCA 1st Sem ( Programming In C)
4)register: This storage class declares register variables which have the same
functionality as that of the auto variables. The only difference is that the compiler
tries to store these variables in the register of the microprocessor if a free register is
available.This makes the use of register variables to be much faster than that of the
variables stored in the memory during the runtime of the program. If a free register
is not available, these are then stored in the memory only.
Syntax:
#include <stdio.h>
void main()
printf("value of a %d”,a);
printf("value of b %d”,b);
Output
value of b20
109
BCA 1st Sem ( Programming In C)
UNIT -IV
Structures
110
BCA 1st Sem ( Programming In C)
A structure is a user defined data type in C. A structure creates a data type that can
be used to group items of possibly different types into a single type.
Declaration of Structure
Syntax
struct structurename
Datatype variablename1;
Datatype variablename2;
Datatype variablename n;
Following is an example.
struct address
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};
111
BCA 1st Sem ( Programming In C)
Initialization of Structure
Syntax
Syntax
Objectname.variablename=value;
Example
#include<stdio.h>
struct student
int rollno;
char name[20];
};
void main()
scanf(“%d%s”,&obj.rollno,&obj.name);
Output
23 rahul
rollno is 23
name is rahul
Syntax
Example
113
BCA 1st Sem ( Programming In C)
#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
int main(){
int i;
for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
return 0;
Output:
114
BCA 1st Sem ( Programming In C)
Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz
Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz
#include <stdio.h>
115
BCA 1st Sem ( Programming In C)
#include <string.h>
struct student
{
int id;
float percentage;
};
int main()
{
struct student record;
record.id=1;
record.percentage = 86.5;
func(record);
return 0;
}
Output
Id is: 1
Percentage is: 86.500000
Syntax:
116
BCA 1st Sem ( Programming In C)
Objectname->variablename=value;
Example
#include<stdio.h>
#include <string.h>
struct student
{
int id;
char name[30];
float percentage;
};
int main()
{
int i;
struct student record1 = {1, "Raju", 90.5};
struct student *ptr;
ptr = &record1;
return 0;
}
Output
Records of STUDENT1:
Id is: 1
Name is: Raju
Percentage is: 90.500000
Union
Like Structures, union is a user defined data type. In union, all members share the
same memory location.
117
BCA 1st Sem ( Programming In C)
A union is a special data type available in C that allows to store different data types
in the same memory location. You can define a union with many members, but
only one member can contain a value at any given time
How is the size of union decided by compiler?
Size of a union is taken according the size of largest member in union.The Union
keyword is used to declare the unions in C.
Syntax
union structurename
Datatype variablename1;
Datatype variablename2;
Datatype variablename n;
};
Example
#include<stdio.h>
union student
int rollno;
char name[20];
};
void main()
{
118
BCA 1st Sem ( Programming In C)
scanf(“%d%s”,&obj.rollno,&obj.name);
BASIS OF
STRUCTURE UNION
COMPARISON
Basic The separate memory location is All members of the
allotted to each member of the 'union' share the same
'structure'. memory location.
Store Value Stores distinct values for all the Stores same value for all
members. the members.
119
BCA 1st Sem ( Programming In C)
Pointers
Pointer variable must be declared before using it as we know in C Programming
Language, every variable must be declared before using. Generally if we declare an
integer type variable that hold a unique memory address from the computer
system, we do it in C like below:
Int Variable_name;
Similarly, we can declare a pointer variable but adding an asterisk ('*' sign) after
data type and before variable name. For that there are three type of pointer
declaration style in C. They are:
1. int* variable_name;
2. int * variable_name;
3. int *variable_name;
Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also
known as indirection pointer used to dereference a pointer.
1. int *a;//pointer to int
2. char *c;//pointer to char
Initializing a pointer
To initialize the pointer variable &(Address Operator )is used.
int* p = &n;
#include <stdio.h>
int main()
{
int *ptr, q;
q = 50;
/* address of q is assigned to ptr */
ptr = &q;
/* display q's value using ptr variable */
printf("%d", *ptr);
printf("%u", ptr);
return 0;
}
Output
50
4104
#include <stdio.h>
int main()
{
int q;
q = 50;
printf("%u",&q);
return 0;
}
Output
50
4104
121
BCA 1st Sem ( Programming In C)
Here variable arr will give the base address, which is a constant pointer pointing to
the first element of the array, arr[0]. Hence arr contains the address
of arr[0] i.e 1000. In short, arr has two purpose - it is the name of the array and it
acts as a pointer pointing towards the first element in the array.
arr is equal to &arr[0] by default
We can also declare a pointer of type int to point to the array arr.
int *p;
p = arr;
// or,
p = &arr[0];
Pointer to Array
As studied above, we can use a pointer to point to an array, and then we can use
that pointer to access the array elements. Let’s have an example,
#include <stdio.h>
int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i = 0; i < 5; i++)
{
printf("%d \t", *p);
printf("address is %u:\n", p);
122
BCA 1st Sem ( Programming In C)
p++;
}
return 0;
}
Output
1 address is :1000
2 address is :1001
3 address is :1002
4 address is :1003
5 address is :1004
Topic-3:
File Handling: File Operations, Processing a Data File.
Types of Files
When dealing with files, there are two types of files you should know about:
1. Text files
2. Binary files
1. Text files
Text files are the normal .txt files that you can easily create using Notepad or any
simple text editors.
When you open those files, you'll see all the contents within the file as plain text.
You can easily edit or delete the contents.
They take minimum effort to maintain, are easily readable, and provide least
security and takes bigger storage space.
2. Binary files
123
BCA 1st Sem ( Programming In C)
File Handling in C
In programming, we may require some specific input data to be generated several
numbers of times. Sometimes, it is not enough to only display the data on the
console. The data to be displayed may be very large, and only a limited amount of
data can be displayed on the console, and since the memory is volatile, it is
impossible to recover the programmatically generated data again and again.
However, if we need to do so, we may store it onto the local file system which is
volatile and can be accessed every time. Here, comes the need of file handling in
C.
File handling in C enables us to create, update, read, and delete the files stored on
the local file system through our C program. The following operations can be
performed on a file.
o Creation of the new file
o Opening an existing file
o Reading from the file
o Writing to the file
o Deleting the file
File Operations
Mode Description
124
BCA 1st Sem ( Programming In C)
There are many functions in the C library to open, read, write, search and close the
file. A list of file functions are given below:
125
BCA 1st Sem ( Programming In C)
Mode Description
{
FILE *fp; // file pointer
char ch;
fp = fopen("file_handle.c","r");
while ( 1 )
{
ch = fgetc ( fp ); //Each character of the file is read and stored in the character file.
if ( ch == EOF )
break;
printf("%c",ch);
}
fclose (fp );
}
2)Closing File: fclose()
The fclose() function is used to close a file. The file must be closed after
performing all the operations on it.
The syntax of fclose() function is given below:
1. int fclose( FILE *fp );
3)fprintf():The fprintf() function is used to write set of characters into file. It sends
formatted output to a stream.
Syntax:
1. int fprintf(FILE *stream, const char *format [, argument, ...])
Example:
#include <stdio.h>
main()
{
FILE *fp;
fp = fopen("file.txt", "w");//opening file
fprintf(fp, "Hello file by fprintf...\n");//writing data into file
fclose(fp);//closing file
}
4)fscanf():The fscanf() function is used to read set of characters from file. It reads
a word from the file and returns EOF at the end of file.
Syntax:
127
BCA 1st Sem ( Programming In C)
5)fgetc():fgetc() is used to obtain input from a file single character at a time. This
function returns the number of characters read by the function. It returns the
character present at position indicated by file pointer.
Syntax:
int fgetc(FILE *pointer)
pointer: pointer to a FILE object that identifies
the stream on which the operation is to be performed.
int main ()
{
// open the file
FILE *fp = fopen("test.txt","r");
do
{
// Taking input single character at a time
char c = fgetc(fp);
128
BCA 1st Sem ( Programming In C)
printf("%c", c);
} while(1);
fclose(fp);
return(0);
}
Output:
The entire content of file is printed character by
character till end of file. It reads newline character
as well.
Syntax:
Example:
#include <stdio.h>
129
BCA 1st Sem ( Programming In C)
int main () {
FILE *fp;
int ch;
fp = fopen("file.txt", "w+");
fputc(ch, fp);
fclose(fp);
return(0);
130