0% found this document useful (0 votes)
7 views138 pages

Computer Programming Basics in C

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

Computer Programming Basics in C

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

lOMoARcPSD|61952182

Computer Programming

Computer Engineering (Purbanchal Vishwavidyalaya)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

COMPUTER PROGRAMMING
BEG175CO
Year: I Semester: I

Teaching Schedule Examination Scheme


Hours/Week
Theory Tutorial Practical Internal Assessment Final Total
Theory Practical* Theory** Practical
3 1 3 150
40 30 60 20

* Continuous
* Duration: 3 hours

Course objectives: To provide fundamental knowledge of programming.

1. Problem Solving Using Computers


1.1 Problem Analysis
1.2 Algorithm Development & Flowcharting
1.3 Coding
1.4 Compilation & Execution
1.5 Debugging & Testing
1.6 Program Documentation
2. Introduction to C
2.1 Historical Development of C
2.2 Importance of C
2.3 Basic Structure of C Programs
2.4 Executing a C Program
3. C Fundamentals
3.1 Character Set
3.2 Identifiers & Keywords
3.3 Data Types
3.4 Constants, Variables
3.5 Declarations and Initialization of variables.
3.6 Expression, Statement and Delimeter
3.7 Escape Sequences
3.8 Preprocessors Directives
3.9 Typedef statement
3.10 Symbolic Constants ( #define )
4. Operators & Expression
4.1 Operators:
4.2 Arithmetic, Relational ,Logical, Assignment, Unary, Conditional, Bit wise
operators
4.3 Precedence & Associativity
5. Input and Output
5.1 Types of I/O
5.2 Reading & Writing data
5.3 Formatted I/O

6. Control Statements
6.1 Loops: For, While, Do-While
6.2 Decisions: IF , IF ELSE, Nested IF…ELSE

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

6.3 Statements: switch, break, continue, goto


6.4 exit( ) function
7. Functions
7.1 Advantages of using Function
7.2 User Defined & Library Functions
7.3 Function Prototypes, definition & return statement
7.4 Call by Value & Call by reference
7.5 Concept of Local, Global & Static variables
7.6 Recursive Function
8. Arrays and Strings
8.1 Introduction
8.2 Single and Multi-dimension arrays
8.3 Processing an array
8.4 Passing arrays to Functions
8.5 Arrays of Strings
8.6 String Handling Function

9. Pointers
9.1 Fundamentals
9.2 Pointer Declarations
9.3 Passing Pointers to Functions
9.4 Relationship between Arrays & Pointers
9.5 Dynamic Memory Allocation
10. Structures and Unions
10.1 Defining a Structure, Arrays of Structures, Structures within Structures
10.2 Processing a Structure
10.3 Structures & Pointers
10.4 Passing Structures to Functions
10.5 Union & its importance
11. Data Files
11.1 Opening & Closing a Data File
11.2 Creating a Data File
11.3 Processing a Data File
12. Graphics
12.1 Initialization
12.2 Graphical mode
12.3 Simple program using built in graphical function.

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

Chapter-1

 Problem Solving Using Computer

Problem solving is the process of transforming the description of a


problem into a solution by using our knowledge of the problem domain and by
relying on our ability to select and use appropriate problem-solving strategies,
techniques and tools.

Programming is a problem solving activity. When we write a program, we are


actually writing an instruction for the computer to solve something for us. Using a
computer as a problem solving tool following steps are involved.

 Problem Definition

A clearly defined problem is already half the solution. Computer


programming requires us to define the problem first before we even try to create a
solution.

 Problem Analysis

Analyzing the problem requires us to identify the following:

- Input(s) to the problem, their form and the input media to be used,
- Output(s) expected from the problem, their form and the output media to be used
- Special constraints or conditions (if any)
- Any formulas or equations to be used

For example, Computer the average marks obtained by students in "C-


Programming".

Inputs : Marks of individual students


Outputs : The average mark of students Formula:
Average : Total Marks / No of students

i.e. A = T/N

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Algorithm Development

Algorithm

An algorithm is a clear and unambiguous specification of the steps needed to


solve a problem. It may be expressed in either:

a) Human Language (e.g. Nepali, Hindi, English etc.)

b) Pseudocode  which is a cross between human language and a programming


language.

A pseudocode is:

- An artificial and informal language that helps programmers to develop algorithms


- Not an actual programming language
- Not actually executed on computers

 Flowcharting

Flowchart is the graphical representation of an algorithm using standard


symbols. In other words, Flowchart is a pictorial representation of an algorithm that
uses boxes of different shapes and connecting lines/arrows to denote different type of
instruction. A flowchart comparises a set of various standards shaped boxes that are
interconnected by flow lines.

 Advantage of Flowcharting

- Communication

Flowcharts are a better way of communications. They quickly and


clearly provide logic, ideas and descriptions of algorithms to other programmers,
students, teachers, computer operator and users.

- Effective Analysis

Flowcharts provide a clear overview of the entire problem and its


algorithm for solution. They show all major elements and their relationships. Thus,
with the help of flowcharts, problems can be analysized more effectively.

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

- Proper Documentation

The flowchart provides a permanent recording of program logic. It


documents the steps followed in an algorithm. A comprehensive, carefully drawn
flowchart is an indispensable part of documentation for each program and it helps
to understand the program and its logic in future when required.

- Efficient Coding

Flowcharts show all major parts of a program. A programmer can code the
programming instruction in a computer anguage more easily with a comprephensive
flowchart as a guide.

 Limitations of Flowchart ( Disadvantage)

- Complex Logic

A flowchart becomes complex and clumsy when the program logic is


quite compilation.

- Diffiency in alteration and modifications

If alterations are required; the flowchart may need to be redrawn


completely.

 Flowchart Symbols

Flowcharta are usually drawn using standard symbols. Some standard symbols
frequently required for flowcharting many computer programs are given below,

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Coding

Coding is the real job of programmer. The algorithm to solve a problem


which is described by pseudo-code or flow chart is converted into actual
programming language code. The code written by programmer by using any
programming language like C is called the source code or source program.

 Compilation and Execution

The source code written in any programming language is not directly


executed by the computer. It should be translated into to the machine readable format
i.e. actual machine language. The process of translation of source code into the target
code is called the compilation. Each programming language has its own compiler
program that translates the source code into its target code. The converted program
in actual machine language is then executed by the computer which is known as
program execution.

 Debugging and Testing

A written program may have errors, some errors can be detected by the language
compilers and some errors can not be identified by the compiler and occured during
the program run. Common types of errors are given below,

 Syntax Errors : Identified by compiler at the program compilation time.

 Logical Errors : Not identified by the compiler at compile time and identified
at the execution time. e.g. misuse of operators .

 Run-time Errors : The errors exist during the execution time even after the
successfully compilation known as the Run-time Errors.

So testing is the process of checking the program for its correct functionality by
executing the program with some input data set and observing the output of the
program.

 Documententions

From the start of the problem solving to the end of the implementation of
the program, all the tasks should be documented i.e. kept for future reference. It is
also the important part of the problem solving or program development.
Documentation may be two types

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

- Technical Documentation known as programmer's documentations which includes


the problem analysis to implementation details for that program. It is needed for
future reference for any modification, update of the program.
- User manual is the documentation prepared for the end-user of the program that
guides the user how to operate the program.

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

Chapter 2

 Histroy of the C programming Language

C language has evolved from three different structured language


ALGOL, BCPL and B language. It uses many concepts from these languages and
introduces many new concepts such as data types, struct, pointer etc.

C is a general-purpose computer programming language developed between 1969


and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the
UNIX operating system. According to Ritchie, the most creative period occurred in
1972. It was named "C" because its features were derived from an earlier language
called "B", which according to Ken Thompson was a stripped- down version of the
BCPL programming language. Although C was designed for implementing system
software, it is also widely used for developing portable application software.

C is one of the most widely used programming languages of all time and there are
very few computer architectures for which a C compiler does not exist. C has greatly
influenced many other popular programming languages, most notably C++, which
began as an extension to C. The origin of C is closely tied to the development of the
UNIX operating system, originally implemented in assembly language on a PDP-7
by Ritchie and Thompson, incorporating several ideas from colleagues. Eventually
they decided to port the operating system to a PDP-11. B's inability to take
advantage of some of the PDP-11's features, notably byte addressability, led to the
development of an early version of C.

The original PDP-11 version of the UNIX system was developed in assembly
language. By 1973, with the addition of struct types, the C language had become
powerful enough that most of the UNIX kernel was rewritten in C. This was one of
the first operating system kernels implemented in a language other than assembly.
(Earlier instances include the Multics system (written in PL/I), and MCP (Master
Control Program) for the Burroughs B5000 written in ALGOL in 1961.) In 1978,
Brian Kernighan and Dennis Ritchie published the first edition of The C
Programming Language. This book, known to C programmers as "K&R", served for
many years as an informal specification of the language. The version of C that it
describes is commonly referred to as K&R C. The second edition of the book covers
the later ANSI C standard.

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Importance of the C Programming Langugae

- C is robust language and has rich set of built-in functions, data types and
operators which can be used to write any complex program.
- Program written in C are efficient due to availability of several data types
and operators
- C has the capabilities of an assembly language (low level features) with the
feature of high level language so it is well suited for writing both system
software and application software.
- C is highly portable language i.e. code written in one machine can be moved
to other which is very important and powerful feature.
- C supports low level features like bit level programming and direct access to
memory using pointer which is very useful for managing resource
efficiently.
- C has high level constructs and it is more user friendly as its syntaxes
approaches to English like language.

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Structure of C Programming Language

All C programs will consist of at least one function, but we can write a
C programs that have several functions body. The only function that has to be
present is the function main. For more advanced programs the main function will
act as a controling function calling other functions in their turn to do the dirty
work! The main function is the first function that is called when your program
executes. So main is the starting of execution of program.

- Documentation Section

This setion contains a set of comment lines giving the name of program,
the author, algrothms, methods used and other details. The documentation acts as a
communication medium between members of the development team when a number
of developers are working in the same project.

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

- Link Section

This section provides instruction to te compiler to link functions with


program from the system library.

- Definiction Section

In this section, all symbolic constants are defined. Symbols play a crucial
role as they represent constants, variables, functions, and other entities in your code.

- Global Declaration Section

The variables which are used in more than one functions or blocks are
called global variables. These variables are defined or declared in this section.
This section is also declareds all the user-defined functions.

- main() Function Section

Every C program starts with a main() function. Within main() function,


there are declaration and executable parts. The decleration part declares all the
variables used in the executing part.

- Sub-program Section

This section contains all the user-defined functions that are called in the
main function. All the sections except the main() function section may ne absent
when they are not required.

 Executing In C Programming Language

- C Programming code:

When you first write the code in the C language, that source code is
sent to the processing section.

- Preprocessing

In this section our source code is attached to the preprocessor file.


Different types of header files are used like the stdio.h, math.h, etc. Our C source
code is attached to these types of files and the final C Source generates. (Some of
the preprocessor directives are #include, #define). After generating the preprocessed
C source code, the C source code is sent to the compiler section.

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

- Compiler

The preprocessed source code moves to the compiler, and an assembly-


level code is generated by the compiler after the compilation of the whole C source
code program. All the different files which have the C program must be saved with
the .c extension. For the compiler to understand whether the program file is a C
program file or not, it is necessary to have the '.c' extension. Suppose there is a
program file named as first.c. The file first.c will be the source file which will
consist of the C source code of the program. Now, when the file is compiled, the
first thing the C compiler does is to search for any error. If there is no error, the C
compiler will report for no error, after that the compiler will store the file as a .obj
file of the same name, which is termed as the object file. So by this process, the
compiler will create the [Link]. Although this .obj file will not be executable. After
the compilation, the process is continued by the assembler section.

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

- Assembler

This part usually generates the Object code, after taking the assembly-level
code from the compiler. This object code is quite similar to the machine code or the
set of binary digits. After this assembler part, The Linker continues the process,
producing an [Link] file at the end.

- Linker

Before getting started with this, we should know that the library functions
are a part of the C software but not of any C program. Hence, the compiler has no
idea about the working of the function, whether it is a printf function or scanf
function. The information for each of these functions is kept in the corresponding
library, which the compiler ought to be able to connect. The linker does this task.
So, when the #include is written, it includes the stdio.h library, which is basically
used for giving access to the Standard Output and Input. The basic goal of the linker
is to link the object file to the library functions so that the programme may be run as
an executable file (.exe). In this Linker process, the [Link] file will be created and
this file is in an executable format. After this process, the next step is the loader
process.

- Loader

Whenever the command is given for the execution of a particular program,


the loader plays an important role. With the help of the loader, the .exe file is loaded
in the RAM and the CPU is informed of the starting point of the address of the
program where it is loaded.

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Introduction to Programming Languages

Computers are general-purpose machines. It is a machine specifically


designed to follow the instructions. A set of instructions of that tells the computer
how to solve a problem or perform a task is called program. A programming
language defines a set of instructions that are complied together to perform a
specific task by the CPU (Central Processing unit). A collection of a program
called software and a special language used to code a program is called a
programming language. Programming languages are mainly two categories - High
Level Languages and Low Level Languages.

 High Level Languages

High Level Languages are developed to makes programming easier. These


languages use instructions that are closer to English and Mathematical notation. The
high level language does not require the programmer to have a detailed knowledge of
hardware of the computer. High level languages are machine independent programs
and problem oriented. High level language must also be translated into machine
language by a program before the instructions are executed

 Low Level Languages

Low Level Language is a programming language that provides no abstraction


from the hardware, and it is represented in ‘0’ and ‘1’ forms, which are the machine
instructions. The languages that come under this category are the Machine languages
and Assembly languages. Low level programming languages are computer own
language. It is more difficult for the user to understand directly. It is a machine
dependent language.

 Machine Language

The machine-level language is a language that consists of a set of instructions


that are in the binary form ‘0’ or ‘1’. Machine language is the lowest level
programming language, which is the only language understood by a computer. While
easily understood by the computers, machine languages are almost impossible for
humans to use because they consist entirely of number.

Merits

- It is directly understood by the processor so has faster execution time.


- The programs written in this language need not to be translated.
- It doesn’t need large memory.

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

Demerits

- It is very difficult to program using machine language.


- All the instructions are to be represented by ‘0s’ and ‘1s’.
- It is difficult to find error and to debug.
- It can be used by experts only.

 Assembly Language

The assembly language comes above the machine language means that it has
less abstraction level from the hardware. The assembler language is used to convert the
assembly code into the machine code. The assembly language is written in simple
English language, so it is easily understandable by the user.

Merits

- It is makes the programming easier than machine language.


- It makes programming process faster.
- It is easier to debug than machine language.
- It is easily identified the error.
- It is easy to read, write and maintain.

Demerits

- It is hardware dependent language.


- This language is very less or not portable.
- This language is not directly understandable by the computer.

 Language Translator

Language translator is system software that converts a computer program


from one language to anothr language. It takes a program written in source code and
converts it into machine code. They are different types of language translator are given
below.
- Assembler
- Compiler
- Interpreter

 Assembler

Assembler is a translator which is used to translate the assembly language


code into machine language code. Assembly language is a low-level programming
language.

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Compiler

Compiler is a translator which is used to convert programs in high-level


language to low-level language. Compiler is used to show errors to the programmer.

 Interpreter

Interpreter is a translator which is used to convert the program in high-level


language to low-level language. An interpreter translates code likes a compiler but reads
the code and immediately executes on that code, and therefore is initially faster than a
compiler.

 Programming Errors

Errors are the problems or the faults that occur in the program. The error
resulting from bad code program involved in producing the erroneous result. These
error are detected either during the time of compilation or execution. There are three
types of errors, such as

- Syntax Error
- Run-time Error
- Logic Error (Semantic Error)

 Syntax Error

Syntax errors are also known as the compilation errors or format error as they
occurred at the compilation time. These errors are mainly occurred due to the mistakes
while typing or do not follow the syntax of the specified programming language.

 Run-time Errors

The errors exist during the execution time even after the successfully
compilation known as the Run-time Errors. When the program is running, and it is not
able to perform the operation is the main cause of the run-time errors.

 Logic Error (Semantic Error)

The logic error is an error that leads to an undesired output. These errors
produce the incorrect output. The occurrence of these errors mainly depends upon the
logic thinking of the developer.

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Source code

Program written in a particular programming language in its original form is


called source code (program). Source code is the only format that readable by humans.
When we purchase programs, we usually receive them in their machine-language
format.

 Object code

Object code is the code produced by a compiler. Object code is often the same
as or similar to a computer’s machine language. The final step in producing an
executable program is to transform the object code into machine languages .

 Introduction to C Programming

C is the one of the most powerful language. C is one of the oldest and finest
programming languages. C was developed by Dennis Ritchie in 1972. It has both the
properties of high-level language and low-level language. It is very powerful
programming language because it is used to prepare system software as well as
application software.

Features of C Programming Language

- It is a structured programming language.


- It is a general purpose programming language.
- It has rich and powerful set of operators.
- It has 32 reserved words.
- It allows manipulation of internal process registers.
- It is a mid-level programming language

 Basic structure of C programming

All C programs have to follow a basic structure. A C program starts with the
main function and executes instructions presents inside it. Each instruction terminated
with a semi-colon( ; ).

 #include<stdio.h> // pre-processor directive


void main() // main function declaration
{
printf(“ Welcome to C program ”);
getch(); // terminating function
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Main Function

The main function is a part of every C program. We can represent the m,ain
function in various forms, such as
- main()
- int main()
- void main()
- main(void)
- void main(void)
- int main(void)

 Basic data types in C

A data type in a programming language is a set of data with values having


predefined characteristics. The language usually specifies the range of the values for a
given data type. The C language provides the four basic data types, such as

- int
- float
- char

 int

int refers to the Integers data type. It is used to represent the integer number or
whole number but without fractions numbers. Its requires 4 bytes memory space and
identified by “ %d ”.

 float

float refers to the floating data type. It is used to represents the real number’s
or fractional number’s. It requires 4 bytes memory space and identified by “ %f ”.

 char

char refers to the character type. It is used to represent the single character,
symbol or multiple characters. It requires 1 bytes memory for the single character and
identified by “ %c “ or “ %s “.

 Variables

Variable is the most fundamental part of any language. It is a named location


in the memory that is used to store a value during a program execution.

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

Examples :- a=3 -------- a is assigned “3”


b=4 -------- b is assigned “4”
n = 5.6 -------- b is assigned “5.6”

Rules for naming Variables

- The first character must be an alphabet or underscore ( _ ).


- No commas or blanks are allowed.
- No special symbol other than underscore is allowed.
- Variable names are case sensitive.

 Constants

Constant is a value that do not change during the execution of a program.


Integers, floating-point numbers, character and strings are just a few of the several types
of constant.
Examples :-
i) Integer Constant ------ 2, 3, 7, 4
ii) Real Constant ------ 2.5, 4.6, 6.3
iii) Character Constant ------ n, r, p, s, r
iv) String Constant ------ ‘s[100]’, ‘a[10]’, ‘n[50]’

 Keywords

All keyword have fixed meaning and these meaning cannot be changed. These
are reserved words whose meaning is already known to the compiler. Keywords in C
language cannot be used as a variable name. They are specifically used by the compiler
for its own purpose. There are 32 keywords available in C

auto double int struct

break long else switch

case return enum typedef

char register extern union

const short float unsigned

continue signed for void

default sizeof goto volatile

do static if while

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Comments

A comment is an explanation or description of the source code of the program.


It helps a developer explain logic of the code and improves program readability. At run-
time, a comment is ignored by the compiler. There are two types of comments, such as

- Single-line comment ( // ) // This is a comment.


- Multi-line comment ( /* */ ) /* This is a multi-line comment. */

 Compilation and Execution

A compiler is a computer program that converts a C program into


machine language so that it can be easily understood by the computer. The
compiler performs some basic checks and finally converts the program into an
executable.

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Operators

Operators are special symbols that are meant for specific-task or


operations. The value or variable on which the operation is performed is called
operand. They are different types of operators are given below,

- Arithmetic Operators
- Relational Operators
- Logical Operators
- Assignment Operators
- Unary Operators
- Conditional Operators
- Bitwise Operator

 Arithmetic Operators

Arithmetic operators are the operators that are used for manipulating
arithmetic data and perform arithmetic operators. C programming language are
provided five basic arithmetic operators. They are

Operator Meaning Example

+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Remainder a%b

 Relational Operators

Relational operator is used to evaluate and compare two values of the


same type, either both numerical or both string. The result of comparison is either
TRUE or FALSE. This result can then be used to make decision regarding
program flow. The relational operators used in C programming are given below,

Operator Meaning Example

== Equal to a == b
< Less than a<b
> Greater than a>b
<= Less than or equal to a <= b
>= Greater than or equal to a >= b
!= Not equal to a != b

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Logical Operators

Logical operators connect two or more relational expressions into one,


or reverse the logic of an expression. This value can be used to make decisions
about program flow. The logical operators used in C programming language are
given below,
Operator Meaning Example

&& Logical AND a && b


|| Logical OR a || b
! Logical NOT !a

 Assignment Operators

Assignment operator is represented by the symbol. The assignment


operator takes the value on the right side and stores it in the variable on the left
side. The assignment operators is used in C programming language are given
below,

Operator Meaning Example

= Assignment a=b
+= Add to a += b
-+ Subtracted from a -= b
*= Multiply by a *= b
/= Divided by a /= b
%= Modulo by a %= b

 Unary Operators

The unary operators operate on one operand-variable or constant. The C


programming language supports two important operators called increment and
decrement operators or unary operators.

Operator Meaning Example

++ Increment the value of the operand a++


-- Decrement the value of the operand a--

 Conditional Operators

Conditional operators in C Programming language are used to perform


conditional evaluations and make decisions based on conditions. The operators

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

consist of the question-mark (?) and the colon (;). The general format are given
below,
expression ? expression : expression ; ------- (x > b) ? a : b ;

 Bitwise Operators

The bitwise operators are the operators used to perform the operations
on the data at the bit-level. When we perform the bitwise operations, then it is
also known as bit-level programming

Operator Meaning Example

& bitwise AND a&b


| bitwise OR a|b
^ bitwise exclusive OR a^b
~ One’s complement (Unary) a~b
<< left shift a << b
>> right shift a >> b

 Comma Operator

The comma operator can be used to link related expressions together.


A comma - linked list of expressions are evaluated from left-to-right and the value of
rightmost expression is the value of the combined expression. The formate is given
below,
n3 = (n1 = 10, n2 = 20, n1+n2 );

 Operators,Precedence and Associativity

- Precedence

It is an order of evaluation of operators existing in an expression. There


are distinct levels of precedence ( integer values ) and an operator may belong to
one of these levels. The operators at the higher level of precedence is evaluated
first and then the operator of next level ( i.e lower level ).

- Associativity

It is an order of evaluation of operatprs with the same level of precedence


in an expression. The operators of the same precedfence are evaluated either from

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

‘left - to - right’ or from ‘right - to - left’, depending on the level. This is known
as the associativity property of an operator.

 Library Functions

Library functions in C programming language are predefined functions


that are grouped together in libraries and can be used by including the appropriate
header file in your C program.

 Printf() Function

The printf() function is used to print the values on the screen (output). It
prints the given statement to the console. The syntax of printf() function is given
below,
printf(“ format_string “, agreement_list);

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Scanf() Function

The scanf() function is used for receiving values (input). It reads the
input data from the console. The syntax of scanf() function is given below,

scanf(“ format_string “, agreement_list);

- Note :- The format string can be integer ( %d ), character ( %c ), string ( %s ),


float ( %f ), etc.

 The first program,

#include<stdio.h>
#include<conio.h>
void main()
{
printf(“ Hello Wrold “);
getch();
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Control Statement

The flow of control jumps from one part of the program to another
depending on the calculations performed in the program. Program statements that
cause jumps are called control statement. The conditional statements of C
programming language are two categories,

- Selection Statements
- Looping Statements
- Unconditional Statements

 Selection Statements

A selection statement selects among a set of statements depending on the


value of a controlling expression. On the basis of a given condition a selected
segment of the program is executed. The C programming language are support
two types of the selection statements are given below,

- If – statement ( )
- If – else statement ( : - All are the If - Statement )
- If – else - if statement ( )
- Switch statement ( Switch Statement are not If – Statement )

 If – Statement
The computer to evaluate the expression first and then, depending on
whether the value of the expression ( relation or condition ) is ‘TRUE( non-zero )’
or ‘FALSE( zero )’, it transfer the control to a particular statement. The syntax of
the if – statement is given below,

If ( condition )
{
Statement ;
}

- The flow – chart of the if – statement is


given below,

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Example of the if – Statement is given below,

#include<stdio.h>
#include<conio.h>
void main()
{
int n;
printf("Enter any number:");
scanf("%d",&n);
if(n%2==0)
{
printf("%d is even number",n);
}
}

 Nested if – Statement

When one if – statement is written within body of another if – statement,


it is called nested if statement. The several if statements shall be declared as
nested if – statement. The syntax of the nested if – statement is given below,

if ( condition )
{
If ( condition )
{
// body
}
}
 If – else Statement

The if – else statement is the most common selection statement in C


programming language. The execution of the if – else statement starts with the
evaluation of the conditions. The statement test one condition; if the first
condition is false ten other the tested. The syntax of the if – else statement are
given below,
If ( condition )
{
Statement 1;
}
else
{
Statement 2;
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

- The flow – chart of the if – else statement is given below

 Example of the if – else statement is given below,

#include<stdio.h>
#include<coni.h>
void main()
{
int n;
printf("Enter any number:");
scanf("%d",&n);
if(n%2==0)
{
printf("%d is even number",n);
}
else
{
printf("%d is odd number",n);
}
}

 If – else – if statement

The if – else – if statement is evaluated from top to the bottom. Each


conditional statement is tested, and if found true, the corresponding statement is
executed. If none of the condition is found true then the final else is executed. The
syntax of the if – else – if statement is given below

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

If ( condition )
{
Statement 1;
}
else if ( condition )
{
Statement 2;
}
else if ( condition )
{
Statement 3;
}
……………….
else
{
Statement n;
}

- The flow – chart of the if – else – if statement is given below,

 Example of the if – else – if statement is given below,

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

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

printf(" Enter the any number");


scanf("%d", &num);

if (num == 1)
{
printf(" Your number is 1\n");
}

else if (num == 2)
{
printf(" Your number is 2\n");
}

else if (num == 3)
{
printf(" Your number is 3\n");
}

else
{
printf(" Its not 1,2 or 3! ");
}
}

 Switch statement

The C programming provides a multi – branch selection statement known


as switch. The selection statements successively test the value of an expression
against a list of integer or character constant. A break statement is use to exit the
switch statement. The syntax of the switch statement is given below,

switch(expression)
{
case value 1:
Statement 1;
Break ;
case value 2:
Statement 2;
break;
------------------
default:
Statement n;
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

- The flow – chart of the switch statement is given below,

 Example of the switch statement is given below,

#include <stdio.h>
void main()
{
int Day;
printf(" Enter the day code\n");
scanf("%d", &Day);
switch (Day)
{
case 1:
printf(" First day is Sunday\n");
break;

case 2:
printf(" Second day is Monday\n");
break;

case 3:
printf(" Third day is Tuesday\n");
break;

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

case 4:
printf(" Forth day is Wednesday\n");
break;

case 5:
printf(" Fifth day is Thruesday\n");
break;

case 6:
printf(" Sixth day is Friday\n");
break;

case 7:
printf(" Seventh day is Saturday\n");
break;

default:
printf(" Invalid Day \n");
}
getch();
}

 Lopping Statement

The looping statements allow a set of instructions to be repeated a certain


numbers of times. The repetition continues while the condition set for its remains
true. While the condition becomes false, the loop ends and the control is passing
to the statement. There are four types of the looping statement are given below,

- while – loop statement


- do – while loop statement
- for – loop statement
- infinite – loop statement
- Nested – loop statement

 while – loop statement

It executes the program statements repeatedly until the given condition is


true. It checks the condition at first; if it is found true then it executes the
statements written in its body part otherwise it just gets out from the loop
structure. It is also known as the entry control or pre-test loop. The syntax of the
while loop statement is given below,

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

while ( condition )
{
Statements ;
Increment / Decrement ;
}

 The flow – chart of the while – loop statement is given below,

 Example of the while - loop statement is given below,

// Write a program to print first n natural numbers by using "while loop".

#include <stdio.h>
void main()
{
int a;
printf("Enter the number ");
scanf("%d", &a);

while(a<=1000)
{
printf("%d\n",a);
a++;
}
}

 do – while loop statement

It also executes the program statement repeatedly until the given


condition is true. It executes the program statements once at first then only

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

condition is checked. If condition is found true then it executes the program


statements again otherwise it gets out from the loop structure. It is also known as
the post – test loop or exit control loop. The syntax of the do – while loop
statement is given below,

do
{
Statements ;

Increment / Decrement ;

} while ( condition );

 The flow – chart of the do – while loop statement is given below,

 Example of the do – while loop statement is given below,

// Write a program to print first 10 natural numbers by using "do-while loop".

#include <stdio.h>
void main()
{
int i = 0;
do
{
printf(" The value of i is %d\n", i);
i++;
} while (i <= 10);
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 for – loop statement

It is the most common type of loop which is used to execute program


statement or block of the program statements repeatedly for specified number of
time. It is definite loop. Mainly it consist three expressions: initialization,
condition and increment / decrement. The initialization defines the loop starting
point, condition defines the loop stopping points and counter helps to increment
and decrement the value of the counter variable. The syntax of the for – loop
statement is given below,

for ( initialization ; condition ; increment/decrement );


{
Statements ;
}

 The flow – chart of the for – loop


statement is given below,

 Example of the for – loop statement is given below,

// Write a program to print first n natural numbers by using "for loop", Increment
Operator.

#include<stdio.h>
void main()
{
int a,n;
printf(" Enter any number :");
scanf("%d", &n);
for(a=0;a<=n;a++)
{
printf(" The value of a is %d\n", a);
}
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Infinite – loop statement

A loop which never terminates is called infinite loop that is it executes the
program statements repeatedly which doesn’t meet any ending point. It is also
called an indefinite loop or an endless loop. We can create an infinite loop
through various loop structure.

 The flow – chart of the infinite loop


is given below,

 Example of the infinite – loop is given below,

// Write a program to print Hello by using infinite loop.

#include <stdio.h>
void main()
{
infinite
{
printf("hello");
}
getch();
}

 Nested – loop statement

Any number of the loops can be defined inside another loop structure.
So, loop inside another loop is called nested loop statement. The syntax of the
nested – loop statement is given below,

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

Nested for loop,

for ( initialization ; condition ; increment/decrement );


{
for ( initialization ; condition ; increment/decrement );
{
Statement ;
}
}

 The flow – chart of the nested loop


statement is given below,

 Example of the nested - loop statement is given below,

// Write a program to print the format by using “nested – loop statement”


( 1 22 333 4444 55555 666666 7777777 ................n)

#include <stdio.h>
void main()
{
int outloop = 1;
while (outloop <= 5)
{
int inloop = 1;
while (inloop <= outloop)
{
printf(" %d", outloop);
inloop++;
}
outloop++;
printf(“ \n ”);
}
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Jumping Statement

The jumping statements are particularly used to jump execution of


program statements from one place to another inside a program. These
statements may execute same program statement repeatedly or skip some
program statement. These are the jumping statement are given below,

- break Statement
- continue Statement
- goto statement

 break Statement

It is used to break the normal flow of the program statement execution in


loop and switch case statement. It allows us to exit from innermost enclosing
loop or switch statement as soon as certain condition is satisfied. The syntax of
the break statement is given below,

// loop or switch statement

break ;

 The flow – chart of the break statement is given below,

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Example of the break statement is given below,

// Write a program to print the any number in increment order by using “ break
statement ”

#include<stdio.h>
void main()
{
int n,a;
printf(" Enter any number : ");
scanf("%d", &n);
for(a=1;a<=n;a++)
{
if(a==5)
break;
printf("%d", a);
}
}

 Continue Statement

It is used to continue the normal flow of program statement execution in


loop; skipping particular iteration in the loop as soon as certain condition is
satisfied. The syntax of the continue statement is given below,
// loop statements

continue ;

// some lines of the code

 The flow – chart of the continue


statement is given below,

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Example of the continue statement is given below,

// Write a program to print any number by using "continue statement"

#include<stdio.h>

void main()
{
int i=0,n;
printf(" Enter the any number ");
scanf(" %d", &n);

while(i<n)
{
i++;

if(i!=n)
{
continue;
}

else
{
printf("The value is %d", i);
}
}
}

 goto Statement

When the goto statement is encountered in a program then it transfers the


control of the program statements execution unconditionally to the location
specified by the goto statement within a current function. The syntax of the goto
statement is given below,

level ;

// Some part of the code

goto level ;

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 The flow – chart of the goto statement is given below,

 Example of the goto statement is given below,

// Write a program to print the multiplication table of any number by using “goto
Statement”

#include <stdio.h>
void main()
{
int num,i;
printf("Enter the any number ");
scanf("%d",&num);
table:
printf("%d X %d = %d\n",num,i,num*i);
i++;
if(i<=10)
goto table;
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Function

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


A function is a set of statements enclosed within curly brackets “{}” that take
inputs, do the computation and provides the resultant output. There are two types
of function are given below,

- Library ( built – in ) Function


- User – defined Function

 Library ( built – in ) Function

Library functions in C programming language are predefined


functions that are grouped together in libraries and can be used by including the
appropriate header file in your C program.

 User – defined Function

Library functions provide the faculty for doing some predefined


operations. User can also create functions for doing any specific task of the
program. Such function is called user – defined function.

 Advantage of Function
- Function increases code reusability,
- The program development will be faster,
- The program debugging will be easier,
- Large number of the programmer can be involved,
- The program can be developed in short period of time,
- The program can be developed in different places,

 Function Prototype

Function prototype provides the following information to the


computer. A function prototype is a declaration of the function that tells the
program about the type of the value returned by the function and the number and
type of each argument.

 Function Definition

The first line of the function definition is known as function


decelerator and is followed by the function body. It contains the actual
statements which are to be executed.

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Function call or call the function

Function can be called from anywhere in the program. The parameter


list must not differ in function calling and function declaration. We must pass the
same number of functions as it is declared in the function declaration.

 Categories of User – defined Function

- Function returning value and passing arguments.


- Function returning no value but passing arguments.
- Function returning value and passing no arguments.
- Function returning no value and passing no arguments.

 Function returning no value but passing arguments

An argument is passed from the calling function to the called function


and there will be also return statement in the called function.

- Example of the function returning value and passing arguments is given below,

// Write a program to sum of any two number by using function call.

#include<stdio.h>
int sum(int a, int b); // Function prototype
void main() // Calling Function
{
int a,b,n;
printf(" Enter the first number : ");
scanf(" %d", &a);
printf(" Enter the second number : ");
scanf(" %d", &b);
n = sum(a,b); // Function Call
printf(" The sum of a and b is %d : ", n);
}

int sum(int a, int b) // Function Declaration


{
int sum;
sum = a+b; // Function body ( called Function )
return (sum);
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Function returning no value but passing arguments

An argument from the calling function to the called function but there is
no need of return statement in the called function.

- Example of the function returning no value but passing arguments is given below,

// Write a program to sum of any two number by using function call.

#include<stdio.h>
void sum(int a , int b);
void main()
{
int a,b;
printf(" Enter the first number : ");
scanf(" %d", &a);
printf(" Enter the second number : ");
scanf(" %d", &b);
sum(a,b);
}

void sum(int a, int b)


{
int sum;
sum = a+b;
printf(" The sum of a and b is %d : ", sum);
}

 Function returning value and passing no arguments.

An argument is not passed from the calling function to the called


function but there is return statement in the called function.

- Example of the function returning value and passing arguments is given below,

// Write a program to sum of any two number by using function call.

#include<stdio.h>
int sum(int a, int b); // Function prototype
void main() // Calling Function
{
int n;
clrscr();

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

n = sum(a,b); // Function Call


printf(" The sum of a and b is %d : ", n);
}

int sum(int a, int b) // Function Declaration


{
int a,b,sum;
printf(" Enter the first number : ");
scanf(" %d", &a);
printf(" Enter the second number : ");
scanf(" %d", &b);
sum = a+b; // Function body ( called Function )
return (sum);
}

 Function returning no value and passing no arguments

An argument is not passed from the calling function to the called


function and there is no return statement in the called function.

- Example of the function returning value and passing arguments is given below,

// Write a program to sum of any two number by using function call.

#include<stdio.h>
void sum(); // Function prototype
void main() // Calling Function
{
sum(); // Function Call
}

void sum() // Function Declaration


{
int a,b,sum;
printf(" Enter the first number : ");
scanf(" %d", &a);

printf(" Enter the second number : ");


scanf(" %d", &b);

sum = a+b; // Function body ( called Function )


printf(" The sum of a and b is %d : ", sum);
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 The list of mostly used header files is given in the following table.

SN Header file Description

1 <stdio.h> This is a standard input/output header file. It


contains all the library functions regarding standard
input/output.

2 <conio.h> This is a console input/output header file.

3 <string.h> It contains all string related library functions like


gets(), puts(),etc.

4 <stdlib.h> This header file contains all the general library


functions like malloc(), calloc(), exit(), etc.

5 <math.h> This header file contains all the math operations


related functions like sqrt(), pow(), etc.

6 <time.h> This header file contains all the time-related


functions.

7 <ctype.h> This header file contains all character handling


functions.

8 <stdarg.h> Variable argument functions are defined in this


header file.

9 <signal.h> All the signal handling functions are defined in this


header file.

10 <setjmp.h> This file contains all the jump functions.

11 <locale.h> This file contains locale functions.

12 <errno.h> This file contains error handling functions.

13 <assert.h> This file contains diagnostics functions.

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Concept of Recursion ( Factorial and Fibonacci )

Recursion can be regarded as the ability of function defining an object in


terms of a simpler case of itself. It is a process by which a function calls itself
repeatedly, until some specific condition has been satisfied.

 Example of the recursion function is given below,

- // Write a program to calculate the sum of first 'n' natural number by using
"Recusive Function".

#include<stdio.h>
int sum( int n);
void main()
{
int n;
printf(" Enter the any number ");
scanf("%d",&n);
printf(" \n The sum of the given number is %d", sum(n));
}

int sum( int n)


{
int a,sum=0;
for(a=1;a<=n;a++)
sum = sum + a;
return (sum);
}

- // Write a program to calculate the nth element of Fibonacci series by using


"Recursive Function".

#include<stdio.h>
int fibo ( int n);
void main()
{
int i,n;
printf(" Enter any number : ");
scanf("%d", &n);
for (i=1;i<=n;i++)
printf(" The fibo is %d\n", fibo(i));
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

int fibo (int n)


{
if(n==0)
{
return 0;
}
else if ( n == 1)
{
return 1;
}
else
{
return (fibo(n-1) + fibo (n-2));
}
}

- // write a program to calculate the average of any three number by using


"Function".

#include<stdio.h>
void average(int a, int b, int c);
void main()
{
int a,b,c;
printf(" Enetr the first number ");
scanf("%d",&a);

printf(" Enter the second number ");


scanf("%d",&b);

printf(" Enter the third number");


scanf("%d",&c);

average(a,b,c);
}

void average(int a, int b, int c)


{
int average;
average = (a+b+c)/3;
printf(" The average value of the given number is %d ", average);
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Storage Classes

The period of time during which memory is associated with a variable is


characterized by the storage classes. So, storage class of a variable indicates the
allocation of space to variable by the compiler. The C programming Language
are support four storage class are given below,

- Automatic Variable
- External Variable
- Static Variable
- Register Variable

 Automatic Variable

The keyword auto is used to define automatic variable. Variable declared


within function bodies are automatic by default. When a block is entered, the
system allocates memory for the automatic variables.

 Example of the Automatic variable is given below,

- Write a program the variables are allocated in the run-time by using “ Automatic
Variable ”.

#include <stdio.h>
int main()
{
int a; //auto
char b;
float c;
printf("%d %c %f",a,b,c); // printing initial default value of automatic
variables a, b, and c.
return 0;
}

 External Variable

The keyword extern is used to define external type variable. The external
storage class is used to transmit information across the blocks and functions.
When a variable is declared outside function storage is permanently assigned.

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Example of the External variable is given below,

- Write a program to declared the storage in memory is permanently assigned.

#include <stdio.h>
int main()
{
extern int a;
printf("%d",a);
return 0;
}

 Static Variable

The keyword static is used to define static type variable. A value is said to
be static if it is allocated storage at the beginning of the segment and the storage
remains allocated until the program execution terminates.

 Example of the static variable is given below,

#include<stdio.h>
static char c;
static int i;
static float f;
static char s[100];
void main ()
{
printf("%c %d %f %s",c,i,f,s); // The initial default value of c,i,f and s will
} will be printed

 Register Variable

The keyword register is used to define register type variable. The use of
the register storage class is an attempt to improve execution speed. It is used
only for frequently used variables only ( that is limited either two or three ).

 Example of the register variable is given below,


#include <stdio.h>
int main()
{
register int a; // Variable a is allocated memory in the CPU register.
printf("%d", a); The initial default value of a is 0
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Arrays

An array is defined as the collection of similar type of the data items stored
at contiguous memory locations. Arrays are the derived data type in C
Programming Language which can store the primitive type of data such as int,
char, double, float, etc. They are two types of array are given below,

- Single – Dimensional Array (1D)


- Double – Dimensional Array (2D)

 Properties of the Arrays

- Each elements of an array is of the same data type and carries the same size,
- Elements of the array are stored at contiguous memory location where the first
element is stored at the smallest memory locations,
- Elements of the array can be randomly accessed since we can calculate the
address of each element of the array with the given base address and the size of
the data element.

 Single – Dimensional Array

A one dimensional array in C programming language is a collection of


elements of the same data type arranged in a single row. The syntax of the
declaring an array is given below,

int marks[100];  integer array


char name[100];  character array or string array
float percentile[100];  float array

- Note : - It is very important to note that the array index starts with ‘o’.

- The value of assigned to the array are given below,

int marks[5];  marks[0] = 56 ;


marks[1] = 76 ;
marks[2] = 80 ;
marks[3] = 86 ;
marks[4] = 98 ;

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

- The accessing elements of the array are given below,

Scanf(“ %d ”, &marks[0]);  Input first value

Printf(“ %d ”, marks[0]);  Output first value of the array

- The initialization of an array are given below,

int a[] ={34,67,58}


 Arrays can be initialized and
declaration
float m[] = {5.6,7.4}

- Example of the initialization of an array is given below,

// Write a program to print the value of a by using "Arrays" ( Initalization_Arrays ) .

#include <stdio.h>
void main()
{
int a[] = {23, 45, 56, 78};
printf(" The value of a is %d\n ", a[0]);
printf(" The value of a is %d\n ", a[1]);
printf(" The value of a is %d\n ", a[2]); --------
printf(" The value of a is %d\n ", a[3]); // |
// |
float a[] = {23, 45, 56, 78}; // |>> int or float only one use
printf(" The value of a is %f\n ", a[0]); // |
printf(" The value of a is %f\n ", a[1]); // |
printf(" The value of a is %f\n ", a[2]); ---------
printf(" The value of a is %f\n ", a[3]);
}

- The array in memory is given below,

int arr[3] = { 1,2,3 }  1 integer = 4 bytes


 This will reserve 4 x 3 = 12 bytes in memory.

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

- Array with Function

// Write a program to print the any number by using “ Arrays with Functions "

#include<stdio.h>

void printArray(int ptr[], int n)


{
for( int i=0;i<n;i++)
{
printf(" The value of the elements %d is %d\n", i+1,ptr[i]);
}
}

void main()
{
int arr[] = {1,43,644,7456,8545,6756,6786,3556,4556};
printArray(arr,9);
}

 Multi – Dimensional Array

Arrays can be of 2-dimensional, 3-dimensional, ........... n-dimensional array.

- Example of the Multi – Dimensional array is given below,

// Write a program to print the Marks in subjects by using "Multidimensional


Arrays".

#include <stdio.h>

void main()
{
int n_students, n_subjects;
int Marks[n_students][n_subjects];
printf(" How many Students are : ");
scanf("%d", &n_students);
printf(" How many Subjects are : ");
scanf("%d", &n_subjects);
for (int i = 0; i < n_students; i++)
{
for (int j = 0; j < n_subjects; j++)
{

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

printf(" Enter the Marks of the Students %d in Subjects %d\n", i + 1, j + 1);


scanf("%d", &Marks[i][j]);
}
}
for (int i = 0; i < n_students; i++)
{
for (int j = 0; j < n_subjects; j++)
{
printf("The Marks of the Students %d in Subjects %d is %d\n", i + 1, j + 1,Marks[i][j]);
}
}
}

 Two – Dimensional Array ( 2D )

The two-dimensional array can be defined as an array of arrays. The 2D array


is organized as matrices which can be represented as the collection of rows and
columns. However, 2D arrays are created to implement a relational database
lookalike data structure. The syntax of the two – dimensional array is given
below,
data_type array_name [rows][columns];

- The declaration of the two – dimensional array is given below,

int n[4][3];  Here, 4 is the number of rows and 3 is the number of columns

- The initialization of the two - dimensional array is given below,

int arr[4][3] = {{1,2,3},{2,3,4},{3,4,5},{4,5,6}}

- Example of the two – dimensional array is given below,

// Write a program to print the matrix of the order [4][3].

#include<stdio.h>
void main()
{
int i=0, j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
// traversing 2D array
for(i=0;i<4;i++)
{
for(j=0;j<3;j++)

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

{
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}
}
}

 Strings

The string can be defined as the one-dimensional array of characters


terminated by a null ('\0'). The character array or the string is used to manipulate
text such as word or sentences. Each character in the array occupies one byte of
memory, and the last character must always be 0. The termination character ('\0') is
important in a string since it is the only way to identify where the string ends.
When we define a string as char s[10], the character s[10] is implicitly initialized
with the null in the memory.

- The initialization of the string is an array of the characters are given below,

char s[] = {'N', 'A', 'G', 'E', 'N', 'D', 'R', 'A', '\0'};
or
char s[] = “ NAGENDRA ”

 Array of String

An array of string is a two-dimensional character array the size of first index


(rows) determines the number of strings and the size of second index (column)
determine maximum length of each string.

- Example of the array of string is given below,

// Write a program to arrange list of student name in ascending order,

#include <stdio.h>
#include <conio.h>
#include <string.h>
void main()
{
char name[5][10], temp[10];
int i, j;
for (i = 0; i < 5; i++)
{
printf("\nEnter the name of student:");

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

scanf("%s", name[i]);
}
for (i = 0; i < (5 - 1); i++)
{
for (j = i + 1; j < 5; j++)
{
if (strcmp(name[i], name[j]) > 0)
{
strcpy(temp, name[i]);
strcpy(name[i], name[j]);
strcpy(name[j], temp);
}
}
}
printf("\n the name of student is:");
for (i = 0; i < 5; i++)
{
printf("\n%s", name[i]);
}
getch();
}

- The string should be short enough to fit into the array.


- Scanf cannot be used to input multi – word strings with spaces.

 gets() and puts() Functions

The gets() and puts() are declared in the header file stdio.h and both the
functions are involved in the input / output operations of the strings.

 gets() Function

The gets() function enables the user to enter some characters followed by
the enter key. All the characters entered by the user get stored in a character array.
The null character is added to the array to make it a string. The gets() allows the
user to enter the space-separated strings.

- The syntax declaration of the gets() function is given below,

char str[100];
// Source code
gets ( str );

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

- Example of the “ gets() string function ” is given below,

// Write a program to print any milti-character supplied by the user by using "gets()
Strings function ".

#include <stdio.h>
void main()
{
char str[10];
printf(" Enter any Character : ");
gets(str); // Multi-Words string
{
printf("Your Name is : %s", str);
}
}

 puts() Function

The puts() function is very much similar to printf() function. The puts()
function is used to print the string on the console which is previously read by using
gets() or scanf() function. The puts() function returns an integer value representing
the number of characters being printed on the console. Since, it prints an additional
newline character with the string, which moves the cursor to the new line on the
console. The syntax declaration of the puts() function is given below,

int puts ( char[] )

- Example of the “ puts() string function ” function is given below,

// Write a program to print any multi-character by using “ puts() string function ”,


cannot without gets() string function.

#include <stdio.h>
#include <string.h>
void main()
{
char name[50];
printf("Enter any character : ");
gets(name); // reads string from user
printf("Your character is: ");
puts(name); // displays string
getch();
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

- There are many important string functions defined in ‘ string.h ’ library are given
below,

[Link]. Functions Description


1. strlen(string_name) returns the length of string name
2. strcpy(destination, Source) copies the contents of source string to
destination string.
3. concats or joins first string with
strcat(first_string, second_string) second string. The result of the
string is stored in first string.
4. compares the first string with second
strcmp(first_string, second_string) string. If both strings are same, it
returns 0.
5. strrev(string) returns reverse string
6. strlwr(string) returns string characters in lowercase
7. strupr(string) returns string characters in lowercase

 String Length ( strlen()Function )

This function is used to count the number of characters in the string. It


doesn’t count the null ( ' \0 ' ) character.

- Example of the strlen() function is given below,

// Write a program to count the number of any character supplied by the user by
using "Strings".

#include<stdio.h>
#include<string.h>
void main()
{
char str[] = "Nagendra";
int a;
a = strlen(str);
printf(" The length of the string in str is : %d",a);
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Copy string ( strcpy() )

This function is used to copy the content of second string into first string
passed to it.

- Example of the strcpy() function is given below,

/* write a program to copy the content of second strings into first string
then the print in Display by using "strings".*/

#include<stdio.h>
#include<string.h>
void main()
{
char str1[100] = "Nagendra";
char str2[100];
strcpy(str2, str1);
printf(" Now the str2 is %s", str1);
}

 String concatenation ( strcat() )

This function is used to concatenate two strings.

- Example of the strcat() function is given below,

//Write a program to print two character between no space in two character by


using "strings".

#include<stdio.h>
#include<string.h>
void main()
{
char str1[100] = "Nagendra";
char str2[100] = "Mukesh";
strcat(str1, str2);
printf("%s",str1,str2);
}

 Compare string ( strcmp() )

This function is used to compare two strings. It returns: 0 if strings are equal.
The negative value if first strings mismatching character's ASCII value is not

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

greater than second string's corresponding mismatching character. It returns


positive values if first strings mismatching character's ASCII value is greater than
second string's corresponding mismatching character.

- Example of the strcmp() function is given below,

// Write a program to check the ascii value by using "Strings".

#include<stdio.h>
#include<string.h>
void main()
{
char str1[100] = "Nagendra";
char str2[100] = "Nagendra";
int val = strcmp(str1, str2);
printf("%d",val);
}

 String Lowercase ( strlwr() )

The strlwr() function returns string character in lowercase. However, it's


not a standard function defined in the C standard library. Instead, it's found in
some specific compilers or libraries.

- Example of the strlwr() function is given below,

// Write a program to print the any lowercase character by using strlwr().

#include <stdio.h>
#include <string.h>
void main()
{
char str[20];
printf("Enter string: ");
gets(str); // reads string from console
printf("String is: %s", str);
printf("\nLower String is: %s", strlwr(str));
}

 String Uppercase ( strupr() )

The strupr(string) function returns string characters in uppercase. It is not


a part of the standard C programming language library.

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

- Example of the strupr() function is given below,

// Write a program to print the any uppercase character by using strupr().

include <stdio.h>
#include <string.h>
void main()
{
char str[20];
printf("Enter string: ");
gets(str); // reads string from console
printf("String is: %s", str);
printf("\nUpper String is: %s", strupr(str));
}

 String- String ( Strstr() )

The strstr() function returns pointer to the first occurrence of the matched
string in the given string. It is used to return substring from first match till the last
character.

- Example of the strstr() function is given below,

#include <stdio.h>
#include <string.h>
int main()
{
char str[100] = "Our country name is Nepal. Our country is landlocked country.";
char *sub;
sub = strstr(str, "country");
printf("\nSubstring is: %s", sub);
return 0;
}

 String Reverse ( strrev )

The function strrev() is used to reverse all characters in string except null
character at the end of string. The reverse of string “ abc ” is “ cba ” . The syntax
of the strrev() is given below,
Strrev ( string )

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Pointers

. The pointer in C language is a variable which stores the address of another


variable. This variable can be of type int, char, array, function, or any other pointer.
The size of the pointer depends on the architecture of the computer.

 Features of the pointer

- Pointer saves memory space.


- Pointer assigns the memory space and also releases it which makes the best use of
the available memory ( dynamic memory allocation ).
- The execution time is faster because data manipulation is done directly inside
memory.
- Pointer is closed to array so it is efficient for solving array and string related
problems.
- Pointer is closed to hardware so it is very efficient for solving hardware interfacing
problems.

 The address ( & ) and Iindirection ( * ) Operator

The ( & ) is the address operator, it represents the address of the variable and
the ( * ) operator is the value at address operator. It represents the value at the
specified address.

- The declaration of the pointer is given below,

int a = 89 ;  This is a integer type variable of ‘a’


int *b = &a ;  This is a pointer integer ‘*b’ and store the address of ‘a’
int **c = &b ;  This is a pointer integer ‘**c’ and store the address of ‘b’

char a = ‘N’ ;  This is a character type variable of ‘a’


char *b = &a ;  This is a pointer character ‘*b’ and store the address of ‘a’
char **c = &b ;  This is a pointer character ‘**c’ and store the address of ‘b’

float a = 8.9 ;  This is a floating type of ‘a’


float *b = &a ;  This is a pointer float ‘*b’ and store the address of ‘a’
float **c = &b ;  This is a pointer float ‘**c’ and store the address of ‘b’

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

- Example of the pointer is given below,

// Write a program to print the integer address of a,b,c,d and the integer value of
a,b,c,d by using “ pointer ”.

#include <stdio.h>
void main()
{
int a;
int *b = &a;
int **c = &b;
int ***d = &c;

printf(" Enter any number ");


scanf("%d", &a);

printf("\n The value of A is %d\n", a);


printf(" The value of A is %d\n", *b);
printf(" The address of A is %u\n", &a);
printf(" The address of A is %u\n", b);
printf(" The value of B is %u\n", *(&b));
printf(" The address of B %u\n", &b);
printf(" The value of A is %u\n", *(&a));
printf("The address of Pointer B is %u\n", &c);
printf("The address of Pointer C is %u\n", &d);
printf(" The value of pointer to pointer C is %d", **c);
}

 Call by values

The values of the variables are passed. In this, values of the variables are not
affected by changing the value of the formal parameter. When an argument is passed
by the value, the data item is copied to the function.

- Example of the call by values is given below,

// Write a program to swap two number showing call by values.

#include <stdio.h>
void swap(int a, int b);
void main()
{
int a = 10;

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

int b = 12;
swap(a, b); // call by values
printf(" The after swapping the value of a and b is %d %d", a, b);
}

void swap(int a, int b)


{
int temp;
temp = a;
a = b;
b = temp;
}

 Call by reference

The address of the variable is passed. The contents of that address can be
accessed freely, either within the function or within the calling routine. The use of
painter as a function argument permits the corresponding data item to be altered
globally from within the function.

- Example of the call by reference is given below,

// Write a program to swap two numbers showing call by reference.

#include <stdio.h>
void swap(int *a, int *b);
void main()
{
int a = 10;
int b = 12;
swap(&a, &b); // call by values
printf(" The after awapping the value of a and b is %d %d", a, b);
}

void swap(int *a, int *b)


{
int temp;
temp = *a;
*a = *b;
*b = temp;
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 NULL Pointer

A NULL pointer is a special pointer value that points nowhere or nothing


in memory address. That is, no other valid pointer to any other variable or array cell
or anything else will ever be equal to a NULL Pointer.

 Pointer to Pointer ( Double Pointer )

C rogramming allows the use of a pointer that points to other pointers,


and these, in turn, point to data. In case of pointer to pointer decleration, we need to
add asterisk ( * ) for each level of reference.

 Array of Pointers

The multiple pointers of same type can be represented by an array. Each


element of such array represents pointer and they can point to different locations.
An array of pointers can be declared is given below,

Data_type *pointer_name [size]

- The relation between Arrays and Pointers is given below,

[Link]. Arrays Pointers


1 An array is a collection of elements A pointer is a variable that stores
of the same data type stored in the memory address of another
contiguous memory locations. variable.
2 Elements in an array are accessed Pointers can be used to indirectly
using an index. The index access the value stored at a
represents the position of the particular memory location.
element in the array.
3 Arrays have a fixed size, which is Pointers can be dynamically
determined at the time of allocated, allowing for more
declaration. flexibility in memory management.
4 The example of the array is given The example of the array is given
below, below,
int x = 10;
int myArray[5] = {1, 2, 3, 4, 5}; int *ptr = &x;

 Dynamic Memory Allocation (DMA)

The process of allocating and freeing memory in a program at run


time is known as DMA. The DMA process reserves the memory required by the

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

program and allows the program to utilize the memory. When the allocated memory
is no more in use, it returns the allocated memory to the system. The deallocated
memory now is free and any other program can use it. Dynamic memory allocation
in c language is possible by 4 functions of stdlib.h header file.

- malloc() Function

malloc() is the standard library function used to allocate a memory block of


specified number of bytes and returns void pointer. The void pointer can be casted to
any datatype. If malloc() function unable to allocate memory due to any reason it
returns NULL pointer. The syntax of the malloc() is gven below,

ptr = (data_type*) malloc (size_of_block);

- calloc() Function

calloc() is the standard library function used to allocate multiple memory


blocks of the specified number of bytes and initializes them to ZERO. calloc()
function returns void pointer. If calloc() function unable to allocate memory due to
any reason it returns a NULL pointer. Generally, calloc() is used to allocate memory
for array and structure. calloc() function takes two arguments and they are 1. The
number of blocks to be allocated 2, Size of each block in bytes. The syntax of the
calloc() is given below,

ptr = (data_type*) calloc(no_of_blocks, size_of_each_block);

- realloc() Function

realloc() is the standard library function used to modify the size of memory
blocks that were previously allocated using malloc() or calloc(). realloc() function
returns void pointer. If calloc() function unable to allocate memory due to any reason
it returns NULL pointer. The syntax of the realloc() is given below,

ptr = (data_type*) realloc (*pointer, new_size_of_each_block_in_bytes);

- free() Function

free() is the standard library function used to deallocate memory block


that was previously allocated using malloc() or calloc(). free() function returns void
pointer. When free() function is used with memory allocated that was created using
calloc(), all the blocks are get deallocated. The syntax of the free() is given below,

free(ptr);

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Structure

Structure is defined as the collection of dissimilar data items treated as single


unit. Each data item is called member of structure. The keyword struct is used to
declare structure variable and type of structure variable is defined by the tag_name
of the structure. The syntax of the structure is given below,

struct employee
{
int Id;
float Salary;  this declares a new user-defined datatype
char Name[50];
};

( Semi-colon is important )

 Some major features of structure.

- It is possible to define structure pointer also known as linked list.


- It is possible to pass structure variable as parameter to any function.
- It allows nested structure that is one structure inside another structure.
- It can be treated as record that is collection of inter-related data fields having
different data types.
- It is possible to copy one structure variable to another by simply assignment
operator (=).

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Array of structure

An array of structures in C can be defined as the collection of multiple


structures variables where each variable contains information about different
entities. The array of structures of Care used to store information about multiple
entities of different data types. The array of structures is also known as the
collection of structures.

- Example of the array of structure is given below,

// Write a program to store the information of five (5) students ant print them.

#include <stdio.h>
#include <string.h>
struct student
{
int rollno;
char name[10];
};
void main()
{
int i;
struct student st[5];
printf("Enter Records of 5 students");
for (i = 0; i < 5; i++)
{
printf("\nEnter Rollno:");
scanf("%d", &st[i].rollno);
printf("\nEnter Name:");
scanf("%s", &st[i].name);
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

printf("\nStudent Information List:");


for (i = 0; i < 5; i++)
{
printf("\nRollno : %d, Name : %s", st[i].rollno, st[i].name);
}
}

- The structure can also be initialized is given below,

struct employee Nagendra = { 1098, 110.5, “Mukesh” };

struct employee suraj = { 0 }; // All elements set to zero (0)

 Structure in memory

The actual memory size of a variable in terms of bytes may vary from machine
to machine. Therefore, the sizeof operator helps us to determine memory size of a
variable.

1098 110.5 “Nagendra”


Address  285646 2805650 2805654

- The pointers to structures or arrow operator to structure is given below,

/* Write a program that takes Id, Name, Salary, Address and supplied by the user
then the print on screen by using "Pointer to structure". */

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

struct employee
{
int Id;
char Name[100];
float Salary;
char Address[100];
};

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

void main()
{
struct employee Emp1;
struct employee *ptr;
ptr = &Emp1;

(*ptr).Id;
(*ptr).Name;  Pointer operator
(*ptr).Salary;
(*ptr).Address;

// ptr->Id;
// ptr->Name;  Arrow Operator
// ptr->Salary;
// ptr->Address;

printf("Enter the Id of Emp1 : ");


scanf("%d", &[Link]);

printf("Enter the Name of Emp1 : ");


scanf("%s", &[Link]);

printf("Enter the Salary of Emp1 : ");


scanf("%f", &[Link]);

printf("Enter the Address of Emp1 : ");


scanf("%s", &[Link]);

printf("\n****************************************************\n\n");

printf("Id = %d\n", [Link]);


printf("Name = %s\n", [Link]);
printf("Salary = %.3f\n", [Link]);
printf("Address = %s\n", [Link]);

printf("\n\n******************************************************");
}

 Passing Structure to a Function

A function can be called by passing structure variable as parameter. Structure


variable can be passed in various way: member can be passed individually or entire
structure can be passed at once.

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

- Example of the passing structure to a pointer is given below,

/* Write a program that takes Id, Name, Salary, Address and supplied by the user
then the print on screen by using "Passing structure of a Function". */

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

struct employee
{
int Id;
char Name[100];
float Salary;
char Address[100];
};

void show(struct employee Emp1)


{
printf("\n**************************************************\n\n");
printf("Id = %d\n", [Link]);
printf("Name = %s\n", [Link]);
printf("Salary = %.3f\n", [Link]);
printf("Address = %s\n", [Link]);
printf("\n\n*************************************************\n\n");
}

void main()
{
struct employee Emp1;
struct employee *ptr;
ptr = &Emp1;

// (*ptr).Id;
// (*ptr).Name;
// (*ptr).Salary;
// (*ptr).Address;

ptr->Id;
ptr->Name;
ptr->Salary;
ptr->Address;

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

printf("Enter the Id of Emp1 : ");


scanf("%d", &[Link]);
printf("Enter the Name of Emp1 : ");
scanf("%s", &[Link]);
printf("Enter the Salary of Emp1 : ");
scanf("%f", &[Link]);
printf("Enter the Address of Emp1 : ");
scanf("%s", &[Link]);

show(Emp1);
}

 Typedef keyword

The typedef keyword allows us to define new data types that are equivalent to
existing data types. This feature also can be implemented to structure to define user
define data types.

- Example of the typedef keyword is given below,

/* Write a program that takes Id, Name, Salary, Address and supplied by the user
then the print on screen by using "Typedef Structure". */

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

typedef struct employee


{
int Id;
char Name[100];
float Salary;
char Address[100];
} Emp;

void show(struct employee Emp1)


{
printf("\n***************************************************\n\n");
printf("Id = %d\n", [Link]);
printf("Name = %s\n", [Link]);
printf("Salary = %.3f\n", [Link]);
printf("Address = %s\n", [Link]);
printf("\n\n**************************************************\n\n");
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

void main()
{
Emp Emp1;
Emp *ptr;
ptr = &Emp1;

ptr->Id;
ptr->Name;
ptr->Salary;
ptr->Address;

printf("Enter the Id of Emp1 : ");


scanf("%d", &[Link]);
printf("Enter the Name of Emp1 : ");
scanf("%s", &[Link]);
printf("Enter the Salary of Emp1 : ");
scanf("%f", &[Link]);
printf("Enter the Address of Emp1 : ");
scanf("%s", &[Link]);

show(Emp1);
}

 Nested Structure ( Structure with Structure)

Structure is defined as a member of another structure. It is also known as


nested structure.

- Example of the nested structure is given below,

// Wriet a program that takes Roll_No, Name, Address and Date of Birth and
output the information on screen.

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

struct date
{
int year;
int month;
int day;
};

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

struct student
{
int Roll_No;
char Name[100];
char Address[100];
struct date d;
};

void main()
{
struct student a;
printf(" Enter The Roll No. : ");
scanf("%d", &a.Roll_No);
printf(" Enter the Name : ");
scanf("%s", &[Link]);
printf(" ENter the Address : ");
scanf("%s", &[Link]);
printf(" Enter the Date of Birth YYYY/MM/DD : ");
scanf("%d %d %d", &[Link], &[Link], &[Link]);

printf("\n****************************************************\n\n");
printf("Id = %d\n", a.Roll_No);
printf("Name = %s\n", [Link]);
printf("Address = %s\n", [Link]);
printf("Date of Birth = %d/%d/%d", [Link], [Link], [Link]);
printf("\n\n**************************************************\n\n");
}

 Union

Union can be defined as a user-defined data type which is a collection of


different variables of different data types in the same memory location. The union
can also be defined as many members, but only one member can contain a value at
a particular point in time. The syntax of the union is given below,

union tag_name
{
data_type member1;
data_type member2;
................
data_type membern;
};

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Importance of Union

- Unions allow you to store different data types in the same memory location, saving
memory by sharing the space among members.
- Unions provide flexibility in handling multiple data types within the same memory
space, making it easier to represent dynamic or polymorphic data.
- Unions are useful for bit-level operations and manipulations, allowing access to
individual bits within a byte or a word.
- Unions are employed in scenarios where a single memory location needs to
represent different aspects of data efficiently.
- Unions can simplify the representation of complex data structures by allowing the
use of a single memory location for different types of data.

 Difference between Structure and Union are given below,

[Link]. Structure Union


1. It is the collection of data items Same as structure but it differs in its
having dissimilar data types. storage class.
2. Memory size is determined by sum of Memory size is determined by the
memories allocated to all the members. memory.
3. Multiple members can be simultaneous Only one member can be accessed
accessed at a time. at a time
4. The syntax keyword is used to The syntax keyword is used to
define structure is given below, define union is given below,

struct tag_name union tag_name


{ {
data_type member1; data_type member1;
data_type member2; data_type member2;
................ ................
data_type membern; data_type membern;
} var; } var;

5. The example of the structure is The example of the union is given


given below, below,
struct employee
{ union employee
int Id; {
float Salary; int Id;
char Name[50]; float Salary;
}; char Name[50];
};

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Difference between Structure and Array are given below,

[Link]. Structure Array


1. It is the collection of data items It is the collection of data items
having dissimilar data types. having similar data types.
2. Each data item is called member. Each data item is called elements.
3. It is user defined data type. It is built in data types.
4. It is possible to define array of It is not possible to define array of
structure. array or array of structure.
5. The syntax of the Structure is given The syntax of the array is given
below, below,

struct tag_name data_type array_name[size];


{
data_type member1;
data_type member2;
................
data_type membern;
} var;

6. The example of the structure is The example of the array is given


given below, below,

struct employee int a[50];


{ char s[100];
int Id; float c[10];
float Salary;
char Name[50];
};

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Concept of Data Files

A data file is defined as the collection of data or information which is


permanently stored inside secondary memory as a single unit. We can read, write,
append and delete data in data file as per our requirements. There are two types file
processing are given below,
- Sequential File Processing
- Random File Processing

 Sequential File Processing

The data is sequentially accessed from/tpo data filr. It is very time consuming
technique. If we need to access the last record of a file, then we need to access all
the records before that record.

 Random File Processing

The data is randomly accessed anywhere from/to data file. It is more faster
technique than the previous one. We can read and write data in particular part of a
file with the help of the function ftell(), fseek() and rewind().

- ftell()

It takes file pointer as parameter and returns lng data type that represent the
current position of the file in terms of bytes.

n = ftell(fp);

- rewind()

It takes file pointer as parameter and reset the position to the start of the file.

rewind(fp);

- fseek()

It helps to move the file position to the desire location within the file. It takes
three parameter fp file pointer, offset position of the file in terms of bytes and
position specifies three values: 0 – beginning, 1-current position and 2 end of the
file.
Fseek(fp, offset, position);

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 The file manipulation Function are given below of the table,

[Link]. Function Description


1. fopen() To create new data file or existing file.
2. fclose() To close the data file.
3. fgetc() To read the character from the data file.
4. fputc() To write a character to the data file.
5. fgetw() To read an integer from the data file.
6. fputw() To write an integer to the data file.
7. fprintf() To write the formatted data to the data file.
8. fscanf() To read the formatted data from the data file.
9. fseek() To sets the file pointer to the given position.
10. rewind() To sets the file pointer to the beginning of the file.
11. ftell() To returns the current position.
12. fread() To read record from the data file.
13. fwrite() To write record to the data file.

 Opeaning File ( fopen() )

We must open a file before it can be read, write, or update. The fopen()
function is used to open a file. The syntax of the fopen() is given below,

FILE *fopen ( const char * file_name, const char * mode );

- The use one of the following modes in fopen() function is given below,

[Link]. Mode Description


1. r To opens a text file in read mode.
2. W To opens a text file in write mode.
3. a To opens a text file in append mode
4. r+ To opens a text file in read and write mode.
5. w+ To opens a text file in read and write mode.
6. a+ To opens a text file in read and write mode.
7. rb To opens a binary file in read mode.
8. wb To opens a binary file in write mode.
9. ab To opens a binary file in append mode.
10. rb+ To opens a binary file in read and write mode.
11. wb+ To opens a binary file in read and write mode.
12. ab+ To opens a binary file in read and write mode.

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 fputc() Fuctions

The fputc() function is used to write a single character into file. It outputs
a character to a stream. The syntax of the fputc() function is given below,

int fputc( int c, FILE*stream )

- Example of the fputc() function is given below,

// Write a program to print the single character by using “ fputc()”

#include <stdio.h>
void main()
{
FILE *fp;
fp = fopen("[Link]", "w"); // opening file
fputc('a', fp); // writing single character into file
fclose(fp); // closing file
}

 fgetc() Function

The fgetc() function returns a single character from the file. It gets a
character from the stream. It returns EOF at the end of file. The syntax of the
fgetc() function is given below,

int fgetc( FILE*stream )

- Example of the fgetc() Function is given below,

// Write a program to read the all character of the file in "[Link]".

#include<stdio.h>

void main()
{
FILE *ptr;
char ch;
ptr = fopen("[Link]","r");
ch = fgetc(ptr);
while(ch!=EOF)
{

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

printf("%c",ch);
ch = fgetc(ptr);
}
}

 fprintf() Function

The fprintf() function is used to write set of characters into file. It sends
formatted output to a stream. The syntax of the fprintf() is given below,

int fprintf( FILE * stream, const char * format[, argument, ….])

- Example of the fprintf() is given below,

// Erite a program, to write Roll_No, Name and Percentage of 5 students to a


file .

#include <stdio.h>
void main()
{
FILE *ptr;
int Roll_No;
char Name[100];
float per;
int i = 1;
ptr = fopen("[Link]", " w");

do
{
printf(" Enter the Roll_No : ");
scanf(" %d", &Roll_No);
printf(" ENter the Name : ");
scanf(" %s", &Name);
printf(" Enter the percentage : ");
scanf(" %f", &per);
fprintf(ptr, "\n %d\t %s\t %f", Roll_No, Name, per);
i++;
} while (i <= 5);

fclose(ptr);
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 fscanf() Function

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. The syntax of the fscanf()
function is given below,

int fscanf( FILE * stream, const char * format[, argument, ….])

- Example of the fscanf() funcrtion is given below,

// Erite a program to read Roll_No, Name and Percentage of 5 students from the
file .

#include <stdio.h>
void main()
{
FILE *ptr;
int Roll_No;
char Name[100];
float per;
int i = 1;
ptr = fopen("[Link]", " r");
printf(" \n Data from the file\n");

while ((fscanf(ptr, " %d\t %s\t %f ", &Roll_No, Name, &per)) != EOF)
printf(" \n %d\t %s\t %f", Roll_No, Name, per);

fclose(ptr);
}

 Error Handling During I/O Operations

C programming language does not support error handling that are


occured at program execution time. However, C provides a header file called error.h.
The header file error.h contains few methods and variables that are used to locate
error occured during the program execution.

- foef()

C feof() function is used to determine if the end of the file (stream) specified
has been reached or not. This function keeps on searching the end of the file (EOF)

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

in your file program. This tutorial guides you on how to use the feof() function in the
C program. The syntax of the feof() function is given below,

int foef ( FILE * stream )

- ferror()

The ferror() function check for an error in reading from or writing to the given
[Link] an error occurs, the error indicator remains set until you close stream,
call the clearerr() function. The syntax of the ferror() function is given below,

int ferror ( FILE * stream )

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 All the program of the all chapters are given below,

- // Find the volume of the rectangle by using inputs supplied by the user.

#include<stdio.h>
#include<conio.h>
void main()
{
int l,b,h,V;
printf("Enter the lentgh of the rectangular");
scanf("%d",&l);
printf("Enter the breadth of the rectangular");
scanf("%d",&b);
printf("Enter the height of the rectangular");
scanf("%d",&h);
V=l*b*h;
printf("\n Volume is=%d", V);
getch();
}

- // Find the value of a, b, c, d and the sum, subtract and remainder.

#include <stdio.h>
int main()
{
int a = 16;
int d = 8;
float b = 8.5;
char c = 'N';
printf("\nThe value of a is %d", a);
printf("\nThe value of b is %f", b);
printf("\nThe value of c is %c", c);
printf("\nThe value of d is %d", d);
printf("\nThe sum of a and b is %f", a + b);
printf("\nThe substract of a and d is %d", a - d);
printf("\nThe Remainder of a and d is %d", a % d);
return 0;
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

- // Find the sum of two number by using inputs supplied by the user.

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,s;
printf("\nEnter the first number= ");
scanf("%d",&a);
printf("\nEnter the first number= ");
scanf("%d",&b);
s=a+b;
printf(" The sum of a and b is %d",s);
getch();
}

- // Find the area of the rectangle by using inputs supplied by the user.

#include<stdio.h>
#include<conio.h>
void main()
{
int l,b,a;
printf("\n Enter the length of the rectangle ");
scanf("%d",&l);
printf("\n Enter the breadth of the rectangle ");
scanf("%d",&b);
a=l*b;
printf("The area of the rectangle is %d",a);
getch();
}

- // Find the area of the circle by using inputs supplied by the user.

#include<stdio.h>
#include<conio.h>
void main()
{
int radius, Area;
float pi = 3.14;
printf("Enter the radius of the circle ");
scanf("%d", &radius);

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

Area = pi*radius*radius;
printf(" The area of the circle is %d", Area);
getch();
}

- // Find the volume of the cylinder by using inputs supplied by the user.

#include<stdio.h>
#include<conio.h>
void main()
{
int radius,height, Volume;
float pi = 3.14;
printf("Enter the radius of the cylinder ");
scanf("%d", &radius);
printf("Enter the height of the cylinder ");
scanf("%d", &height);
Volume = pi*radius*radius*height;
printf(" The Volume of the circle is %d", Volume);
getch();
}

- // Write a program to convert the celsius temperature to fahrenheit temperature.

#include<stdio.h>
#include<conio.h>
void main()
{
float C,F;
printf(" Enter the celsius temperature ");
scanf("%f",&C);
F = ((C*(9.0/5.0))+32);
printf(" The value of the celsius into fahrenheit temperature is %f", F);
getch();
}

- // Write a prgram to find the value of the SimpleInterest by using inputs supplied
by the user.

#include<stdio.h>
#include<conio.h>
void main()
{

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

int principal,time,rate,SimpleInterest;
printf(" Enter the principal value ");
scanf("%d", &principal);
printf(" Enter the time ");
scanf("%d", &time);
printf(" Enter the rate value ");
scanf("%d", &rate);
SimpleInterest = (principal*time*rate)/100;
printf(" The value of the SimpleInterest is %d", SimpleInterest);
getch();
}

- // Write a program to find the value of equation by using inputs supplied by the
user.

#include <stdio.h>
#include <stdio.h>
int main()
{
int x, y, z, k, V;
printf(" Enter the value of x = ");
scanf("%d", &x);
printf(" Enter the value of y = ");
scanf("%d", &y);
printf(" Enter the value of z = ");
scanf("%d", &z);
printf(" Enter the value of k = ");
scanf("%d", &k);
V = (((3 * x) / y) - z + k);
printf(" The value of V is %d", V);
return 0;
}

- // Write a program to check the whether a number is divisible by 97 or not by


using inputs supplied by the user.

#include <stdio.h>
#include <conio.h>
void main()
{
int a;
printf(" Enter the any number ");
scanf("%d",&a);

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

printf(" Divisibillity test returns is d", a%97);


getch();
}

 Conditional Instructions

- // Write a program to check the number is odd and even by using inputs supplied
by the user by using "If-else statement".

#include <stdio.h>
#include <conio.h>
void main()
{
int a;
printf(" Enter the any number ");
scanf("%d", &a);
if(a%2==0)
{
printf("%d is an Even number", a);
}
else
{
printf("%d is a Odd number", a);
}
getch();
}

- /* Write a program to check your age and you can drive or not ?
By using "If - else Statement" */

#include<stdio.h>
#include<conio.h>
void main()
{
int n;
printf(" Enter the Age ");
scanf("%d", &n);
if(n<=70 && n>=18)
{
printf(" You are above 18 and below 70, You can drive\n");
}
else
{

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

printf("You are below 18 and above 70, You cannot drive \n");
}
if(n==50)
{
printf(" half Century\n");
}
getch();
}

- /* Write a program to check your age and you can drive or not ?
By using "If - else statement" */

#include<stdio.h>
#include<conio.h>
void main()
{
int n;
int Emergency = 0;
Emergency= 1;
printf(" Enter the Age ");
scanf("%d", &n);
if(n<=70 && n>=18 || Emergency==1)
{
printf(" You are above 18 and below 70, You can drive\n");
}
else
{
printf("You are below 18 and above 70, You cannot drive \n");
}
if(n==50)
{
printf(" half Century\n");
}

- /* write a program to check 1, 2, 3 is your number yes or not ?


By using "else if clause" */

#include <stdio.h>
int main()
{
int num;
printf(" Enter the any number");
scanf("%d", &num);

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

if (num == 1)
{
printf(" Your number is 1\n");
}
else if (num == 2)
{
printf(" Your number is 2\n");
}
else if (num == 3)
{
printf(" Your number is 3\n");
}
else
{
printf(" Its not 1,2 or 3! ");
}
return 0;
}

- // Write a program to check the any number is greater than or Less than 5

#include <stdio.h>
int main()
{
int num;
printf(" Enter the number ");
scanf("%d", &num);

(num < 5) ? printf(" Number is less than 5 ") : printf(" Number is greater than
5 ");
return 0;
}

- // Write a program to enter the code and print the day of week.

#include <stdio.h>

int main()
{
int Day;
printf(" Enter the day code\n");
scanf("%d", &Day);

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

switch (Day)
{
case 1:
printf(" First day is Sunday\n");
break;

case 2:
printf(" Second day is Monday\n");
break;

case 3:
printf(" Third day is Tuesday\n");
break;

case 4:
printf(" Forth day is Wednesday\n");
break;

case 5:
printf(" Fifth day is Thruesday\n");
break;

case 6:
printf(" Sixth day is Friday\n");
break;

case 7:
printf(" Seventh day is Saturday\n");
break;

default:
printf(" Invalid Day \n");
}
return 0;
}

- // Write a program to enter the percentage and print the your grade.

#include <stdio.h>
int main()
{
int Percentage;
printf(" Enter your percentage:\n");

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

scanf("%d", &Percentage);

if (Percentage >= 90 && Percentage <= 100)


{
printf(" Your Grade is A+");
}
else if (Percentage >= 80 && Percentage <= 90)
{
printf(" Your Grade is A");
}
else if (Percentage >= 70 && Percentage <= 80)
{
printf(" Your Grade is B+");
}
else if (Percentage >= 60 && Percentage <= 70)
{
printf(" Your Grade is B");
}
else if (Percentage >= 50 && Percentage <= 60)
{
printf(" Your Grade is C+");
}
else if (Percentage >= 40 && Percentage <= 50)
{
printf(" Your Grade is C");
}
else if (Percentage >= 35 && Percentage <= 40)
{
printf(" Your Grade is D");
}
else
{
printf(" You are Fail ");
}
return 0;
}

- // Write a program to enter the six (6) subject marks then check you are failed or
passed ?

#include <stdio.h>

int main()

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

{
int Physics, Chemistry, Math, Computer, English, Nepali;
float total;
printf("Enter the Physics Marks \n");
scanf("%d", &Physics);
printf("Enter the Chemistry Marks \n");
scanf("%d", &Chemistry);
printf(" Enter the Math Marks \n");
scanf("%d", &Math);
printf("Enter the Computer Marks\n");
scanf("%d", &Computer);
printf(" Enter the English Marks \n");
scanf("%d", &English);
printf("Enter the Nepali Marks\n");
scanf("%d", &Nepali);
total = ((Physics + Chemistry + Math + Computer + English + Nepali) / 6);
if ((total < 35) || Physics < 35 || Chemistry < 35 || Math < 35 || Computer < 35
|| English < 35 || Nepali < 35)
{
printf("Total percentage is %f and you are Failed\n", total);
}
else
{
printf("Total percentage is %f and you are Passed\n ", total);
}
return 0;
}

- // Calculate income tax paid by an employee to the goverment as per the salary
mention below,

Income Salary Tax


2.5L – 50L 5%
50L – 10L 20%
Above 10L 30%

#include <stdio.h>
int main()
{
float Tax = 0, Income;

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

printf(" Enter your Yearly Income ");


scanf("%f", &Income);

if (Income >= 250000 && Income <= 500000)


{
Tax = Tax + 0.05 * (Income - 250000);
}
if (Income >= 500000 && Income <= 1000000)
{
Tax = Tax + 0.20 * (Income - 500000);
}
if (Income >= 1000000)
{
Tax = Tax + 0.30 * (Income - 1000000);
}
printf(" Your Net Income Tax to be paid is %f", Tax);
return 0;
}

- // Write a program to find the Greatest of four numbers entered by the user

#include<stdio.h>
void main()
{
int a,b,c,d;
printf(" Enter( the first number\n");
scanf("%d", &a);
printf(" Enter( the second number\n");
scanf("%d", &b);
printf(" Enter( the third number\n");
scanf("%d", &c);
printf(" Enter( the forth number\n");
scanf("%d", &d);
if(a>b && a>d)
{
printf(" %d is the Greatest Number ", a);
}
else if(b>c && b>d )
{
printf(" %d is the Greatest Number ", b);
}
else if(c>a && c>d)
{

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

printf(" %d is the Greatest Number ", c);


}
else
{
printf(" %d is the Greatest Number ", d);
}
}

- // Write a program to determine wheather a character entered by the useris


LowerCase.

#include <stdio.h>
void main()
{
// 97-122 = a-z ( LowerCase )
char ch;
printf(" Enter the Character \n");
scanf("%c", &ch);

if (ch >= 97 && ch <= 122)


{
printf(" It is a LowerCase");
}
else
{
printf(" It is not a LowerCase");
}
}

 Loop Contro Instructions

- // Write a program to print first n natural numbers by using "while loop".

#include <stdio.h>
void main()
{
int a;
printf("Enter the number ");
scanf("%d", &a);

while(a<=1000)
{
printf("%d\n",a);

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

a++;
}
}

// Write a program to print first n natural numbers by using "while loop".

#include <stdio.h>
void main()
{
int i = 0;
while (i <= 50)
{
if (i >= 10)
{
printf(" The value of i is %d\n", i);
}
i++;
}
}

- // Write a program to print first 10 natural numbers by using "do-while loop".

#include <stdio.h>
void main()
{
int i = 0;
do
{
printf(" The value of i is %d\n", i);
i++;
} while (i <= 10);
}

- // Write a program to print first n natural numbers by using "do-while loop".

#include <stdio.h>
void main()
{
int i = 0;
int n;
printf(" Enter any number: ");
scanf("%d", &n);
do

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

{
printf(" The value of i is %d\n", i+1);
i++;
} while (i < n);
}

- // Write a program to print first n natural numbers by using "for loop", Increment
Operator.

#include<stdio.h>
void main()
{
int a,n;
printf(" Enter any number :");
scanf("%d", &n);
for(a=0;a<=n;a++)
{
printf(" The value of a is %d\n", a);
}
}

- // Write a program to print first n natural numbers by using "for loop",


Decrement Operators

#include<stdio.h>
void main()
{
int a,n;
printf(" Enter the any number :");
scanf("%d", &n);
for(a=n;a;a--)
{
printf("The value of a is %d\n", a);
}
}

- // Write a program to print any number by using "continue statement"

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

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

int i=0,n;
printf(" Enter the any number ");
scanf(" %d", &n);
while(i<n)
{
i++;
if(i!=n)
{
continue;
}
else
{
printf("The value is %d", i);
}
}
}

- // Write a program to print multiplication table of any number by using "For


Loop".

#include <stdio.h>
void main()
{
int i,n;
printf(" Enter the any number ");
scanf("%d", &n);
for(i=1;i<=10;i++)
{
printf("%d X %d = %d\n",n,i,10*i);
}
}

- // write a program to sum of first ten(10) natural numberby using "While Loop".

#include <stdio.h>
void main()
{
int n=0,sum,a;
printf("How many numbers are added ? : ");
scanf("%d", &a);
while (n <= a)
{
sum +=n;

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

n++;
}
printf(" The sum of total number is %d\n", sum);
}

- // write a program to sum of first ten(10) natural numberby using "For Loop".

#include<stdio.h>
void main()
{
int sum=0,a,n;
printf(" How many numbers is added : ");
scanf("%d",&n);
for(a=1;a<=n;a++)
{
sum +=a;
}
printf(" The sum of the total number is %d", sum);
}

- // write a program to sum of first ten(10) natural numberby using "do-While


Loop".

#include <stdio.h>
void main()
{
int a = 0, n, sum;
printf(" How many number is added ? ");
scanf("%d", &n);
do
{
sum += a;
a++;
} while (a <= n);
{
printf(" The sum of the total number is = %d", sum);
}
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

- // Write a program to calculate the Factorial of a given number By using "For


Loop"

#include<stdio.h>
void main()
{
int a=0,n,factorial=1;
printf(" Enter the any number ");
scanf(" %d",&n);

for(a=1;a<=n;a++)
{
factorial = factorial * a;
}
{
printf(" The Factorial is given by the number %d is %d\n", n,factorial);
}
}

- // Write a program to calculate the Factorial of a given number By using "While


Loop"

#include <stdio.h>
void main()
{
int a = 1, n, factorial=1;
printf(" Enter any number ");
scanf("%d", &n);
while (a <= n)
{
factorial = factorial * a;
a++;
}
{
printf(" The Factorial is given by the number %d is %d\n", n,factorial);
}
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

// Write a program to check the wheather the given number is rime or not by
using "Loops"

#include<stdio.h>

void main()
{
int a,n;
printf(" Enter the any number ");
scanf("%d", &n);
for(a=2;a<=n;a++)
{
if(n%a==0)
break;
}
if(a==n)
{
printf(" This is a Prime number ");
}
else
{
printf(" This is not a prime number ");
}
}

 Function

- // Write a program to print the 'Hello! I am Nagendra Dash' by using function.

#include<stdio.h>
void display(); // Function Prototype
void main()
{
int a;
printf(" Initializing dispaly function \n");
display(); // Function Call
printf(" Display function finished its work.\n");
}

void display() // Function Definiction


{
printf(" Hello! I am Nagendra Dash \n");
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

- // Write a program to print Good Morning / Good Afternoon / Good Night by


using "Function"

#include<stdio.h>
void goodmorning();
void goodafternoon();
void goodnight();
void main()
{
goodmorning();
goodafternoon();
goodnight();
}

void goodmorning()
{
printf(" Good Morning Nagendra\n");
}
void goodafternoon()
{
printf(" Good AfterNoon Nagendra\n");
}
void goodnight()
{
printf(" Good Night Nagendra\n");
}

- /* Write a program to print Good Morning / Good Afternoon / Good Night by


using "Function" and only one function calling. */

#include <stdio.h>
#include <stdio.h>
void goodmorning();
void goodafternoon();
void goodnight();
void main()
{
goodmorning(); // Only one function call
}

void goodmorning()
{
printf(" Good Morning Nagendra\n");

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

goodafternoon();
}

void goodafternoon()
{
printf(" Good AfterNoon Nagendra\n");
goodnight();
}

void goodnight()
{
printf(" Good Night Nagendra\n");
}

- // Write a program to sum of any two number by using "Function".

#include<stdio.h>
int sum(int a,int b);
void main()
{
int a,b,s;
printf("Enter the first number\n");
scanf("%d",&a);
printf("Enter the second number\n");
scanf("%d",&b);
sum(a,b);
}

int sum(int a,int b)


{
int sum;
sum=a+b;
printf(" The sum of the number is %d", sum);

- // write a program to check the value of before change and after change by using
"Function"

#include<stdio.h>
void change(int b);
void main()
{

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

int a = 300;
printf("The value f a before change is %d\n",a);
change(a);
printf("The value f a after change is %d\n",a);
}

void change(int a)
{
a = 77;
}

 The output value of a = 300 do not change the value a = 77.

- // Write a program to calculate the area of a square with a side by using


"Libbrary Function".

#include<stdio.h>
void area(int a);
void main()
{
int a;
printf(" Enter the side");
scanf(" %d",&a);
area(a);
}

void area(int a)
{
int area;
area = a*a;
printf(" The area of the square is %d",area);
}

 Recursive Function

- // Write a program to calculate factorial by using "Recursive Function".

#include <stdio.h>
int factorial(int a);
void main()
{

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

int a;
printf(" Enter the any number ");
scanf("%d", &a);
printf(" The value of the given factorial number is %d", factorial(a));
}
int factorial(int a)
{
if (a == 0 || a == 1)
{
return 1;
}
else
{
return a * factorial(a - 1);
}
}

- // write a program to calculate the average of any three number by using


"Function".

#include<stdio.h>
void average(int a, int b, int c);
void main()
{
int a,b,c;
printf(" Enetr the first number ");
scanf("%d",&a);
printf(" Enter the second number ");
scanf("%d",&b);
printf(" Enter the third number");
scanf("%d",&c);
average(a,b,c);
}

void average(int a, int b, int c)


{
int average;
average = (a+b+c)/3;
printf(" The average value of the given number is %d ", average);
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

- // Write a program to convert Celcius Temperature into Farenheit Temerature by


using "Function".

#include <stdio.h>
void temperature(int c);
void main()
{
float c;
printf(" Enter the celcius temperature value ");
scanf("%f", &c);
temperature(c);
}

void temperature(int c)
{
float temperature;
temperature = ((c * (9.0/5.0)) + 32);
printf(" The value of the farenheit temperature is %f",temperature);
}

- /* Write a program to calculate the force of attraction of a body of a mass


exerted by the body by using "Function".*/

#include <stdio.h>
float force(float mass, float acceleration);
void main()
{
float mass, acceleration;
printf(" Enter the mass of the body ");
scanf("%f", &mass);
printf(" Enter the acceleration due to Gravity ");
scanf("%f", &acceleration);
force(mass, acceleration);
}

float force(float mass, float acceleration)


{
float force;
force = mass * acceleration;
printf("The value of the force in Newton %.3f", force);
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

- // Write a program to calculate the nth element of Fibonacci series by using


"Recursive Function".

#include<stdio.h>
int fibo ( int n);
void main()
{
int i,n;
printf(" Enter any number : ");
scanf("%d", &n);
for (i=1;i<=n;i++)
printf(" The fibo is %d\n", fibo(i));
}

int fibo (int n)


{
if(n==0)
{
return 0;
}
else if ( n == 1)
{
return 1;
}
else
{
return (fibo(n-1) + fibo (n-2));
}
}

- // Write a program to calculate the sum of first 'n' natural number by using
"Recusive Function".

#include<stdio.h>
int sum( int n);
void main()
{
int n;
printf(" Enter the any number ");
scanf("%d",&n);
printf(" \n The sum of the given number is %d", sum(n));
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

int sum( int n)


{
int a,sum=0;
for(a=1;a<=n;a++)
sum = sum + a;
return(sum);
}

- / * Write a program to print the following Pattern by using "Function"


*
***
*****
******* */

#include<stdio.h>
void printpattern(int n);
void main()
{
int n;
printf(" Enter any number ");
scanf("%d",&n);
printpattern(n);
}

void printpattern(int n)
{
int a;
if(n == 1)
{
printf("*\n");
return;
}
printpattern(n-1);
for(a=0;a<(2*n-1);a++)
{
printf("*");
}
printf("\n");
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Pointers

- /* Write a program to print the integer address of a, b, c, d and the integer value of
a, b, c, d by using “ pointer ” */.

#include <stdio.h>
void main()
{
int a;
int *b = &a;
int **c = &b;
int ***d = &c;
printf(" Enter any number ");
scanf("%d", &a);
printf("\n The value of A is %d\n", a);
printf(" The value of A is %d\n", *b);
printf(" The address of A is %u\n", &a);
printf(" The address of A is %u\n", b);
printf(" The value of B is %u\n", *(&b));
printf(" The address of B %u\n", &b);
printf(" The value of A is %u\n", *(&a));
printf("The address of Pointer B is %u\n", &c);
printf("The address of Pointer C is %u\n", &d);
printf(" The value of pointer to pointer C is %d", **c);
}

- // Write a program to calculate the sum of two number by using Pointer.

#include<stdio.h>
void main()
{
int a,b,*x,*y,sum;
printf(" Enter the first number ");
scanf("%d",&a);
printf(" Enter the second number ");
scanf("%d",&b);
x = &a;
y = &b;
sum = *x+*y;
printf(" The sum of the value of x and y is %d",sum);
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

- // Write a program to print the address of the variable.

#include<stdio.h>
void main()
{
int a;
int *b = &a;
printf(" The address of variable A is %u\n",&a);
printf(" The address of variable B is %u\n",&b);
}

- /* Write a program having a variable "i" then the print the address of "i", Pass this
variable to a function and print the address That will be the address are same?. */

#include<stdio.h>
void address( int a)
{
printf(" The address of A is %u\n",&a);
}
void main()
{
int i;
address(i);
printf(" The address of i is %u",&i);
}

- /* Write a program to calculate the sum and average of any two number by using
"function", then the use of pointer and print the values of sum and average in main */

#include <stdio.h>
void SumandAvg(int a, int b, int *sum, float *avg)
{
*sum = a + b;
*avg = (float)*sum / 2;
}
void main()
{
int m, n, sum;
float avg;
printf(" Enter the first number ");
scanf("%d", &m);
printf(" Enter the second number ");
scanf("%d", &n);

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

SumandAvg(m, n, &sum, &avg);


printf("The value of sum is %d\n", sum);
printf(" The value of average is %f\n", avg);
}

 Arrays

- // Write a program to print the five (5) subjects Marks for a student by using Arrays.

#include<stdio.h>
void main()
{
int Marks[5];
printf(" Enter the Mark of Physics : ");
scanf("%d", &Marks[0]);
printf(" Enter the Mark of Chemistry : ");
scanf("%d", &Marks[1]);
printf(" Enter the Mark of Math : ");
scanf("%d", &Marks[2]);
printf(" Enter the Mark of Computer : ");
scanf("%d", &Marks[3]);
printf(" Enter the Mark of English : ");
scanf("%d", &Marks[4]);
printf(" The value of All Subjects are :\n\n %d\n %d\n %d\n %d\n %d\n
",Marks[0],Marks[1],Marks[2],Marks[3],Marks[4]);
}

- // Write a program to print the Marks for five students by using " Arrays "

#include<stdio.h>
void main()
{
int Marks[5];
for(int i=0;i<5;i++)
{
printf(" Enter the value of the Marks for Students %d : ", i+1);
scanf(" %d",&Marks[i]);
}
for(int i=0;i<5;i++)
{
printf("The value of the Marks for Students %d is : %d\n", i+1,Marks[i]);
}
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

- // Write a program to print the value of a by using "Arrays" ( Initalization_Arrays).

#include <stdio.h>
void main()
{
int a[] = {23, 45, 56, 78};
printf(" The value of a is %d\n ", a[0]);
printf(" The value of a is %d\n ", a[1]);
printf(" The value of a is %d\n ", a[2]); // --------
printf(" The value of a is %d\n ", a[3]); // |
// |
float a[] = {23, 45, 56, 78}; // | >>>> int or float only one use
printf(" The value of a is %f\n ", a[0]); // |
printf(" The value of a is %f\n ", a[1]); // |
printf(" The value of a is %f\n ", a[2]); // --------
printf(" The value of a is %f\n ", a[3]);
}

- // Write a program to check the byte of the memory in computer .

#include<stdio.h>
void main()
{
int a ;
int*b = &a;
printf(" Enter the any number ");
scanf("%d", &a);
printf(" The address of b is %u\n", b);
b++;
b++;
printf(" The address of b is %u\n", b);
}

- // Write a program to print the Marks of the Students by using "Arrays with
Pointers"

#include <stdio.h>
void main()
{
int Marks[5];
int *ptr;
ptr = &Marks[0];

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

for (int i = 0; i < 5; i++)


{
printf(" Enter the value of the Marks for Students %d\n ", i + 1);
scanf(" %d", ptr);
ptr++;
}

for (int i = 0; i < 5; i++)


{
printf(" The value of the Marks for Students %d is : %d\n", i + 1, Marks[i]);
}
}

- /* Create an array of 10 numbers verify using pointer arithmetic that (ptr + 2)


points to the thirds elements where ptr is a pointer pointing to the
first element of the array */

#include<stdio.h>
void main()
{
int arr[10];
// int *ptr = &arr[0];
int *ptr = arr;
ptr = ptr+2;
if (ptr==&arr[2])
{
printf(" These Point to the same Locatin in Memory\n ");
}
else
{
printf(" These do not Point to the same Locatin in Memory\n ");
}
}

- // Write a program to create an array of 10 intergers and store multiplication


table of 5 in it.

#include<stdio.h>
void main()
{
int mul[10];
for( int i=0;i<10;i++)
{

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

mul[i] = 5*(i+1);
}

for( int i=0;i<10;i++)


{
printf(" 5 X %d = %d\n",i+1,mul[i]);
}
}

- /* Write a program to create an array of 10 integers and store multiplication


table of any number supplied by the user */

#include<stdio.h>
void main()
{
int mul[10],n;
printf("Enter the any number ");
scanf("%d",&n);
for( int i=0;i<10;i++)
{
mul[i] = n*(i+1);
}

for( int i=0;i<10;i++)


{
printf(" %d = %d\n",i+1,mul[i]);
}
}

- // Write a program containing a function which reverse the array passed to it.

#include<stdio.h>
void reverse(int *arr, int n)
{
int temp;
for(int i=0;i<(n/2);i++)
{
temp = arr[i];
arr[i] = arr[n-i-1];
arr[n-i-1] = temp;
}
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

void main()
{
int arr[] = {1,2,3,4,5,6,7,8,9,10};
reverse(arr,10);
for(int i=0;i<10;i++)
{
printf(" The value of %d elements is : %d\n", i, arr[i]);
}
}

- // Create an array of size 3 X 10 containing multiplication tables of the numbers


2, 7 and 9 respectively.

#include <stdio.h>
void main()
{
int mulTable[3][10];
{
for (int i = 0; i < 10; i++)
{
mulTable[0][i] = 2 * (i + 1);
}
for (int i = 0; i < 10; i++)
{
printf(" 2 X %d = %d\n", i + 1, mulTable[0][i]);
}
printf(" ************************************************\n\n");

for (int i = 0; i < 10; i++)


{
mulTable[0][i] = 7 * (i + 1);
}
for (int i = 0; i < 10; i++)
{
printf(" 7 X %d = %d\n", i + 1, mulTable[0][i]);
}
printf(" ************************************************\n\n");

for (int i = 0; i < 10; i++)


{
mulTable[0][i] = 9 * (i + 1);
}
for (int i = 0; i < 10; i++)
{
printf(" 9 X %d = %d\n", i + 1, mulTable[0][i]);
}
printf(" ************************************************\n\n");
}
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

- /* Create a three - Dimensional arrays and print the address of its elements in
increasing order. */

#include <stdio.h>
void main()
{
int arr[2][3][4];
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
for (int k = 0; k < 4; k++)
{
printf(" The address of arr[%d][%d][%d] is : %u\n", i, j, k, &arr[i][j][k]);
}
}
}
}

 Strings

- // Create a strings using " " and print its contant using a loop.

#include<stdio.h>
void main()
{
char str[] = "Nagendra"; or // char str[] = {'N','a','g','e','n','d','r','a','\0'};
char *ptr = str;
while(*ptr!='\0')
{
printf(" %c",*ptr);
ptr++;
}
}

- // Write a program to print any character ( single word ) supplied by the user by
using "Strings".

#include <stdio.h>
void main()
{
char str[10];
printf(" Enter any Character : ");

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

scanf("%s", str);
{
printf("Your Name is : %s", str);
}
}

- // Write a program to take string as an input from the user using %c and %s.
Conform that the strings are equal.

#include<stdio.h>
void main()
{
char str1[100];
char str2[100];
printf(" Enter first strings ");
scanf("%s", str1);
printf(" Enter second strings ");
scanf("%c", str2);
printf("The first string is %s",str1);
printf("The first string is %c",str1);
}

- // Write your own version of strlen function from <string.h>.

#include<stdio.h>
#include<string.h>
int strlen(char *str)
{
char *ptr = str;
int len = 0;
while(*ptr!='\0')
{
len++;
ptr++;
}
return len;
}
void main()
{
char str[] = "Nagendra";
int l = strlen(str);
printf(" The length of this strings is %d",l);
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

- /* Write a function slice() to slice a string . It should change the original string
such that it is now the slice string .Take m and n as the start and ending
position for slice.*/

#include<stdio.h>
void slice(char *str,int m, int n)
{
int i = 0;
while((m+i)<n)
{
str[i] = str[i+m];
i++;
}
str[i] = '\0';
}
void main()
{
char str[] = "Nagendra";
slice(str,1,8);
printf("%s",str);
}

- //Write a program to encrypt a string by adding 1 to the ascii value of its


character.

#include <stdio.h>
void encrypt(char *c)
{
char *ptr = c;
while (*ptr != '\0')
{
*ptr = *ptr + 1;
ptr++;
}
}
void main()
{
char c[] = "Nagendra";
encrypt(c);
printf("Encrypted string is : %s", c);
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

- // Write a program to decrypt the string encrypted using encrypted function in


above problem number

#include <stdio.h>
void decrypt(char *c)
{
char *ptr = c;
while (*ptr != '\0')
{
*ptr = *ptr - 1;
ptr++;
}
}
void main()
{
char c[] = "Obhfoesb"; // Obhfoesb is the output of the question number 85.c
decrypt(c);
printf("Decrypted string is : %s", c);
}

- // Write a program to count the occurrence of a given character in a string.

#include<stdio.h>
int occurance(char str[], char c)
{
char *ptr = str;
int count = 0;
while (*ptr!='\0')
{
if(*ptr==c)
{
count++;
}
ptr++;
}
return count;
}
void main()
{
char str[] = "Nagendra";
int count = occurance(str,'a');
printf(" The occurance is : %d", count);
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

 Structure

- // Write a program that takes Id, Salary, Name and print the record by using
"Structure ".

#include<stdio.h>
struct employee
{
int Id;
float Salary;
char Name[50];
};
void main()
{
struct employee a;
printf("Enter the Id : ");
scanf("%d",&[Link]);
printf("Enter the Salary : ");
scanf("%f",&[Link]);
printf("Enter the Name : ");
scanf("%s",[Link]);
printf("Id = %d\n Salary = %.3f\n Name = %s\n ", [Link],[Link],[Link]);
}

- // Write a program to store the details of three employees from user defined data
by using "Structure".

#include <stdio.h>
struct employee
{
int Id[10];
char Name[100];
float Salary[50];
};
void main()
{
struct employee Emp1, Emp2, Emp3;
printf("Enter the Id of Emp1 : ");
scanf("%d", &[Link]);
printf("Enter the Name of Emp1 : ");
scanf("%s", &[Link]);
printf("Enter the Salary of Emp1 : ");
scanf("%f", [Link]);

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

printf("\n\nEnter the Id of Emp2 : ");


scanf("%d", &[Link]);
printf("Enter the Name of Emp2 : ");
scanf("%s", &[Link]);
printf("Enter the Salary of Emp2 : ");
scanf("%f", [Link]);

printf("\n\nEnter the Id of Emp3 : ");


scanf("%d", &[Link]);
printf("Enter the Name of Emp3 : ");
scanf("%s", &[Link]);
printf("Enter the Salary of Emp3 : ");
scanf("%f", [Link]);
}

- // Write a program that takes Id,Name,Salary and print them by using


"Structure".

#include <stdio.h>
struct employee
{
int Id;
char Name[100];
float Salary;
};
void main()
{
struct employee Company = {100, "Nagendra", 500000};

printf("Id : %d\n", [Link]);


printf("Name : %s\n", [Link]);
printf("Salary : %.3f\n", [Link]);
}

- // Create a two dimensional vector using structure in c.

#include <stdio.h>
struct vector
{
int x;
int y;
};

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

void main()
{
struct vector v1, v2;
printf("Enter the value of v1.x : ");
scanf("%d", &v1.x);
printf("Enter the value of v1.y : ");
scanf("%d", &v1.y);
printf("Enter the value of v2.x : ");
scanf("%d", &v2.x);
printf("Enter the value of v2.y : ");
scanf("%d", &v2.y);
printf(" X dimensional is : %d\n Y dimensional is : %d\n", v1.x, v1.y);
printf(" X dimensional is : %d\n Y dimensional is : %d\n", v2.x, v2.y);
}

- // Write a function sumvector which returns the sum of two vectors to it .the
vectors must be two-Dimensional.

#include <stdio.h>
struct vector
{
int x;
int y;
};
struct vector sumvector(struct vector v1, struct vector v2)
{
struct vector sum;
sum.x = v1.x + v2.x;
sum.y = v1.y + v2.y;
return sum;
}
void main()
{
struct vector v1, v2, sum;
{
printf("Enter the value of v1.x : ");
scanf("%d", &v1.x);
printf("Enter the value of v1.y : ");
scanf("%d", &v1.y);
printf("Enter the value of v2.x : ");
scanf("%d", &v2.x);
printf("Enter the value of v2.y : ");
scanf("%d", &v2.y);

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

}
sum = sumvector(v1, v2);
printf(" The sum of X dimensional is : %d\n The sum of Y dimensional is :
%d\n", sum.x, sum.y);
}

- /* Create an array of 5 complex numbers created in problem 5 and display then


with the help of a display function . the value must be taken as an input
from the user. */

#include <stdio.h>
typedef struct complex
{
int real;
int Complex;
} comp;

void display(comp c)
{
printf("The value of the real parts is : %d\n", [Link]);
printf(" The value of the complex part is : %d\n", [Link]);
}
void main()
{
comp cnumbs[5];
for (int i = 0; i < 5; i++)
{
printf("Enter the real value %d numb\n", i + 1);
scanf("%d", &cnumbs[i].real);
printf("Enter the complex value %d numb\n", i + 1);
scanf("%d", &cnumbs[i].Complex);
}
for (int i = 0; i < 5; i++)
{
display(cnumbs[i]);
}
}

- // Write a program with a structure representing a complex numbers.

#include <stdio.h>
struct complex
{

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

int real;
int Complex;
};
void main()
{
struct complex cnumbs[5];
{
for (int i = 0; i < 5; i++)
{
printf("Enter the real value %d numb\n", i + 1);
scanf("%d", &cnumbs[i].real);
printf("Enter the complex value %d numb\n", i + 1);
scanf("%d", &cnumbs[i].Complex);
}
}
for (int i = 0; i < 5; i++)
{
printf("The value of the real parts is : %d\n", cnumbs[i].real);
printf(" The value of the compex part is : %d\n", cnumbs[i].Complex);
}
}

- // Write a program with a structure representing a complex numbers by using


typedef.

#include <stdio.h>
typedef struct complex
{
int real;
int Complex;
} comp;
void main()
{
comp cnumbs[5];
{
for (int i = 0; i < 5; i++)
{
printf("Enter the real value %d numb\n", i + 1);
scanf("%d", &cnumbs[i].real);
printf("Enter the complex value %d numb\n", i + 1);
scanf("%d", &cnumbs[i].Complex);
}
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

for (int i = 0; i < 5; i++)


{
printf("The value of the real parts is : %d\n", cnumbs[i].real);
printf(" The value of the compex part is : %d\n", cnumbs[i].Complex);
}
}

- // Create a structure representing a bank account of a customer. What fields did you use.

#include <stdio.h>
struct bankaccount
{
int Account_number;
char Name[100];
int balance;
int Opening_date;
char Address[100];
};
void main()
{
struct bankaccount a;
{
printf("Enter the Account anumber : ");
scanf("%d", &a.Account_number);
printf("Enter the Name : ");
scanf("%s", &[Link]);
printf("Enter the Balance : ");
scanf("%d", &[Link]);
printf("Enter the Opening Date : ");
scanf("%d",&a.Opening_date);
printf("Enter the Address : ");
scanf("%s",&[Link]);
}
printf("****************************************************\n\n");

printf("Account Number = %d\n", a.Account_number);


printf("Name = %s\n", [Link]);
printf("Balance = %d\n", [Link]);
printf("Opening Date = %d\n", a.Opening_date);
printf("Address = %s\n", [Link]);

printf("\n******************************************************");
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

// Write a structure capable of storing date .Write a function to compare those times.

#include<stdio.h>
struct time
{
int Hour;
int Minute;
int Second;
};

void display(struct time t)


{
printf("The time is : %d:%d:%d\n", [Link],[Link],[Link]);
}

int timecmp(struct time t1, struct time t2)


{
if([Link]>[Link])
{
return 1;
}
if ([Link]<[Link])
{
return -1;
}
if([Link]>[Link])
{
return 1;
}
if ([Link]<[Link])
{
return -1;
}
if([Link]>[Link])
{
return 1;
}
if ([Link]<[Link])
{
return -1;
}
return 0;
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

void main()
{
struct time t1,t2;
int a;
printf("Enter the Hours : ");
scanf("%d", &[Link]);
printf("Enter the Minutes : ");
scanf("%d", &[Link]);
printf("Enter the Secondrs : ");
scanf("%d", &[Link]);

printf("Enter the Hours : ");


scanf("%d", &[Link]);
printf("Enter the Minutes : ");
scanf("%d", &[Link]);
printf("Enter the Secondrs : ");
scanf("%d", &[Link]);
a = timecmp(t1, t2);
printf("Time Comparison function returns : %d", a);
}

- // Write a structure capable of storing date. Write a function to compare those dates.

#include<stdio.h>
struct date
{
int year;
int month;
int day;
};

void display( struct date d)


{
printf("The date is : %d/%d/%d\n",[Link],[Link],[Link] );
}

int datecmp( struct date d1, struct date d2)


{
if ([Link]>[Link])
{
return 1;
}
if([Link]<[Link])

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

{
return -1;
}
if ([Link]>[Link])
{
return 1;
}
if([Link]<[Link])
{
return -1;
}
if ([Link]>[Link])
{
return 1;
}
if([Link]<[Link])
{
return -1;
}
return 0;
}

void main()
{
struct date d1,d2;
int a;
printf("Enter the Year : ");
scanf("%d", &[Link]);
printf("Enter the month : ");
scanf("%d", &[Link]);
printf("Enter the day : ");
scanf("%d", &[Link]);

printf("Enter the Year : ");


scanf("%d", &[Link]);
printf("Enter the month : ");
scanf("%d", &[Link]);
printf("Enter the day : ");
scanf("%d", &[Link]);

a = datecmp(d1,d2);
printf("Time comparision function returns : %d ",a);
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

- // Write a structure capable of storing date .Write a function to compare those


times by using " Typedef keywords".

#include<stdio.h>
typedef struct time
{
int Hour;
int Minute;
int Second;
}time;

void display(time t)
{
printf("The time is : %d:%d:%d\n", [Link],[Link],[Link]);
}

int timecmp( time t1, time t2)


{
if([Link]>[Link])
{
return 1;
}
if ([Link]<[Link])
{
return -1;
}
if([Link]>[Link])
{
return 1;
}
if ([Link]<[Link])
{
return -1;
}
if([Link]>[Link])
{
return 1;
}
if ([Link]<[Link])
{
return -1;
}
return 0;

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

}
void main()
{
time t1,t2;
int a;
printf("Enter the Hours : ");
scanf("%d", &[Link]);
printf("Enter the Minutes : ");
scanf("%d", &[Link]);
printf("Enter the Secondrs : ");
scanf("%d", &[Link]);

printf("Enter the Hours : ");


scanf("%d", &[Link]);
printf("Enter the Minutes : ");
scanf("%d", &[Link]);
printf("Enter the Secondrs : ");
scanf("%d", &[Link]);
a = timecmp(t1, t2);
printf("Time Comparison function returns : %d", a);
}

- // Write a structure capable of storing date. Write a function to compare those


Timestamps.

#include<stdio.h>
struct timestamp
{
int Year;
int Month;
int Day;
int Hour;
int Minute;
int Second;
};

void display( struct timestamp d)


{
printf(" The timestamps is '%d/%d/%d','%d:%d:%d'\n", [Link], [Link],
[Link], [Link], [Link], [Link]);
}

int timecmp(struct timestamp t1, struct timestamp t2)

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

{
if ([Link]>[Link])
{
return 1;
}
if([Link]<[Link])
{
return -1;
}
if ([Link]>[Link])
{
return 1;
}
if([Link]<[Link])
{
return -1;
}
if ([Link]>[Link])
{
return 1;
}
if([Link]<[Link])
{
return -1;
}
if ([Link]>[Link])
{
return 1;
}
if([Link]<[Link])
{
return -1;
}
if ([Link]>[Link])
{
return 1;
}
if([Link]<[Link])
{
return -1;
}
if ([Link]>[Link])
{

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

return 1;
}
if([Link]<[Link])
{
return -1;
}
return 0;

}
void main()
{
struct timestamp t1,t2;
int a;
printf("Enter the Year : ");
scanf("%d", &[Link]);
printf("Enter the month : ");
scanf("%d", &[Link]);
printf("Enter the day : ");
scanf("%d", &[Link]);
printf("Enter the Hours : ");
scanf("%d", &[Link]);
printf("Enter the Minutes : ");
scanf("%d", &[Link]);
printf("Enter the Secondrs : ");
scanf("%d", &[Link]);

printf("Enter the Hours : ");


scanf("%d", &[Link]);
printf("Enter the Minutes : ");
scanf("%d", &[Link]);
printf("Enter the Secondrs : ");
scanf("%d", &[Link]);
printf("Enter the Year : ");
scanf("%d", &[Link]);
printf("Enter the month : ");
scanf("%d", &[Link]);
printf("Enter the day : ");
scanf("%d", &[Link]);
a = timecmp(t1,t2);
printf("Timestamp Comparision function returns : %d ", a);
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

- // Write a program to read two integers from '[Link]' file by using "FILE
Pointer".

#include<stdio.h>

void main()
{
FILE *ptr;
int num1;
int num2;
ptr = fopen("[Link]", " r");
fscanf(ptr,"%d", &num1);
fscanf(ptr,"%d", &num2);
fclose(ptr);
printf(" The value of num1 is %d\n",num1);
printf(" The value of num2 is %d\n",num2);
}

- /* Write a program number '105_file_pointer' modify the program above to


check wheather the file exit or not before opening the file. */

#include<stdio.h>
void main()
{
FILE *ptr;
int num1;
int num2;
ptr = fopen("[Link]","r");

if (ptr == NULL)
{
printf(" This file does not exit \n");
}
else
{
fscanf(ptr,"%d", &num1);
fscanf(ptr, "%d", &num2);
fclose(ptr);
printf(" The value of the num1 is %d\n",num1 );
printf(" The value of the num2 is %d\n", num2);
}
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

- // Write a program to read the Character of file in '[Link]'.

[Link] file  This is my book.

#include<stdio.h>
void main()
{
FILE *ptr;
ptr = fopen("[Link]","r");
printf(" The valu of my character is %c\n", fgetc(ptr));
printf(" The valu of my character is %c\n", fgetc(ptr));
printf(" The valu of my character is %c\n", fgetc(ptr));
printf(" The valu of my character is %c\n", fgetc(ptr));
printf(" The valu of my character is %c\n", fgetc(ptr));
printf(" The valu of my character is %c\n", fgetc(ptr));
printf(" The valu of my character is %c\n", fgetc(ptr));
fclose(ptr);
}

- // Write a program to writing the character of the file in "[Link]".

[Link] file  This is my book.

#include<stdio.h>
void main()
{
FILE *ptr;
ptr = fopen("[Link]","w");
fputc('N', ptr);
fclose(ptr);
}

- // Write a program to read the all character of the file in "[Link]".

#include<stdio.h>
void main()
{
FILE *ptr;
char ch;
ptr = fopen("[Link]","r");
ch = fgetc(ptr);
while(ch!=EOF)
{

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

printf("%c",ch);
ch = fgetc(ptr);
}
}

- // Write a program to read three intergers from a file .

[Link] file  23 45 67

#include <stdio.h>
void main()
{
int a, b, c;
FILE *ptr;
ptr = fopen("[Link]", "r");
fscanf(ptr, "%d", &a);
fscanf(ptr, "%d", &b);
fscanf(ptr, "%d", &c);
printf(" The value of A : %d\n", a);
printf(" The value of B : %d\n", b);
printf(" The value of C : %d\n", c);
}

- /* Write a program to generate the multiplication table of a given number in


text format. Make sure that the file readable and well format. */

#include<stdio.h>
void main()
{
FILE *ptr;
int n;
printf(" Enter the any number ");
scanf(" %d", &n);
ptr = fopen("[Link]","w");
for( int a=0;a<10;a++)
{
fprintf(ptr, "%d X %d = %d\n",n,a+1,n*(a+1));
}
fclose(ptr);
printf("Successfully generated table of %d to [Link]\n",n);
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

- // Write a program to read a text file character by character and write its content
twice in a seperate file .

#include<stdio.h>
void main()
{
FILE *ptr1;
FILE *ptr2;
ptr1 = fopen("[Link]","r");
ptr2 = fopen("[Link]","w");
char c = fgetc(ptr1);
while (c!=EOF)
{
fputc(c,ptr2);
fputc(c,ptr2);
c = fgetc(ptr1);
}
fclose(ptr1);
fclose(ptr2);
}

- /* Take name and salary of two employees as input from the user and write
them to a text file in the following formate

name1,3300
name2,7700 */

#include <stdio.h>
void main()
{
FILE *ptr;

char Name1[100];
int Salary1;

char Name2[100];
int Salary2;

printf(" Enter the number : ");


scanf(" %s", &Name1);
printf(" Enter the Salary : ");
scanf("%d", &Salary1);

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

printf(" Enter the number : ");


scanf(" %s", &Name2);
printf(" Enter the Salary : ");
scanf("%d", &Salary2);

ptr = fopen("[Link]", "w");


{
fprintf(ptr, "%s,%d\n",Name1,Salary1);
fprintf(ptr, "%s,%d",Name2,Salary2);
}
fclose(ptr);
}

- // write a program to modify a file containing an integer to a double its value.

#include <stdio.h>
#include<conio.h>
int main()
{
int num;
FILE *ptr1;
FILE *ptr2;
ptr1 = fopen("[Link]", "r");
ptr2 = fopen("[Link]", "w");
// if(ptr1 == NULL)
// {
// printf("Error opening file\n");
// return -1;
// }

// if(ptr2 == NULL)
// {
// printf("Error creating file\n");
// return -1;
// }
while (fscanf(ptr1, "%d ", &num)==1)
{
fprintf(ptr2, " %d", num * 2);
}
fclose(ptr1);
fclose(ptr2);
printf("Doubled integers written to the [Link] file .\n");
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])
lOMoARcPSD|61952182

- //Write a program that takes Roll_No, Name, Address and Date of Birthand utput
the information on screen.

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

struct date
{
int year;
int month;
int day;
};

struct student
{
int Roll_No;
char Name[100];
char Address[100];
struct date d;
};

void main()
{
struct student a;
printf(" Enter The Roll No. : ");
scanf("%d", &a.Roll_No);
printf(" Enter the Name : ");
scanf("%s", &[Link]);
printf(" ENter the Address : ");
scanf("%s", &[Link]);
printf(" Enter the Date of Birth YYYY/MM/DD : ");
scanf("%d %d %d", &[Link], &[Link], &[Link]);

printf("\n*************************************************\n\n");

printf("Id = %d\n", a.Roll_No);


printf("Name = %s\n", [Link]);
printf("Address = %s\n", [Link]);
printf("Date of Birth = %d/%d/%d", [Link], [Link], [Link]);

printf("\n\n***********************************************\n\n");
}

Nagendra Das
Downloaded by Aayush Mandal (mandalaayush069@[Link])

You might also like