Notes C Programming
Notes C Programming
Study Materials
First Semester
MCA
Faculty In-charge
Dr. Jayasimha S R
Associate Professor
Department of MCA
JSSATE, Bengaluru
2024 Batch
@#@#@
JSS Mahavidyapeetha – Towards a better world
The Jagadguru Veerasimhaasana Peetha was established in the 11th Century A.D. at Sutturu by Adi
Jagadguru Sri Shivarathreeshwara Shivayogi Mahaswamiji. Sutturu is a village in Nanjangud taluk, Mysuru
District in Karnataka. It is about 28 km from Mysuru city, in the south east direction.
The Peetha with its high ideals has been making remarkable contribution in religious, social, educational and
economic spheres in the state and across the country. It is striving for social development by responding to
the community needs. It strongly believes that, unless the problems of the socially backward communities and
the poor are taken care, there will not be social development. With this objective, the math has initiated
several programmes, while at the same time living up to its principle of “work is worship” and is engaged in
raising public awareness on issues of social concern.
JSS Academy of Technical Education (JSSATE) was established in the year 1997 at Bengaluru and is under
the umbrella of JSS Mahavidyapeetha, Mysuru. JSSATE is the result of the vision of our President, His
Holiness Jagadguru Sri Shivarathri Deshikendra Mahaswamiji to proactively participate in establishing a
world class Institution for Technical Education. The Campus is located on a sprawling 21.17 acres land
surrounded by lush green plantation on the South-Western edge of Bengaluru City. The institution is
affiliated to Visvesvaraya Technological University (VTU), Belagavi, India.
VISION:
To be among the finest Institutions providing Engineering and Management Education empowered
with research, innovation and entrepreneurship
MISSION:
@#@#@
About the Department
JSS Academy of Technical Education, Bengaluru offers Master of Computer Applications program (MCA)
from the academic year 2022-23. The institute is approved by AICTE, affiliated to VTU, Belagavi and is
recognized by Govt. of Karnataka. The institute is equipped with state-of-the-art infrastructure and computing
facilities. The current intake of the MCA program is 60 and the duration is two years (Four Semesters). The
curriculum, designed by VTU, is aimed at broadcasting a wide spectrum of practice and knowledge in the
computing domain in the latest and emerging technologies. The Department of MCA inculcates innovative
teaching-learning methods, and Outcome Based Education (OBE) to enable students to become intellectual
but competent professionals to meet global challenges.
To cater to the industry requirements and standards, industry experts are involved in partial curriculum design
and course delivery in order to address all the graduate attributes. The section comprising the IT related
Several MoUs with Industries are established for Students Training, Seminars, Internships and Project work.
VISION:
To be an esteemed academic and research department by imparting Quality Education to build competent
professionals and entrepreneurs.
MISSION:
1. Adopt novel methodologies in the teaching-learning process for quality education through experiential
learning.
2. Promote research and development activities, leading to publications, patents and start-ups.
3. Inculcate ethical values and leadership qualities among the students for a better society.
1. Graduates shall possess professional skills to build sustainable and inclusive applications for changing IT
Technologies.
2. Graduates shall possess technical excellence in their workspace and professional growth.
3. Graduates shall possess entrepreneurial qualities through interpersonal skills and teamwork.
1. PO1 (Foundation Knowledge): Apply knowledge of mathematics, programming logic and coding
fundamentals for solution architecture and problem solving.
2. PO2 (Problem Analysis): Identify, review, formulate and analyse problems for primarily focussing on
customer requirements using critical thinking frameworks.
@#@#@
3. PO3 (Development of Solutions): Design, develop and investigate problems with as an innovative
approach for solutions incorporating ESG/SDG goals.
4. PO4 (Modern Tool Usage): Select, adapt and apply modern computational tools such as development of
algorithms with an understanding of the limitations including human biases.
5. PO5 (Individual and Teamwork): Function and communicate effectively as an individual or a team
leader in diverse and multidisciplinary groups. Use methodologies such as agile.
6. PO6 (Project Management and Finance): Use the principles of project management such as scheduling,
work breakdown structure and be conversant with the principles of Finance for profitable project
management.
7. PO7 (Ethics): Commit to professional ethics in managing software projects with financial aspects. Learn
to use new technologies for cyber security and insulate customers from malware
8. PO8 (Life-long learning): Change management skills and the ability to learn, keep up with contemporary
technologies and ways of working
The MCA program will enable the students, by the time they graduate to:
1. Design and develop sustainable applications using principles of mathematics, computing and business
foundations.
2. Inculcate technical skills to develop innovative products to solve real-time societal problems in an ethical
way.
Course outcome:
(Course Skill Set) At the end of the course the student will be able to:
CO1: Understand the basics concepts of computer fundamentals and C programming to formulate simple algorithms
and translate the algorithms to programs in C language.
CO2: Apply loop, decision making statement and functions to solve a given problem and also correct syntax and
logical errors.
CO3: Implement arrays, pointers, structures and union to formulate algorithms and programs and apply it for
searching and sorting problems.
CO4: Implement file handling in C programming for a given application
@#@#@
Semester- I
@#@#@
Sl. Experiments
NO
1 Simulation of a SimpleCalculator.
2
Implement Binary Search on Integers
3
Sort the given set of N numbers using Bubble sort.
4
Implement Matrix multiplication and validate the rules of multiplication.
5
An electricity board charges the following rates for the use of electricity: for the first 200 units 80 paise per uni t:
for the next 100 units 90 paise per unit: beyond 300 units Rs 1 per unit. All users are charged a minimum of Rs.
100 as meter charge. If the total amount is more than Rs 400, then an additional surcharge of 15% of total
amount is charged. Write a program to read the name of the user, number of units consumed and print out the
charges.
6
Write functions to implement string operations such as compare, concatenate, and find string length. Use the
parameter passing techniques.
7
mplement structures to read, write and compute average- marks of the students, list the students scoring above
and below the average marks for a class of N students.
8
Write a C program to copy a text file to another, read both the input file name and target file name.
REFERENCES:
@#@#@
UNIT 1
BASICS OF C PROGRAMMING
Introduction to programming paradigms – Applications of C Language - Structure of C program - C
programming: Data Types - Constants – Enumeration Constants - Keywords – Operators: Precedence and
Associativity - Expressions - Input/Output statements, Assignment statements – Decision making
statements - Switch statement - Looping statements – Preprocessor directives - Compilation process .
PROGRAMMING PARADIGMS:
In computing, a program is a specific set of ordered operation for a computer to perform.The process
of developing and implementing various sets of instruction to enable a computer to perform a certain task
is called PROGRAMMING.
PROGRAMMING PARADIGMS INCLUDE:
1. IMPERATIVE PROGRAMMING PARADIGMS:
Command show how the computation takes place, step by step. Each step affects the global
state of the computation.
2. STRUCTURED PROGRAMMING PARADIGMS:
It is a kind of imperative programming where the control flow is defined by nested loops,
conditionals, and subroutines, rather than via gotos. Variables generally local to blocks.
3. OBJECT ORIENTED PROGRAMMING(OOP) PARADIGMS:
It is a programming paradigms based on the concepts of objects, which may contain data, in the
form of fields, often known as attributes, and code, in the form of procedures, often known as
methods.
4. DECLARATIVE PROGRAMMING PARADIGMS:
The programmer states only what the results should look like , not how to obtain it. No loops,
no assignments, etc. Whatever engines that interprets this code is just supposed go gets the
desired information and can use whatever approach its wants.
5. FUNCTIONAL PROGRAMMING PARADIGMS:
In functional programming, control flow is expressed by combining functional calls, rather than
by assigning values to variables.
6. PROCEDURAL PROGRAMMING PARADIGMS:
This paradigms includes imperative programming with procedure calls.
7. EVENT DRIVEN PROGRAMMING PARADIGMS:
In which the flow of the program is determined by events such as user action(mouse clicks, key
presses), sensor output, or message from other program/threads. It is the dominant paradigms
used in GUI and other applications that are centred on performing certain action in response to
user input.
8. FLOW DRIVEN PROGRAMMING PARADIGMS:
Programming processes communicating with each other over predefined channels.
9. LOGIC PROGRAMMING PARADIGMS:
Here programming is done by specifying a set of facts and rules. An engine infers the answer
to question.
10. CONSTRAINTS PROGRAMMING PARADIGMS:
An engine finds the value that meet the constraints.
One of the characteristics of a language is its support for particular programming
paradigms. For example: small talks has direct support for programming in the object oriented
way, so it might called an object oriented language.
Very few language implement a paradigms 100%, when they do, they are “PURE”. It is
incredibly rare to have a “pure OOP language” or a “pure functional language”.
A lot of language will facilitate programming in one or more paradigms. If a language is
purposely designed to allow programming in many paradigms is called a “multi paradigms
language”.
APPLICATION OF C:
1. OPERATING SYSTEM
2. EMBEDDED SYSTEM
3. GUI(GRAPHICAL USER INTERFACE)
4. NEW PROGRAMMING PLATFORMS
5. GOOGLE
6. MOZILLA FIREBOX AND THUNDERBIRD
7. MYSQL
8. COMPILER DESIGN
9. ASSEMBLERS
10. TEXT EDITORS
11. DRIVERS
12. NETWORK DEVICES
13. GAMING AND ANIMATION
FEATURES OF C PROGRAMMING/ADVANTAGES:
• C is a robust language with rich set of built in function.
• Programs written in c are efficient and fast.
• C is highly portable, programs once written in c can be run on another machine with minor or no
modification.
• C is basically a collection of c library functions, we can also create our own function and add it to
the c library.
• C is easily extensible.
DISADVANTAGE OF C:
• C doesnot provide OOP.
• There is no concepts of namespace in c.
• C doesnot provides binding or wrapping up of a single unit.
• C doesnot provide constructor and destructor.
STRUCTURE OF C:
Documentation section:
The documentation section consists of a set of comment lines giving the name of
the program, the author and other details, which the programmer would like to use later.
Link section: The link section provides instructions to the compiler to link functions
from the system library such as using the #include directive.
Definition section: The definition section defines all symbolic constants such using the
#define directive.
Global declaration section: There are some variables that are used in more than one function.
Such variables are called global variables and are declared in the global declaration section that
is outside of all the functions. This section also declares all the user-defined functions.
Main () function section: Every C program must have one main function section. This section
contains two parts; declaration part and executable part.
Declaration part:
The declaration part declares all the variables used in the executable part.
Executable part:
There is at least one statement in the executable part. These two parts must appear between
the opening and closing braces. The program execution begins at the opening brace and ends at
the closing brace. The closing brace of the main function is the logical end of the program. All
statements in the declaration and executable part end with a semicolon.
Subprogram section:
If the program is a multi-function program then the subprogram section contains all the
user-defined functions that are called in the main () function. User-defined functions are
generally placed immediately after the main () function, although they may appear in any order.
All section, except the main () function section may be absent when they are not required.
C PROGRAMMING: DATA-TYPES
A data-type in C programming is a set of values and is determined to act on those
values. C provides various types of data-types which allow the programmer to select the
appropriate typefor the variable to set its value.
The data-type in a programming language is the collection of data with values having
fixed meaning as well as characteristics. Some of them are integer, floating point, character etc.
Usually, programming languages specify the range values for given data-type.
C Data Types are used to:
Pointers These are powerful C features which are used to access the
memory and deal with their addresses.
C allows the feature called type definition which allows programmers to define their own
identifier that would represent an existing data type. There are three such types:
Structure It is a package of variables of different types under a single name. This is done
to handle data efficiently. “struct” keyword is used to define a structure.
Union These allow storing various data types in the same memory location. Programmers
can define a union with different members but only a single member can contain
a value at given time.
Enum Enumeration is a special data type that consists of integral constants and each of them
is assigned with a specific name. “enum” keyword is used to define the enumerated data
type.
int a = 4000; // positive integer data type float b = 5.2324; // float data type
char c = 'Z'; // char data type
long d = 41657; // long positive integer data type long e = -21556; // long -ve integer data type
int f = -185; // -ve integer data type
short g = 130; // short +ve integer data type short h = -130; // short -ve integer data type
double i = 4.1234567890; // double float data type float j = -3.55; // float data type
}
Let's see the basic data types. Its size is given according to 32 bit architecture.
Data Types Memory Size Range
float 4 byte
double 8 byte
long double 10 byte
The storage representation and machine instructions differ from machine to Machine.
sizeof operator can use to get the exact size of a type or a variable on a particular platform.
Example: #include <stdio.h>
#include <limits.h>
int main() {
printf("Storage size for int is: %d \n", sizeof(int));
printf("Storage size for char is: %d \n", sizeof(char)); return 0
}
CONSTANTS
A constant is a value or variable that can't be changed in the program, for example: 10,
20, 'a', 3.4, "c programming" etc. There are different types of constants in C programming.
List of Constants in C
Constant Example
1. const keyword
2. #define preprocessor
C const keyword:
The const keyword is used to define constant in C programming.
Example:
const float PI=3.14;
Now, the value of PI variable can't be changed.
#include<stdio.h>
int main()
{
const float PI=3.14;
printf("The value of PI is: %f",PI);
return 0;
}
Output:
The value of PI is: 3.140000
If you try to change the value of PI, it will render compile time error.
#include<stdio.h>
int main(){
const float PI=3.14; PI=4.5;
printf("The value of PI is: %f",PI);
return 0;
}
Output:
Compile Time Error: Cannot modify a const object.
C #define preprocessor
The #define preprocessor directive is used to define constant or micro substitution. It can use any
basic data type.
Syntax: #define token value
Let's see an example of #define to define a constant.
#include <stdio.h>
#define PI 3.14
main()
{
printf("%f",PI);
}
Output:
3.140000
Backslash character constant:
C supports some character constants having a backslash in front of it. The lists of backslash
characters have a specific meaning which is known to the compiler. They are also termed as “Escape
Sequence”.
Example:
\t is used to give a tab
\n is used to give new line
Constants Meaning Constants Meaning
\a beep sound \n newline
\v vertical tab \\ backslash
\b backspace \r carriage return
\’ single quote \0 null
\f form feed \t horizontal tab
\” double quote
ENUMERATION CONSTANTS:
An enum is a keyword, it is an user defined data type. All properties of integer are
applied on Enumeration data type so size of the enumerator data type is 2 byte . It work like
the Integer. It is used for creating an user defined data type of integer. Using enum we can
create sequence of integer constant value.
• In above syntax tagname is our own variable. tagname is any variable name.
It is start with 0 (zero) by default and value is incremented by 1 for the sequential
identifiers in the list. If constant one value is not initialized then by default sequence will be start
from zero and next to generated value should be previous constant value one.
Example:
• In above code first line is create user defined data type called week.
Example:
#include<stdio.h>
#include<conio.h>
enum abc{x,y,z};
void main()
{
int a;
clrscr();
a=x+y+z; //0+1+2
printf(“sum: %d”,a);
getch();
}
Output:
Sum: 3
KEYWORDS:
A keyword is a reserved word. You cannot use it as a variable name, constant name etc. There are
only 32 reserved words (keywords) in C language.
A list of 32 keywords in c language is given below:
OPERATORS :
Operator is a special symbol that tells the compiler to perform specific mathematical or logical Operation.
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Ternary or Conditional Operators
Arithmetic Operators:
Given table shows all the Arithmetic operator supported by C Language. Lets suppose variable A
hold 8 and B hold 3.
Operator Example (int A=8, B=3) Result
+ A+B 11
- A-B 5
* A*B 24
/ A/B 2
% A%4 0
Relational Operators:
Which can be used to check the Condition, it always return true or false. Lets suppose variable
hold 8 and B hold 3.
Logical Operator:
Which can be used to combine more than one Condition?. Suppose you want to combined two
conditions A<B and B>C, then you need to use Logical Operator like (A<B) && (B>C). Here && is
Logical Operator.
Assignment operators:
Which can be used to assign a value to a variable. Lets suppose variable A hold 8 and B hold 3.
Ternary Operator:
If any operator is used on three operands or variable is known as Ternary Operator. It can be
represented with ? : . It is also called as conditional operator
Advantage of Ternary Operator
Using ?: reduce the number of line codes and improve the performance of application.
Syntax:
In the above symbol expression-1 is condition and expression-2 and expression-3 will be either
value Or variable or statement or any mathematical expression. If condition will be true expression-2 will
be execute otherwise expression-3 will be executed.
Conditional Operator flow diagram
Example:
Special Operators:
C supports some special operators
Operator Description
* Pointer to a variable.
Expression evaluation
In C language expression evaluation is mainly depends on priority and associativity.
Priority
This represents the evaluation of expression starts from "what" operator.
Associativity
It represents which operator should be evaluated first if an expression is containing more than one
operator with same priority.
Precedence of operators :
The precedence rule is used to determine the order of application of operators in evaluating sub
expressions. Each operator in C has a precedence associated with it. The operator with the highest
precedence is operated first.
Associativity of operators :
The associativity rule is applied when two or more operators are having same precedence in the sub
expression. An operator can be left-to-right associative or right-to-left associative.
Rules for evaluation of expression:
•First parenthesized sub expressions are evaluated first.
•If parentheses are nested, the evaluation begins with the innermost sub expression.
•The precedence rule is applied to determine the order of application of operators in evaluating
sub expressions.
•The associability rule is applied when two or more operators are having same precedence in the sub
expression.
EXPRESSION:
For e.g, a=2+3 is an expression with three operands a,2,3 and 2 operators = & +
An expression that has only one operator is known as a simple expression. E.g: a+2
An expression that involves more than one operator is called a compound expression.
E.g: b=2+3*5.
IO STATEMENT:
• Formatted Functions
• Unformatted functions
FORMATTED INPUT FUNCTION:
SCANF():
It is used to get data in a specified format. It can accept different data types.
Syntax:
scanf(“Control String”, var1address, var2address, …);
EXAMPLE:
#include<stdio.h>
#include<conio.h>
Void main()
{
int a,b,sum;
clrscr();
scanf(“%d %d”,&a,&b);
sum= a+b;
}
sum= a+b;
printf(“sum is:%d”,sum);
}
Example:
#include<stdio.h>
OUTPUT:
#include<conio.h> j
void main()
{
Char ch;
ch=getchar();
Printf(“%c”,ch);
}
getch():
getch() accepts only a single character from keyboard. The character entered through getch() is not
displayed in the screen (monitor).
Syntax:
variable_name = getch();
Example:
#include<stdio.h>
#include<conio.h>
void main()
OUTPUT:
{ Ch=a
Char ch;
ch=getch();
Printf(“ch=%c”,ch);
}
getche():
getche() also accepts only single character, but getche() displays the entered character in the
screen.
Syntax:
variable_name = getche();
Example:
#include<stdio.h>
#include<conio.h>
void main()
OUTPUT:
{ a
Ch=a
Char ch;
ch=getche();
Printf(“ch=%c”,ch);
}
gets():
This function is used for accepting any string through stdin (keyboard) until enter key
is pressed.
Syntax:
gets(variable_name);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
Char ch[10]; OUTPUT:
cprogram
gets(ch); Ch=cprogram
Printf(“ch=%s”,ch);
getch();
}
UNFORMATTED OUTPUT FUNCTION:
• putchar()
• putch()
• puts()
putchar():
This function prints one character on the screen at a time.
Syntax :
putchar(variable name);
Example:
#include<stdio.h>
OUTPUT:
#include<conio.h> enter a character: j
j
void main()
{
Char ch;
printf(“enter a character:”);
ch=getchar();
putchar(ch);
getch();
}
putch():
putch displays any alphanumeric characters to the standard output device. It displays only one
character at a time.
Syntax:
putch(variable_name);
Example:
include<stdio.h>
#include<conio.h>
void main()
{ OUTPUT:
Press any character:
char ch; Pressed character is: e
clrscr();
printf(“Press any character: ”);
ch = getch();
printf(“\nPressed character is:”);
putch(ch);
getch();
}
puts():
This function prints the string or character array.
Syntax:
puts(variable_name);
Example:
include<stdio.h>
#include<conio.h>
void main()
{ OUTPUT:
Enter a string: cprogramming
char ch[20]; cprogramming
clrscr();
puts(“enter a string”);
gets(ch);
puts(ch);
}
ASSIGNMENT STATEMENT:
The assignment statement has the following form:
Syntax:
variable = expression/constant/variable;
Its purpose is saving the result of the expression to the right of the assignment operator to the
variable on the left. Here are some rules:
• If the type of the expression is identical to that of the variable, the result is saved in the variable.
• Otherwise, the result is converted to the type of the variable and saved there.
❖ If the type of the variable is integer while the type of the result is real, the fractional
part, including the decimal point, is removed making it an integer result.
❖ If the type of the variable is real while the type of the result is integer, then a decimal
point is appended to the integer making it a real number.
• Once the variable receives a new value, the original one disappears and is no more available.
Examples of assignment statements,
b = c ; /* b is assigned the value of c */
a = 9 ; /* a is assigned the value 9*/
b = c+5; /* b is assigned the value of expr c+5 */
• The expression on the right hand side of the assignment statement can be: An arithmetic
expression;
❖ A relational expression;
❖ A logical expression;
❖ A mixed expression.
For example,
int a;
float b,c ,avg, t;
avg = (b+c) / 2; /*arithmetic expression */
a = b && c; /*logical expression*/
a = (b+c) && (b<c); /* mixed expression*/
DECISION MAKING STATEMENTS:
Decision making statement is depending on the condition block need to be executed or not which
is decided by condition.
If the condition is "true" statement block will be executed, if condition is "false" then statement
block will not be executed.
In this section we are discuss about if-then (if), if-then-else (if else), and switch statement. In C
language there are three types of decision making statement.
• if
• if-else
• switch
if Statement:
if-then is most basic statement of Decision making statement. It tells to program to execute a
certain part of code only if particular condition is true.
Syntax:
if(condition)
{
Statements executed if the condition is true
}
FLOWCHART:
Constructing the body of "if" statement is always optional, Create the body when we are having multiple
statements.
For a single statement, it is not required to specify the body.
If the body is not specified, then automatically condition part will be terminated with next semicolon ( ; ).
Example:
#include<stdio.h>
int main()
{
int num=0;
printf(“enter a number:”); OUTPUT:
scanf(“%d”,&num); Enter a number: 4
4 is even number
if(num%2==0)
{
printf(“%d is even number”,num);
}
return 0;
}
if-else statement:
In general it can be used to execute one block of statement among two blocks, in C language if
and else are the keyword in C.
Syntax:
if(expression)
{
else
Flowchar
t:
In the above syntax whenever condition is true all the if block statement are executed remaining
statement of the program by neglecting else block statement. If the condition is false else block statement
remaining statement of the program are executed by neglecting if block statements.
Example:
#include<stdio.h>
void main()
{
int age;
printf(“enter age:”)
scanf(“%d”,&age);
Output:
if(age>=18) Enter age: 18
Eligible to vote
{ Enter age: 17
Not eligible to vote
printf(“age:%d”,age);
printf(“eligible to vote” );
}
else
{
printf(“age:%d”,age);
printf(“not eligible to vote” );
}
Nested if:
When an if else statement is present inside the body of another “if” or “else” then this is called
nested if else.
Syntax of Nested if else statement:
if(condition) {
//Nested if else inside the body of "if"
if(condition2) {
//Statements inside the body of nested "if"
}
else {
//Statements inside the body of nested "else"
}
}
else {
//Statements inside the body of "else"
}
Flowchart:
EXAMPLE:
#include<stdio.h>
void main() Output:
Enter age and salary: 55 55000
{ 65000
int age, salary;
printf(“enter age and salary”);
scanf(%d %d”, &age,&salary);
if(age>50)
{
if(salary<60000)
{
salary=salary+10000
;printf(“%d”,salary);
}
else
{
salary=
salary+5000;
printf(“%d”,salary);
}
}
else
{
salary=salary+1000;
printf(“%d”,salary);
}
printf(“end of program”);
getch();
}
Switch:
A switch statement work with byte, short, char and int primitive data type, it also works with
enumerated types and string.
Syntax:
switch(expression/variable)
{
case value1:
statements;
break;//optional
case value2:
statements;
break;//optional
default:
statements;
break;//optional
}
Rules for apply switch:
1. With switch statement use only byte, short, int, char data type.
2. You can use any number of case statements within a switch.
3. Value for a case must be same as the variable in switch
Flowchart:
Example:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
void main()
{
// declaration of local variable op;
int op, n1, n2;
printf (" enter 2 number: ");
scanf(%d %d”,&n1,&n2);
printf (" \n 1 Addition \t \t 2 Subtraction \n 3 Multiplication \t 4 Division \n 5 Exit \n \n Please,
Make a choice ");
scanf ("%d", &op); // accepts a numeric input to choose the operation
switch (op)
{
case 1:
printf ("sum is :%d ",n1+n2);
break;
case 2:
printf ("difference is :%d ",n1-n2);
break;
case 3:
printf ("multiplication :%d ",n1*n2);
break;
case 4:
printf ("division :%d ",n1/n2);
break;
case 5:
printf ("exit”);
break;
default:
printf(“enter the number between 1 to 5:”);
}
}
LOOPING STATEMENTS
Sometimes it is necessary for the program to execute the statement several times, and C loops
execute a block of commands a specified number of times until a condition is met.
What is Loop?
A computer is the most suitable machine to perform repetitive tasks and can tirelessly do a task
tens of thousands of times. Every programming language has the feature to instruct to do such repetitive
tasks with the help of certain form of statements. The process of repeatedly executing a collection of
statement is called looping . The statements get executed many numbers of times based on the condition.
But if the condition is given in such a logic that the repetition continues any number of times with no
fixed condition to stop looping those statements, then this type of looping is called infinite looping.
C supports following types of loops:
• while loops
• do while loops
• for loops
while loops:
C while loops statement allows to repeatedly run the same block of code until a condition is met.
while loop is a most basic loop in C programming. while loop has one control condition, and executes as
long the condition is true.
The condition of the loop is tested before the body of the loop is executed, hence it is called an
entry-controlled loop.
Syntax:
while (condition)
{
statement(s); Increment statement;
}
Flowchart:
Flowchart:
Output:
1 2 3 4 5 6 7 8 9 10
Do..while loops:
C do while loops are very similar to the while loops, but it always executes the code block at least
once and furthermore as long as the condition remains true. This is an exit- controlled loop.
Syntax:
do{
statement(s);
}while( condition );
Flowchart:
EXAMPLE:
#include<stdio.h>
void main ()
{ Output:
int i=1; 1 2 3 4 5 6 7 8 9 10
clrscr();
do
{
printf(“%d”,i);
i++;
} while(i<=10);
getch();
}
For loop:
C for loops is very similar to a while loops in that it continues to process a block of code until a
statement becomes false, and everything is defined in a single line. The for loop is also entry-controlled
loop.
Syntax:
for ( init; condition; increment )
{
statement(s);
}
Flowchart:
Example:
#include<stdio.h>
void main ()
{ Output:
int i; 1 2 3 4 5 6 7 8 9 10
clrscr();
for(i=1;i<=10;i++)
{
printf(“%d”,i);
getch();
}
PRE-PROCESSOR DIRECTIVES
The C preprocessor is a micro processor that is used by compiler to transform your code before
compilation. It is called micro preprocessor because it allows us to add macros. Preprocessor directives are
executed before compilation.
• We first create a C program using an editor and save the file as filename.c
$ vi filename.c
The diagram on right shows a simple program to add two numbers.
compile it using below command.
$ gcc –Wall filename.c –o filename
The option -Wall enables all compiler’s warning messages. This option is recommended to generate
bettercode. The option -o is used to specify output file name. If we do not use this option, then an output
file with name a.out is generated.
After compilation executable is generated and we run the generated executable using below
command.
$ ./filename
What goes inside the compilation process?
Compiler converts a C program into an executable. There are four phases for a C program to
become an executable:
1. Pre-processing
2. Compilation
3. Assembly
4. Linking
By executing below command, We get the all intermediate files in the current directory along with the
executable.
$gcc –Wall –save-temps filename.c –o filename
The following screenshot shows all generated intermediate files.
Let us one by one see what these intermediate files contain
Pre-processing:
This is the first phase through which source code is passed. This phase include:
• Removal of Comments
• Expansion of Macros
• Expansion of the included files.
The preprocessed output is stored in the filename.i. Let’s see what’s inside
filename.i:using $vi filename.i
In the above output, source file is filled with lots and lots of info, but at the end our code is
preserved.
Analysis:
• printf contains now a + b rather than add(a, b) that’s because macros have expanded.
• Comments are stripped off.
• #include<stdio.h> is missing instead we see lots of code. So header files has been
expanded andincluded in our source file.
Compiling:
The next step is to compile filename.i and produce an; intermediate compiled output file
filename.s.
This file is in assembly level instructions. Let’s see through this file using $vi filename.s
Assembly:
In this phase the filename.s is taken as input and turned into filename.o by assembler.
This file contain machine level instructions. At this phase, only existing code is converted into
machine language, the function calls like printf() are not resolved. Let’s view this file using $vi
filename.o
Linking:
This is the final phase in which all the linking of function calls with their definitions are
done. Linkerknows where all these functions are implemented.
Linker does some extra work also, it adds some extra code to our program which is
required whenthe program starts and ends.
For example, there is a code which is required for setting up the environment like passing
commandline arguments. This task can be easily verified by using $size filename.o and $size
filename.
Through these commands, we know that how output file increases from an object file to
an executable file. This is because of the extra code that linker adds with our program.
UNIT II
ARRAYS AND STRINGS
Introduction to Arrays: Declaration, Initialization – One dimensional array –
Two dimensional arrays - String operations: length, compare, concatenate, copy –
Selection sort, linear and binary search.
DIMENSIONAL ARRAYS:
Array in C language is a collection or group of elements (data). All the elements of c
array are homogeneous (similar). It has contiguous memory location.
C array is beneficial if you have to store similar elements. Suppose you have to store
marks of 50 students, one way to do this is allotting 50 variables.
So it will be typical and hard to manage.
For example we cannot access the value of these variables with only 1 or 2 lines of
code.
Another way to do this is array. By using array, we can access the elements easily. Only
few lines of code is required to access the elements of array.
Advantage of C Array:
1) Code Optimization: Less code to the access the data.
2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array
easily.
3) Easy to sort data: To sort the elements of array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array:
1) Fixed Size: Whatever size, we define at the time of declaration of array, we can't
exceed the limit. So, it doesn't grow the size dynamically like Linked List.
Declaration of C Array:
We can declare an array in the c language in the following way.
Syntax:
data_type array_name[array_size];
Initialization of C Array:
A simple way to initialize array is by index. Notice that array index starts from 0 and
ends with [SIZE - 1].
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
Example:
#include<stdio.h>
int main()
{ Output:
int i=0; 80
int marks[5];//declaration of array 60
marks[0]=80;//initialization of array 70
marks[1]=60; 85
marks[2]=70; 75
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++)
{
printf("%d \n",marks[i]);
}//end of for loop return 0;
}
C Array: Declaration with Initialization:
We can initialize the c array at the time of declaration. Let's see the code. int
marks[5]={20,30,40,50,60};
In such case, there is no requirement to define size. So it can also be written as the
following code
.
Example: int marks[]={20,30,40,50,60};
Programs:
#include<stdio.h> Output:
int main() 20
{ 30
int i=0; 40
int marks[5]={20,30,40,50,60};//declaration and initialization of array 50
//traversal of array 60
for(i=0;i<5;i++)
{
printf("%d \n",marks[i]);
}
return 0;
}
TWO DIMENSIONAL ARRAYS (2 D arrays):
The two dimensional array in C language is represented in the form of rows and
columns, also known as matrix. It is also known as array of arrays or list of arrays.
The two dimensional, three dimensional or other dimensional arrays are also known
as multidimensional arrays.
Declaration of two dimensional Array in C:
We can declare an array in the c language in the following way.
Syntax:
data_type array_name[size1][size2];
#include<stdio.h> Output:
int main() arr[0][0] = 1
{ arr[0][1] = 2
int i=0,j=0; arr[0][2] = 3
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}}; arr[1][0] = 2
//traversing 2D array arr[1][1] = 3
for(i=0;i<4;i++) arr[1][2] = 4
{ arr[2][0] = 3
for(j=0;j<3;j++) arr[2][1] = 4
{ arr[2][2] = 5
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]); arr[3][0] = 4
}//end of j arr[3][1] = 5
}//end of i return 0; arr[3][2] = 6
}
STRING OPERATION:
What is meant by String?
String in C language is an array of characters that is terminated by \0 (null character).
There are two ways to declare string in c language.
1. By char array
2. By string literal
char ch[]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
You can also define string by string literal in C language.
For example: char ch[]="javatpoint";
In such case, '\0' will be appended at the end of string by the compiler.
The strrev(string) function returns reverse of the given string. Let's see a simple example
of strrev() function.
Programs:
#include<stdio.h>
#include <string.h>int
main() Output:
{ Enter string: javatpoint
char str[20]; String is: javatpoint
printf("Enter string: "); Reverse String is: tnioptavaj
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nReverse String is: %s",strrev(str));
return 0;
}
Introduction to functions: Function prototype, function definition, function call, Built-in functions
(string functions, math functions) – Recursion – Example Program: Computation of Sine series,
Scientific calculator using built-in functions, Binary Search using recursive functions – Pointers – Pointer
operators – Pointer arithmetic – Arrays and pointers – Array of pointers – Example Program: Sorting
of names – Parameter passing: Pass by value, Pass by reference – Example Program: Swapping of two
numbers and changing the value of a variable using pass by reference.
FUNCTIONS
Definition
C enables its programmers to break up a program into segments commonly known as functions
Every function in the program is supposed to perform a well-defined task. Therefore, the programcode of
one function is completely insulated from the other functions.
main() calls a function named func1(). Therefore, main() is known as the calling function
andfunc1() is known as the called function.
Need For Functions:
Functions are used because of following reasons –
a) To improve the readability of code.
b) Improves the reusability of the code, same function can be used in any program rather than
writing the same code from scratch.
c) Debugging of the code would be easier if you use functions, as errors are easy to be traced.
d) Reduces the size of the code, duplicate set of statements are replaced by function calls.
Terminologies In Functions
• A function f that uses another function g is known as the calling function, and g is known as the
called function.
• The inputs that a function takes are known as arguments.
• When a called function returns some result back to the calling function, it is said to
returnthat result.
• The calling function may or may not pass parameters to the called function. If the
called function accepts arguments, the calling function will pass parameters, else not.
➢ Function declaration is a declaration statement that identifies a function’s name, a
list ofarguments that it accepts, and the type of data it returns.
➢ Function definition consists of a function header that identifies the function, followed
by the bodyof the function containing the executable code for that function.
Function Declaration
The general format for declaring a function that accepts arguments and returns a value as result
can be given as:
o function_name - is a valid name for the function. Naming a function follows the
same rules that are followed while naming variables. A function should have a
meaningful name that must specify the task that the function will perform.
o return_data_type - the data type of the value that will be returned to the calling
function asa result of the processing performed by the called function.
o (data_type variable1, data_type variable2, ...) - is a list of variables of specified
data types. These variables are passed from the calling function to the called
function. They are also known as arguments or parameters that the called
function accepts to perform its task.
Function Definition
When a function is defined, space is allocated for that function in the memory. A functiondefinition
comprises of two parts:
• Function header
• Function body
The syntax of a function definition can be given as:
return_data_type function_name(data_type variable1, data_type variable2,..)
{
.............
statements
.............
return(variable);
}
Function Call
The function call statement invokes the function. When a function is invoked, the compiler jumps to the
called function to execute the statements that are a part of that function. Once the called function is
executed, the program control passes back to the calling function. A function call statement has the
following syntax:
function_name(variable1, variable2, ...);
If the return type of the function is not void, then the value returned by the
called functionmay be assigned to some variable as given below.
variable_name = function_name(variable1, variable2, ...);
Eg:// program to find whether a number is even or odd using functions.
#include <stdio.h>
int evenodd(int); //FUNCTION DECLARATION
int main()
{
int num, flag;
printf("\n Enter the number : ");
scanf("%d",&num);
flag = evenodd(num); //FUNCTION CALL
if (flag == 1)
printf("\n %d is EVEN", num);
else
printf("\n %d is ODD", num);
return 0;
}
int evenodd(int a) // FUNCTION HEADER
{
if(a%2 == 0)
return 1;
else
return 0;
}
Output:
Enter the number : 7878 is EVEN
PASSING PARAMETERS TO FUNCTIONS
There are two ways in which arguments or parameters can be passed to the called function.
1. Call by value - The values of the variables are passed by the calling function to
the calledfunction.
2. Call by reference - The addresses of the variables are passed by the calling
function to thecalled function.
1. Call by Value
• In call by value method, the value of the actual parameters is copied into the formal
parameters.
• In call by value method, we cannot modify the value of the actual parameter by
the formalparameter.
• In call by value, different memory is allocated for actual and formal parameters.
• The actual parameter is the argument which is used in the function call whereas formal
parameter isthe argument which is used in the function definition.
Eg://Program for call by value
#include<stdio.h>
int main()
{
int x,y;
void swap(int,int); printf("Enter two
numbers:");scanf("%d%d",&x,&y);
printf("\n\nBefore Swapping: x = %d\ty =
%d",x,y);
swap(x,y);
printf("\n\nAfter Swapping: x = %d\ty = %d",x,y);
}
Output:
1. Its main drawback is that copying data consumes additional storage space. In addition, it can take
alot of time to copy, thereby resulting in performance penalty, especially if the function is called
many times.
Call By Reference:
• The method of passing arguments by address or reference is also known as call by address or call
by reference. Here, the addresses of the actual arguments are passed to the formal parameters of
the function.
• If the arguments are passed by reference, changes in the formal parameters also make changes on
actual parameters.
#include<stdio.h>
int main()
{
int x ,y;
void swap (int*,int*);
printf(“enter the two numbers”);
scanf(“%d%d”,&x,&y);
printf("\n\nBefore Swapping:\n\nx = %d\ty = %d",x,y);
swap(&x,&y);
printf("\n\nAfter Swapping:\n\nx = %d\ty = %d\n\n",x,y);
}
void swap(int *a, int *b)
{
*a=*a+*b;
*b=*a-*b;
*a=*a-*b;
printf("\n\nIn swap function: x = %d\ty = %d\n\n",a,b);
}
Output:
3.A function can return only one value. In case we need to return multiple values, we can pass those
arguments by reference, so that the modified values are visible in the calling function.
Disadvantage:
1. if inadvertent changes are caused to variables in called function then these changes would
bereflected in calling function as original values would have been overwritten.
RECURSIVE FUNCTION
Output:
Types of Recursion
1. Direct Recursion
A function is said to be directly recursive if it explicitly calls itself.
2. Indirect Recursion
A function is said to be indirectly recursive if it contains a call to another function which
ultimately calls it
3. Tail Recursion
A recursive function is said to be tail recursive if no operations are pending to be performed when
the recursive function returns to its caller.
4. Non Tail Recursion:
A recursive function is said to be non tail recursive if operations are pending to be performed when
the recursive function returns to its caller.
int Fact(int n)
{
if(n==1)
return 1;else
return (n * Fact(n–1));
}
Advantages
➢ Recursive solutions often tend to be shorter and simpler than non-recursive ones.
➢ Code is clearer and easier to use.
➢ Recursion works similar to the original formula to solve a problem.
➢ Recursion follows a divide and conquer technique to solve problems.
disadvantages
➢ Recursion is implemented using system stack. If the stack space on the system is limited,
recursion to a deeper level will be difficult to implement.
#include<stdio.h>
#define size 10
int binsearch(int[], int, int, int);
int main()
{
int num, i, key, position;
int low, high, list[size];
printf("\nEnter the total number of elements");
scanf("%d", &num);
printf("\nEnter the elements of list :");
for (i = 0; i < num; i++)
{
scanf("%d", &list[i]);
}
low = 0;
high = num - 1;
printf("\nEnter element to be searched : ");
scanf("%d", &key);
position = binsearch(list, key, low, high);
if (position != -1)
{
printf("\nNumber present at %d", (position + 1));
}
else
printf("\n The number is not present in the list");
return (0);
}
{
return (mid);
}
else if (x < a[mid])
{
binsearch(a, x, low, mid - 1);
}
else
{
}
Output:
Enter the total number of elements : 5
Enter the elements of list : 11 22 33 44 55
POINTERS
A pointer is a variable that contains the memory location of another variable.
#include<stdio.h>
int main()
{
int num,*pnum;
pnum=#
printf(“enter the number”);
scanf(“%d”,&num);
printf(“the no that was entered is %d”,*pnum);
return 0;
}
Output
Enter the number : 10
The number that was entered is : 10
Pointer Arithmetic
There are four arithmetic operators that can be used on pointers: ++, --, +, and –
Valid Pointer Arithmetic Invalid Pointer Arithmetic
Operations Operations
✓ Adding a number to pointer. ➢ Addition of two pointers.
✓ Subtracting a number form a ➢ Division of two pointers.
pointer.
✓ Incrementing a pointer.
✓ Decrementing a pointer.
✓ Subtracting two pointers.
#include <stdio.h>int main()
{
int m = 5, n = 10, q = 0;
int *p1;
int *p2;
int *p3;
OUTPUT: p1
p1 = &m; //printing the address of m
= 2680016
p2 = &n; //printing the address of n
p2 = 2680012
printf("p1 = %d\n", p1);
*p1+*p2 = 15
printf("p2 = %d\n", p2);
p1-p2 = 1
q = *p1+*p2;
p1++ = 2680020
printf("*p1+*p2 = %d\n", q);//point 1
p2-- = 2680008
p3 = p1-p2;
printf("p1 - p2 = %d\n", p3); //point 2
p1++;
printf("p1++ = %d\n", p1); //point 3
p2--;
printf("p2-- = %d\n", p2); //point 4
//Below line will give ERROR
printf("p1+p2 = %d\n", p1+p2); //point 5return 0;
}
NULL POINTER
null pointer which is a special pointer value and does not point to any value. This means that a
nullpointer does not point to any valid memory address.
int *ptr = NULL;
The null pointer is used in three ways,
1.To stop indirection in a recursive data structure.
2.As an error value
3.As a sentinel value
#include <stdio.h>
int main()
{
int *ptr = NULL;
printf("The value of ptr is %u",ptr);
return 0;
}
Output :
The value of ptr is 0
#include <stdio.h>
int main()
{
int arr[]={1,2,3,4,5,6,7,8,9};
int *ptr1, *ptr2;
ptr1 = arr;
ptr2 = &arr[8];
Output
while(ptr1<=ptr2) 1234567
{
printf("%d", *ptr1);
ptr1++;
}
return 0;
}
ARRAY OF POINTERS:
Eg:int *ptr[10];
The above statement declares an array of 10 pointers where each of the pointer points to aninteger variable.
Example 2://Program on Array of Pointers
int main()
{
int *ptr[10];
int p = 1, q = 2, r = 3, s = 4, t = 5;
ptr[0] = &p;
ptr[1] = &q; OUTPUT:4
ptr[2] = &r;
ptr[3] = &s;
ptr[4] = &t;
printf("\n %d", *ptr[3]);
return 0;
}
1. Write a program to calculate the GCD of two numbers using recursive functions.#include
<stdio.h>
int GCD(int, int);
int main()
{
int num1, num2, res;
printf("\n Enter the two numbers: ");
scanf("%d %d", &num1, &num2);
res = GCD(num1, num2);
printf("\n GCD of %d and %d = %d", num1, num2, res);
return 0;
}
int GCD(int x, int y)
{
int rem;
rem = x%y;
if(rem==0)
return y;
else
return (GCD(y, rem));
}
Output
Enter the two numbers : 8 12
GCD of 8 and 12 = 4
int Fibonacci(int n)
{ output:
if ( n == 0 ) enter the terms of Fibonacci series 01123
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n–1) + Fibonacci(n–2) ))
}
3. Write a program to add two integers using pointers and functions.
#include <stdio.h>
void sum (int*, int*, int*);int
main()
{
int num1, num2, total;
printf("\n Enter the first number : ");
scanf("%d", &num1);
printf("\n Enter the second number : ");
scanf("%d", &num2);
sum(&num1, &num2, &total);
printf("\n Total = %d", total);
return 0;
}
void sum (int *a, int *b, int *t)
{
*t = *a + *b;
}
Output
Enter the first number : 23
Enter the second number : 34
Total = 57
UNIT 4 STRUCTURES AND UNION
STRUCTURES:
• A structure is a user-defined data type that can store related information together. A
structure is acollection of variables under a single name.
• the major difference between a structure and an array is that, an array contains
related informationof the same data type.
• The variables within a structure are of different data types and each has a name that is
used to selectit from the structure.
Features of structures
• Structures can store more than one different data type data under a
single variable.
• Structure elements are stored in successive memory locations.
• Nesting of structure is possible.
• Structure elements can be passed as argument to the function.
Syntax:
//Structure creation
struct structurename
{
Datatype1
variablename;Datatype2
variablename;
.
.
};
//Object Creation
#include<stdio.h>struct point
int x,y;
};
void main()
Output:
{ (2,3)
printf(“(%d,%d)”,p1.x,p1.y);
Initialization of structures:
Syntax:
struct struct_name
datatype membername1;
datatype membername2;
datatype membername3;
}sturct_var={constant1,constant2,constant3,….};
Example:
struct student
{
int rno;
char name[20];
char course[20];
float fees;
}stud1={01,”Rahul”,”BCA”,45000};
or
Fig. illustrates how the values will be assigned to individual fields of the structure
Example:
stud1.rno=01; stud1.name=”Rahul”;stud1.course=”BCA”;stud1.fees=45000;
scanf(“%d”,&stud1.rno);
scanf(“%s”,stud1.name);
Displaying output:
printf(“Roll No:%d”,stud1.rno);printf(“Name:%s”,stud1.name);
TYPEDEF DECLARATION:
The typedef keyword enables the programmer to create a new data type name
from an existing data
type.
Syntax:
typedef existingdatatype newdatatype;
Example 1:
Example 2:
int rno;
char name[20]; char course[20];float fees;
};
Copy
Compare:
if(stud1.fees==stud2.fees)
printf(“Fees of s2 and s1 are equal”);
STRUCTURES WITHIN STRUCTURES (NESTED STRUCTURES) :
• Structures can be placed within another structures ie., a structure may contain another
structure as itsmember. A structure that contains another structure as its member is
called as nested structures.
ARRAYS OF STRUCTURES.
In the above examples, we have seen how to declare a structure and assign
values to its datamembers.
PASSING STRUCTURES THROUGH POINTERS:
• Passing large structures to functions using the call by value method is very inefficient.
Therefore, it is preferred to pass structures through pointers. It is possible to create a
pointer to almost any type in C, including the user-defined types.
struct struct_name
{
data_type member_name1;
data_type member_name2;
data_type member_name3;
.......................
}*ptr;
Or
#include <conio.h>
struct student
{
int r_no; Output
char name[20]; Enter the details of the student:
SELF-REFERENTIAL STRUCTURES
Self-referential structures are those structures that contain a reference to the data
of its same type. That is, a self-referential structure, in addition to other data, contains a pointer to
a data that is of the sametype as that of the structure. For example, consider the structure node given
below.
struct node
{
int val;
struct node *next;
};
Here, the structure node will contain two types of data: an integer val and a pointer
next. You must be wondering why we need such a structure. Actually, self-referential
structure is the foundation of other data structures. We will be using them throughout this
book and their purpose will be clearer to you when we discuss linked lists, trees, and graphs.
LINKED LISTS
Array is a linear collection of data elements in which the elements are stored in
consecutive memorylocations. Its size is fixed.
A linked list does not store its elements in consecutive memory locations and the user can
add anynumber of elements to it.
However, unlike an array, a linked list does not allow random access of data. Elements in a
linked listcan be accessed only in a sequential manner. But like an array, insertions and deletions
can be done at any point in the list in a constant time.
A linked list can be perceived as a train or a sequence of nodes in which each node contains one
ormore data fields and a pointer to the next node
Start
Since in a linked list, every node contains a pointer to another node which is of the same type, it is
also called a self-referential data type.
Declaration of node:
struct node
{
int data;
struct node *next;
}
START
.
struct node *insert_beg(struct node *start)
{
struct node *new_node;int num;
printf(“\n Enter the data : “);
scanf(“%d”, &num);
new_node = (struct node *)malloc(sizeof(struct node));
new_node -> data = num;
new_node -> next = start;
start = new_node;
return start;
}
Programming Example
Declare a structure to store information of a particular date.
struct date
{
int day;
int month;
int year;
};
Write a program, using an array of pointers to a structure, to read and display the data of
students.
#include <stdio.h>
#include <conio.h>
#include <alloc.h>
struct student
int r_no;
char name[20];
char course[20];
int fees;
};
int main()
int i, n;
scanf("%d", &n);
for(i=0;i<n;i++)
{
ptr_stud[i] = (struct student *)malloc(sizeof(struct student));
printf("\nEnter the data for student %d ", i+1);
printf("\n ROLL NO.: ");
scanf("%d", &ptr_stud[i]–>r_no);
printf("\n NAME: ");
gets(ptr_stud[i]->name);
printf(“\ncourse”);
gets(ptr->stud[i]->course);
printf(“/n FEES”);
scanf(“%d”,&ptr_stud[i]->fees);
}
printf(“\n DETAILS OF STUDENT”);
for(i=0;i<n;i++)
{
printf((“\n ROLL NO=%d”,ptr.stud[i]->r.no);
printf(“\n NAME=%s,ptr->stud[i]->name);
printf(“\n COURSE=%s,ptr->stud[i]->course);
printf(“n FEES=%d”,ptr->stud[i]->fees);
}
return 0;
}
Output
Enter the number ofstudents : 1
Enter the data forstudent 1
ROLL NO.: 01
NAME: Rahul
COURSE:BCA
FEES: 45000
DETAILS OF STUDENT
SROLL NO. = 01
NAME = Rahul
COURSE = BCA
FEES = 45000
scanf("%d", &ptr–>fees);
display(ptr);
getch();
return
}
ROLL NO.: 01
NAME: Rahul
COURSE: BCA
FEES: 45000
DETAILS OF STUDENT
ROLL NO. = 01
NAME = Rahul
COURSE = BCA
FEES = 45000