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

CS1CRT02 Methodology of Programming and C Language (Core)

This document discusses the syllabus for the course "CS1CRT02 Methodology of Programming and C Language" which covers the following topics: 1. Introduction to programming concepts like data processing, memory, inputs/outputs and the importance of programming languages. It also discusses low-level and high-level languages. 2. Language translators like assemblers, compilers, and interpreters which are used to convert programs into machine-readable format. 3. Additional topics covered include C programming fundamentals like variables, data types, operators, control structures and input/output functions. 4. The syllabus also mentions pointers, functions, recursion, structures and dynamic memory allocation in C.

Uploaded by

Eugin Lopez
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
83 views

CS1CRT02 Methodology of Programming and C Language (Core)

This document discusses the syllabus for the course "CS1CRT02 Methodology of Programming and C Language" which covers the following topics: 1. Introduction to programming concepts like data processing, memory, inputs/outputs and the importance of programming languages. It also discusses low-level and high-level languages. 2. Language translators like assemblers, compilers, and interpreters which are used to convert programs into machine-readable format. 3. Additional topics covered include C programming fundamentals like variables, data types, operators, control structures and input/output functions. 4. The syllabus also mentions pointers, functions, recursion, structures and dynamic memory allocation in C.

Uploaded by

Eugin Lopez
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

1

CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

CS1CRT02 (B.Sc. Computer Science) Array, initialization, array terminology,


CA1CRT02 (BCA) characteristics of an array, one dimensional
CA1CRT02 (B.Sc. CA Triple Main) array and operations, two dimensional arrays
IT1CRT03 (B.Sc. IT) and operations. Strings and standard
functions, Pointers, Features of Pointer, Pointer
Methodology of Programming and address, Pointer declaration, void wild
and constant pointers, Arithmetic operations with
C Language pointers, pointer and arrays, pointers and two
dimensional arrays.
Semester I
Module 5
MG University, Kottayam Basics of a function, function definition, return
statement, Types of functions, call by value
Syllabus and reference. Recursion -Types of recursion,
Module 1 Rules for recursive function, direct and indirect
Introduction to programming, Classification of recursion, recursion vs iterations, Advantages
computer languages, Language translators and disadvantages of recursion. Storage class,
(Assembler, Compiler, Interpreter), Linker, Structure and union, Features of structures,
Characteristics of a good programming Declaration and initialization of structures,
language, Factors for selecting a language, array of structures, Pointer to structure,
Subprogram, Purpose of program planning, structure and functions, typedef, bit fields ,
Algorithm, Flowchart, Pseudo code, Control enumerated data types, Union, Dynamic
structures (sequence, selection, Iteration), memory allocation, memory models, memory
Testing and debugging allocation functions.

Module 2 Book of Study:


C Character Set, Delimiters, Types of Tokens, C 1. Ashok Kamthane - Programming in C, Third
Keywords, Identifiers, Constants, Variables, Edition, Pearson Education
Rules for defining variables, Data types, C data 2. P K Sinha & Priti Sinha - Computer
types, Declaring and initialization of variables, Fundamentals, Fourth Edition, BPB
Type modifiers, Type conversion, Operators Publications.
and Expressions- Properties of operators,
Priority of operators, Comma and conditional Reference:
operator, Arithmetic operators, Relational 1. E. Balaguruswamy -Programming in ANSI C
operators, Assignment operators and ,Seventh Edition, McGraw Hill Education
expressions, Logical Operators, Bitwise 2. Byron Gotfried - Programming with C,
operators Second Edition, Schaums Outline series.
McGraw Hill
Module 3
Input and Output in C – Formatted functions,
unformatted functions, commonly used library
functions, Decision Statements If, if-else,
nested if-else, if-else-if ladder, break, continue,
go-to, switch, nested switch, switch case and
nested if. Loop control- for loops, nested for
loops, while loops, do while loop.

Module 4

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


2
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

Module 1 Low Level Language


INTRODUCTION TO PROGRAMMING Programs or set of instructions written in the
Computer is an electronic device that accepts form of binary (1s and 0s) are known as Low
data, process those data, store the data and Level Language or machine language.
results the output. Data are accepted by This is the only language that can be
keyboard or any other input devices. Data are understood or interpreted by a computer.
processed by means of central processing unit
or simply CPU. Some kind of memories are High Level Language
used to store the data and results. And these Programs or set of instructions that are written
results as delivered to the output or visualized in structured languages such as English are
by monitors. known as High Level Languages. High level
languages are not directly interpreted or
Computers can perform its operation by the understood by a computer. Examples: C,
means of programs. Programs are set or group FORTRAN, COBOL, BASIC etc.
of instructions that are loaded into memory.
Instructions are set of commands that what a LANGUAGE TRANSLATORS
computer to do or perform. Art of writing or
creating programs are known as
programming.

Computer can communicate with the users by


means of languages. Computers can only There are some special programs are required
understand its own language known as to make the computer understand what a
machine language. Machine language consist computer to do. Such language converting
of 1s and 0s. Or simply known as binary. programs are known as Language Translator.
Machine language is the lowest level language The word translator means decoder or
because computer knows only the patterns or interpreter. The process is known as Language
combinations of 1s and 0s. translation. Some special programs designed
and create to do the translation job for a
In order to write or create programs in binary computer are as follows.
is complicated and confused. Because change
in 0 as 1 or 1 as 0 will create serious errors on 1. Assembler
the result. So the experts designed languages 2. Compiler
to communicate with the computers known as 3. Interpreter
high level languages. This will avoid
complication and confusion since high level Assembler
languages are written in English like language.
That’s why C is called high level language since
it has a structure like English. English words are
used in C Programming. It is very easy to learn
C programming.
Assembler is a special program to convert
CLASSIFICATION OF COMPUTER assembly language into machine language.
LANGUAGES Assembly language means that language
Computer Languages are classified into two. written in mnemonics. It is also seemed to be
They are written in English-like words, but in the form
1. Low Level Language of abbreviations.
2. High Level Language.

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


3
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

Example, a program written in mnemonics or Interpreter


assembly code is shown.
MVI A, 6AH
MOV B, A
ADD B
STA 5000H
Interpreter is also a program that converts
The program shown above is an assembly high level language to machine language line
program for Intel 8085 Microprocessor by line. On other hand, it could be said that the
systems. MVI means “Move Immediately”. interpreter is “compiler online”. Because as
That means 6AH is a hexadecimal number that soon as a line of statement is completed in the
should copy or move immediately to register interpreter platform, it will check the syntax
A in the microprocessor. MOV means “to and semantics of the statement at the end of
move” a data from source register to the line and compile it. If there exist any
destination register. Here the content 6A H of mistake in the statement it will report error to
the register A will be copied to Register B. ADD the programmer.
B means content of Register B will be “added”
to the Register A. STA means “store the For Example, Microsoft Visual Basic IDE, while
content of the register A” to the memory coding, report error, when the syntax is wrong.
location 5000H. Register is a memory location So the programmer could be able to correct
inside the microprocessor for temporary the syntax errors by the end of the line of the
storage of data. statement itself.

So the assembly language consist of Linker


mnemonics or assembly codes such as MVI,
MOV, ADD and STA are English-like words but
abbreviations in assembly programming. So
an assembly programmer can easily identify
the logic and nature of the program to get the
output.

Those programs are interpreted or understood


by an assembler. It will convert assembly
language to its own machine language.
We know that compilers are capable for
Compiler converting high level languages to machine
languages. Moreover additional programs are
also required to compile more complex user
programs. In order to compile complex
programs created by the user it may need to
Another special program are designed and link some library files in the computer to get
developed to convert high level language to the desired output. Some additional programs
machine languages are known as compiler. are required to link library files. Such programs
The word compile means to “convert”. High are known as linkers. Linkers are nothing but
level languages such as C, FORTRAN, COBOL, the programs run along with the compiler for
BASIC etc. are to be compiled to machine linking library files so as to get the final
language. machine code.

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


4
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

CHARACTERISTICS OF A GOOD Compactness


PROGRAMMING LANGUAGE In a good language, programmers should be
There are some popular and powerful high- able to express the intended operations
level programming languages. There are concisely without losing readability.
several characteristics believed to be Programmers generally do not like a verbose
important for making it good. language because they need to write too
much.
Naturalness
A good language should be natural for the Locality
application area for which it is designed. That A good language should be such that while
is, it should provide appropriate operators, writing a program, a programmer need not
data structures, control structures and a jump around the visually as the text of a
natural syntax to facilitate programmers to program is prepared. This allows the
code their problems easily and efficiently. programmer to concentrate almost solely on
FORTRAN and COBOL are good examples of the part of the program around the statement
languages possessing high degree of currently being worked with. COBOL and to
naturalness in scientific and business some extent C and Pascal lack locality because
application areas, respectively. data definitions are separated from processing
statements, perhaps by many pages of code,
Abstraction or have to appear before any processing
Abstraction means ability to define and then statement in the function/procedure.
use complicated structures or operations in
ways that allow many of the details to be Extensibility
ignored. The degree of abstraction allowed by A good language should also allow extensions
a language directly affects its ease of through a simply, natural and neat mechanism.
programming. Almost all languages provide subprogram
definition mechanisms for the purpose, but
Efficiency some languages are weak in this aspect.
Programs written in a good language are
translated into machine code efficiently, are Suitability to its Environment
executed and require relatively less space in Depending upon the type of application for
memory. That is, a good programming which a programming language has been
language is supported with a good language designed, the language must also be made
translator (a compiler or an interpreter) that suitable to its environment. For Example, a
gives due consideration to space and time language designed for a real-time applications
efficiency. must be interactive in nature. On the other
hand, languages used for data-processing jobs
Structured Programming Support like payroll, stores accounting etc. may be
A good language should have necessary designed to operative in batch mode.
features to allow programmers to write their
programs based on the concepts of structured FACTORS FOR SELECTING A LANGUAGE
programming .This property greatly affects the The factors we select or choose a language is
ease with which a program may be written, described as follows.
tested and maintained. Moreover, it forces a
programmer to look at a problem in a logical Popularity
way so that fewer errors are created while This is a very important one. You are more
writing a program for the problem. likely to find people to collaborate with if you

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


5
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

use a popular language. You are also more menu, and can be executed just like a
likely to find reference material and other help. regular program.
• Internal — they are contained inside the
Language-domain match. program itself, so that they can be called by
Select a language that matches your problem the program whenever needed.
domain. You can do this by looking at what
other people in your field are using. Look at PURPOSE OF PROGRAM PLANNING
the code that solves problems that you are Before writing a program, one should know
working on. what is going to be programmed. Problems
are solved using computer programs. A
Availability of libraries Programmer should analyze the problem very
If there's a library that solves your problem well from the beginning to end. He should
well, then it will be helpful to choose the have an idea and design the problem before it
language for your need. implement. Also imagination of the result
should be predicted. Else he would get
Efficiency unpredicted and undesirable output.
Languages compilers should be efficient. Look
at the efficiency of compilers or interpreters Program Life Cycle
for your language. Be aware that interpreted When we want to develop a program using
code will run properly. any programming language, we follow a
sequence of steps. These steps are called
Expressiveness phases in program development. The program
The number of lines of code you create per development life cycle is a set of steps or
hour is not a strong function of language, so phases that are used to develop a program in
favor languages that are expressive or any programming language.
powerful.
Generally, program development life cycle
Tool Support contains 6 phases, they are as follows:
Popularity usually buys tool support. Some
languages are easier to write tools. If you are a • Problem Definition
tool-oriented user, choose a language with • Problem Analysis
good tool support. • Algorithm Development
• Coding & Documentation
SUBPROGRAM • Testing & Debugging
A subprogram is a program called by another • Maintenance
program to perform a particular task or
function for the program. When a task needs
to be performed multiple times, you can make
it into a separate section. The complete
program is thus made up of multiple smaller,
independent subprograms that work together
with the main program.

There are two different general types of


subprograms available:
• External — they exist as stand-alone
programs that are listed in the program

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


6
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

Problem Definition end user. If the user encounters any problem


In this phase, we define the problem statement or wants any enhancement, then we need to
and we decide the boundaries of the problem. repeat all the phases from the starting, so that
In this phase we need to understand the the encountered problem is solved or
problem statement, what is our requirement, enhancement is added.
what should be the output of the problem
solution. These are defined in this first phase There are some basic tools for programming
of the program development life cycle. before the programmer start to implement or
coding the programs. The basic tools are as
Problem Analysis follows.
In phase 2, we determine the requirements like
variables, functions, etc. to solve the problem. Algorithm
That means we gather the required resources Any problem can be ever followed by
to solve the problem defined in the problem sequence of steps or procedures. Those
definition phase. We also determine the sequence of steps or procedures are termed as
bounds of the solution. algorithm.
Algorithm Development
During this phase, we develop a step by step Example: Recipe for making a cup of Tea.
procedure to solve the problem using the Here the problem is to make a cup of tea to
specification given in the previous phase. This drink. Analyze the problem very well and check
phase is very important for program for the availability of requirements. For making
development. That means we write the tea; water, milk, tea powder, sugar sauce pan,
solution in step by step statements. filter etc. are required.

Coding & Documentation Algorithm for making a cup of Tea


This phase uses a programming language to 1. START stove
write or implement actual programming 2. Take ½ cup WATER
instructions for the steps defined in the 3. Take ½ cup MILK
previous phase. In this phase, we construct 4. Pour both into SAUCE PAN.
actual program. That means we write the 5. BOIL it
program to solve the given problem using 6. Put ½ tea-spoon of TEA POWDER into
programming languages like C, C++, Java etc. boiled material.
7. Mix 1 tea-spoon of SUGAR on it.
Testing & Debugging 8. STIR it well
During this phase, we check whether the code 9. FILTER tea to a cup
written in previous step is solving the specified 10. STOP stove
problem or not. That means we test the
program whether it is solving the problem for The example shows above is, just to illustrate
various input data values or not. We also test and to understand what the algorithm is.
that whether it is providing the desired output
or not. For anything we want to make, we should
follow some steps. These steps are known as
Maintenance algorithm.
During this phase, the program is actively used
by the users. If any enhancements found in this Similarly, problems are solved by writing
phase, all the phases are to be repeated again sequence of statements or steps in
to make the enhancements. That means in this chronological order. The way of writing
phase, the solution (program) is used by the sequence of statements or steps in

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


7
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

chronological order to solve a problem is or can be written in a language that we feel


known as an algorithm. like.

Example: Sum of two numbers Flowchart


1. START Program The pictorial or graphical representation of
2. READ First Number flow of a program is known as flowchart. If the
3. READ Second Number algorithms or programs are displayed in the
4. ADD First Number with Second form of a picture then it will be more
Number noticeable and recognizable. Only thing what
5. ASSIGN to SUM we need to know some specific shapes to
6. DISPLAY SUM represent each processes or actions. The
7. END Program fundamental shapes and descriptions using in
flowcharts are as follows.
The problem above is to monitor or display the
sum of two numbers are illustrated in the form
of an algorithm. We can use comfortable
languages or its abbreviations to implement
an algorithm as follows.
Rhombus: For decision making and branching
1. START
the flow of execution.
2. READ NUM1
Rectangle: For processing and assigning
3. READ NUM2
variables.
4. SUMNUM1+NUM2
Parallelogram: Accessing inputs and printing
5. PRINT SUM
outputs.
6. END
Rectangle with Curved Edges: Start/Begin or
Stop/End of the program execution.
Algorithm should be
Circle: Connectors to continue the flow of
1. Simple
execution.
2. Short
Arrow: Represents the direction of Flow of
3. Understandable
execution.
4. Keep proper sequence
5. maintain ethical logic
Example: Flowchart for Sum of two
6. Result oriented.
numbers

Another Example: Largest of Two Numbers.

1. Start
2. Read Num1
3. Read Num2
4. Is (Num1>Num2)?
5. Yes: Print Num1 is Large, GOTO Step 7
6. Else: Print Num2 is Large
7. End

It is possible to switch from a step to another


without violating the logic of the program.
Algorithms are written in English like language

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


8
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

in any way necessary to deal with a given


problem. The control structures are:
Example: Flowchart to find Largest of Two 1. Sequence
Numbers. 2. Selection
3. Iteration

Sequence

Pseudo code
The term pseudo means false. The false codes The sequence structure simply executes a
used to represent the flow of execution of a sequence of statements in the order in which
program is known as pseudo codes. Usually they occur.
programmers use pseudo codes for rough
work on their problem solving. Most probably, Selection
they use pen and papers for their rough
programming work. They should not bother
syntax or semantics of any high-level
programming languages.

Pseudo code is an informal high-level


description of the operating principle of a
computer program or any other algorithm. It
uses the structural conventions of a normal
programming language but is intended for
human reading rather than machine reading. The selection structure tests a condition, then
executes one sequence of statements instead
Example: Pseudo Code to find Largest of of another, depending on whether the
Two Numbers. condition is true or false. A condition is any
variable or expression that returns a Boolean
Rd N1, N2 value (TRUE or FALSE).
N1>N2?
Y: Prn N1 Iteration
N: Prn N2

CONTROL STRUCTURES
A control structure is a block of programming
that analyzes variables and chooses a direction
in which to go based on given parameters. Any
computer program can be written using the
basic control structures. They can be combined

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


9
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

Know more about C


The iteration structure executes a sequence of • C was invented to write an operating
statements repeatedly if a condition holds system called UNIX.
true. • C is a successor of B language which was
introduced around the early 1970s.
TESTING AND DEBUGGING • The language was formalized in 1988 by
Testing is meant to find defects or errors in the the American National Standard Institute
code, or from a different angle, to prove to a (ANSI).
suitable level that the program does what it is • The UNIX OS was totally written in C.
supposed to do. It can be manual or • Today C is the most widely used and
automated. It has many different types, like popular System Programming Language.
unit testing, integration testing, system testing • Most of the state-of-the-art software have
user acceptance testing, stress testing, load been implemented using C.
testing, and soak testing etc. • Today's most popular Linux OS and RDBMS
MySQL have been written in C.
Bug means error. Debugging is the process of
finding and removing a specific bugs or errors Application of C
from the program. It is always a manual, on-off C was initially used for system development
process, as all bugs are different. work, particularly the programs that make-up
the operating system. C was adopted as a
Module 2 system development language because it
C - AN INTRODUCTION produces code that runs nearly as fast as the
C is a general-purpose, procedural, imperative code written in assembly language. Some
computer programming language developed examples of the use of C might be –
in 1972 by Dennis M. Ritchie at the Bell
Telephone Laboratories to develop the UNIX • Operating Systems
operating system. C is the most widely used • Language Compilers
computer language. • Assemblers
C was originally first implemented on the DEC • Text Editors
PDP-11 computer in 1972. • Print Spoolers
• Network Drivers
In 1978, Brian Kernighan and Dennis Ritchie • Modern Programs
produced the first publicly available • Databases
description of C, now known as the K&R • Language Interpreters
standard. • Utility programs

The UNIX operating system, the C compiler, PROGRAM STRUCTURE


and essentially all UNIX application programs
have been written in C. C has now become a
widely used professional language for various
reasons−
• Easy simple to learn
• Structured language
• It produces efficient programs
• It can handle low-level activities
• It can be compiled on a variety of computer
platforms

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


10
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

The basic building blocks of the C Look at the various parts of the above program
programming language has well defined −
program structure as shown below. • The first line of the program #include
<stdio.h> is a preprocessor command,
The documentation section consist of a set of which tells a C compiler to include stdio.h
comment line giving the name of the program, file before going to actual compilation.
author, and other details which the • The next line int main() is the main
programmer would like to use later. The link function where the program execution
section provides instructions to the compiler begins.
to link functions from the system library. The • The next line /*...*/ will be ignored by the
definition section defines all symbolic compiler and it has been put to add
constants. There are some variables and are additional comments in the program. So
declared in the global declaration section that such lines are called comments in the
is outside of all the functions. program.
• The next line printf(...) is another function
Every C program has one main() function available in C which causes the message
section. This section contains two parts, "Hello, World!" to be displayed on the
declaration part and executable part. The screen.
declaration part declares all variables used in • The next line return 0; terminates the
the executable parts. There is at least one main() function and returns the value 0 to
statement in executable part. These two parts the compiler.
must appear between the opening and closing
braces. CHARACTER SET
Character set is a set of alphabets, letters and
The program execution begins at the opening some special characters that are valid in C
brace and ends at the closing brace. The language.
closing brace of the main function section is
the logical end of the program. All statements Alphabets
in the declaration and executable parts end Uppercase: A B C ................................... X Y Z
with a semicolon. Lowercase: a b c ...................................... x y z

The subprogram section contains all the user C accepts both lowercase and uppercase
defined functions that are called in the main alphabets as variables and functions.
function. User defined functions are generally
placed immediately after the main function. Digits
0123456789
Let us look at a simple code that would print
the words "Hello World". Special Characters
Special Characters in C Programming
Example: Hello World , < > . _
( ) ; $ :
#include <stdio.h> % [ ] # ?
int main() ' & { } "
{ ^ ! * / |
/* my first sample program in C */ - \ ~ +
printf("Hello, World! \n");
return 0;
}

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


11
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

White space Characters Also remember, identifier names must be


Blank space, new line, horizontal tab, carriage different from keywords. You cannot use int as
return and form feed. an identifier because int is a keyword.

C Keywords Rules for writing an identifier.


Keywords are predefined, reserved words used 1. A valid identifier can have letters (both
in programming that have special meanings to uppercase and lowercase letters), digits
the compiler. Keywords are part of the syntax and underscores.
and they cannot be used as an identifier. 2. The first letter of an identifier should be
For example: either a letter or an underscore. However,
int money; it is discouraged to start an identifier name
with an underscore.
Here, int is a keyword that indicates 'money' 3. There is no rule on length of an identifier.
is a variable of type integer. However, the first 31 characters of
identifiers are discriminated by the
As C is a case sensitive language, all keywords compiler.
must be written in lowercase. Here is a list of
all keywords allowed in ANSI C. Good Programming Practice
Keywords in C Language You can choose any name for an identifier
auto double int struct (excluding keywords). However, if you give
break Else long switch meaningful name to an identifier, it will be easy
case enum register typedef to understand and work on for you and your
char extern return union fellow programmers.
continue for signed void
do If static while Variables
default goto sizeof volatile In programming, a variable is a container
const float short unsigned (storage area) to hold data. To indicate the
storage area, each variable should be given a
Along with these keywords, C supports other unique name (identifier). Variable names are
numerous keywords depending upon the just the symbolic representation of a memory
compiler. location.
For example:
C Identifiers int playerScore = 95;
Identifier refers to name given to entities such Here, playerScore is a variable of integer type.
as variables, functions, structures etc. Identifier The variable is assigned value: 95. The value of
must be unique. They are created to give a variable can be changed, hence the name
unique name to a entity to identify it during 'variable'. In C programming, you have to
the execution of the program. declare a variable before you can use it.

For example: Rules for naming a variable in C


int money; 1. A variable name can have letters (both
double accountBalance; uppercase and lowercase letters), digits
and underscore only.
Here, money and accountBalance are 2. The first letter of a variable should be either
identifiers. a letter or an underscore. However, it is
discouraged to start variable name with an
underscore. It is because variable name

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


12
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

that starts with an underscore can conflict Character constants


with system name and may cause error. A character constant is a constant which uses
3. There is no rule on how long a variable can single quotation around characters. For
be. However, only the first 31 characters of example: 'a', 'l', 'm', 'F'
a variable are checked by the compiler. So,
the first 31 letters of two variables in a Escape Sequences
program should be different. Sometimes, it is necessary to use characters
which cannot be typed or has special meaning
C is a strongly typed language. It means that, in C programming.
the type of a variable cannot be changed.
For example: newline(enter), tab, question
Constants/Literals mark etc. To use these characters, escape
A constant is a value or an identifier whose sequence is used.
value cannot be altered in a program. For
example: 1, 2.5, "C programming is easy", etc. For example: \n is used for newline. The
As mentioned, an identifier also can be defined backslash ( \ ) causes "escape" from the normal
as a constant. way the characters are interpreted by the
const double PI = 3.14 compiler.
Here, PI is a constant. Basically what it means
is that, PI and 3.14 is same for this program. Escape Sequences
Below are the different types of constants you Escape
Character
can use in C. Sequences
\b Backspace
Integer constants \f Form feed
An integer constant is a numeric constant \n Newline
(associated with number) without any \r Return
fractional or exponential part. There are three \t Horizontal tab
types of integer constants in C programming: \v Vertical tab
• decimal constant(base 10) \\ Backslash
• octal constant(base 8) \' Single quotation mark
• hexadecimal constant(base 16)
\" Double quotation
For example: mark
Decimal constants: 0, -9, 22 etc \? Question mark
Octal constants: 021, 077, 033 etc
\0 Null character
Hexadecimal constants: 0x7f, 0x2a, 0x521 etc
String constants
In C programming, octal constant starts with a
String constants are the constants which are
0 and hexadecimal constant starts with a 0x.
enclosed in a pair of double-quote marks. For
example:
Floating-point constants
"good" //string constant
A floating point constant is a numeric constant
"" //null string constant
that has either a fractional form or an
" " //string constant of six white
exponent form.
space
For example:
"x" //string constant having
-2.0
single character.
0.0000234
"Earth is round\n" //prints string with newline
-0.22E-5
Note: E-5 = 10-5

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


13
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

Enumeration constants distinct states as: -231,-231+1, ...,-2, -1, 0, 1, 2, ...,


Keyword enum is used to define enumeration 231-2, 231-1
types.
For example: Similarly, int of 2 bytes, it can take 216 distinct
states from -215 to 215-1. If you try to store
enum color {yellow, green, black, white}; larger number than 231-1, i.e,+2147483647
and smaller number than -231, i.e, -
Here, color is a variable and yellow, green, 2147483648, program will not run correctly.
black and white are the enumeration
constants having value 0, 1, 2 and 3 float - Floating types
respectively. Floating type variables can hold real numbers
such as: 2.34, -9.382, 5.0 etc. You can declare a
Data types in C floating point variable in C by using either
In C programming, variables or memory float or double keyword.
locations should be declared before it can be
used. Similarly, a function also needs to be For example:
declared before use. Data types simply refers float accountBalance;
to the type and size of data associated with double bookPrice;
variables and functions. Here, both accountBalance and bookPrice
are floating type variables.
1. Fundamental Data Types
o Integer types In C, floating values can be represented in
o Floating type exponential form as well.
o Character type
2. Derived Data Types For example:
o Arrays float normalizationFactor = 22.442e2;
o Pointers
o Structures Difference between float and double
o Enumeration The size of float (single precision float data
type) is 4 bytes. And the size of double
int - Integer data types (double precision float data type) is 8 bytes.
Integers are whole numbers that can have Floating point variables has a precision of 6
both positive and negative values but no digits whereas the precision of double is 14
decimal values. Example: 0, -5, 10 digits.

In C programming, keyword is used for char - Character types


declaring integer variable. For example: Keyword char is used for declaring character
int id; type variables.
Here, id is a variable of type integer.
You can declare multiple variable at once in C For example:
programming. char test = 'h';
Here, test is a character variable. The value of
For example: test is 'h'.
int id, age; The size of character variable is 1 byte.
The size of int is either 2 bytes(In older PC's) or
4 bytes. If you consider an integer having size C Qualifiers
of 4 byte( equal to 32 bits), it can take 232 Qualifiers alters the meaning of base data
types to yield a new data type.

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


14
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

Size qualifiers Keyword volatile is used for creating volatile


Size qualifiers alters the size of a basic type. variables.
There are two size qualifiers, long and short.
For example: OPERATORS IN C
long double i; An operator is a symbol which operates on a
value or a variable. For example: + is an
The size of double is 8 bytes. However, when operator to perform addition.
long keyword is used, that variable becomes
10 bytes. C programming has wide range of operators
to perform various operations. For better
There is another keyword short which can be understanding of operators, these operators
used if you previously know the value of a can be classified as:
variable will always be a small number. • Arithmetic Operators
• Increment and Decrement Operators
Sign qualifiers • Assignment Operators
Integers and floating point variables can hold • Relational Operators
both negative and positive values. However, if • Logical Operators
a variable needs to hold positive value only, • Conditional Operators
unsigned data types are used. • Bitwise Operators
• Special Operators
For example:
// unsigned variables cannot hold negative C Arithmetic Operators
value An arithmetic operator performs mathematical
unsigned int positiveInteger; operations such as addition, subtraction and
multiplication on numerical values (constants
There is another qualifier signed which can and variables).
hold both negative and positive only. Operator Meaning of Operator
However, it is not necessary to define variable + addition or unary plus
signed since a variable is signed by default. - subtraction or unary minus
* multiplication
An integer variable of 4 bytes can hold data / Division
from -231 to 231-1. However, if the variable is % remainder after division(modulo
defined as unsigned, it can hold data from 0 to division)
232-1.
Example #1: Arithmetic Operators
It is important to note that, sign qualifiers can // C Program to demonstrate the working of
be applied to int and char types only. arithmetic operators
Constant qualifiers #include <stdio.h>
An identifier can be declared as a constant. To int main()
do so const keyword is used. {
const int cost = 20; int a = 9,b = 4, c;
The value of cost cannot be changed in the
program. c = a+b;
printf("a+b = %d \n",c);
Volatile qualifiers
A variable should be declared volatile c = a-b;
whenever its value can be changed by some printf("a-b = %d \n",c);
external sources outside the program.

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


15
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

c = a*b;
printf("a*b = %d \n",c); Increment and decrement operators
C programming has two operators increment
c=a/b; ++ and decrement -- to change the value of
printf("a/b = %d \n",c); an operand (constant or variable) by 1.
Increment ++ increases the value by 1 whereas
c=a%b; decrement -- decreases the value by 1. These
printf("Remainder when a divided by b = %d two operators are unary operators, meaning
\n",c); they only operate on a single operand.

return 0; Example #2: Increment and Decrement


} Operators
// C Program to demonstrate the working of
Output increment and decrement operators
a+b = 13 #include <stdio.h>
a-b = 5 int main()
a*b = 36 {
a/b = 2 int a = 10, b = 100;
Remainder when a divided by b=1 float c = 10.5, d = 100.5;

The operators +, - and * computes addition, printf("++a = %d \n", ++a);


subtraction and multiplication respectively as
you might have expected. printf("--b = %d \n", --b);

In normal calculation, 9/4 = 2.25. However, the printf("++c = %f \n", ++c);


output is 2 in the program.
printf("--d = %f \n", --d);
It is because both variables a and b are
integers. Hence, the output is also an integer. return 0;
The compiler neglects the term after decimal }
point and shows answer 2 instead of 2.25. Output
++a = 11
The modulo operator % computes the --b = 99
remainder. When a = 9 is divided by b = 4, the ++c = 11.500000
remainder is 1. The % operator can only be ++d = 99.500000
used with integers. Here, the operators ++ and -- are used as
prefix. These two operators can also be used
Suppose a = 5.0, b = 2.0, c = 5 and d = 2. Then as postfix like a++ and a--.
in C programming,
C Assignment Operators
a/b = 2.5 // Because both operands are An assignment operator is used for assigning
floating-point variables a value to a variable. The most common
a/d = 2.5 // Because one operand is floating- assignment operator is =
point variable Operator Example Same as
c/b = 2.5 // Because one operand is floating- = a=b a=b
point variable += a += b a = a+b
c/d = 2 // Because both operands are -= a -= b a = a-b
integers *= a *= b a = a*b

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


16
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

/= a /= b a = a/b Operator Meaning of Example


%= a %= b a = a%b Operator
== Equal to 5 == 3
Example #3: Assignment Operators returns 0
// C Program to demonstrate the working of > Greater than 5>3
assignment operators returns 1
#include <stdio.h> < Less than 5<3
int main() returns 0
{ != Not equal to 5 != 3
int a = 5, c; returns 1
>= Greater than or 5 >= 3
c = a; equal to returns 1
printf("c = %d \n", c); <= Less than or 5 <= 3
equal to return 0
c += a; // c = c+a
printf("c = %d \n", c); Example #4: Relational Operators
// C Program to demonstrate the working of
c -= a; // c = c-a arithmetic operators
printf("c = %d \n", c); #include <stdio.h>
int main()
c *= a; // c = c*a {
printf("c = %d \n", c); int a = 5, b = 5, c = 10;

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


printf("c = %d \n", c); true
printf("%d == %d = %d \n", a, c, a == c); //
c %= a; // c = c%a false
printf("c = %d \n", c);
printf("%d > %d = %d \n", a, b, a > b); //false
return 0; printf("%d > %d = %d \n", a, c, a > c); //false
}

Output printf("%d < %d = %d \n", a, b, a < b); //false


c=5 printf("%d < %d = %d \n", a, c, a < c); //true
c = 10
c=5
c = 25 printf("%d != %d = %d \n", a, b, a != b);
c=5 //false
c=0 printf("%d != %d = %d \n", a, c, a != c); //true

C Relational Operators
A relational operator checks the relationship printf("%d >= %d = %d \n", a, b, a >= b);
between two operands. If the relation is true, it //true
returns 1; if the relation is false, it returns value printf("%d >= %d = %d \n", a, c, a >= c);
0. //false

Relational operators are used in decision


making and loops.

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


17
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

printf("%d <= %d = %d \n", a, b, a <= b); Example #5: Logical Operators


//true // C Program to demonstrate the working of
printf("%d <= %d = %d \n", a, c, a <= c); logical operators
//true
#include <stdio.h>
return 0; int main()
{
} int a = 5, b = 5, c = 10, result;

Output result = (a == b) && (c > b);


5 == 5 = 1 printf("(a == b) && (c > b) equals to %d \n",
5 == 10 = 0 result);
5>5=0
5 > 10 = 0 result = (a == b) && (c < b);
5<5=0 printf("(a == b) && (c < b) equals to %d \n",
5 < 10 = 1 result);
5 != 5 = 0
5 != 10 = 1 result = (a == b) || (c < b);
5 >= 5 = 1 printf("(a == b) || (c < b) equals to %d \n",
5 >= 10 = 0 result);
5 <= 5 = 1
5 <= 10 = 1 result = (a != b) || (c < b);
printf("(a != b) || (c < b) equals to %d \n",
C Logical Operators result);
An expression containing logical operator
returns either 0 or 1 depending upon whether result = !(a != b);
expression results true or false. Logical printf("!(a == b) equals to %d \n", result);
operators are commonly used in decision
making in C programming. result = !(a == b);
printf("!(a == b) equals to %d \n", result);
Meaning of
Operator Example
Operator return 0;
If c = 5 and d = }
Logial AND.
2 then,
True only if
&& expression ((c Output
all operands
== 5) && (d > (a == b) && (c > b) equals to 1
are true
5)) equals to 0. (a == b) && (c < b) equals to 0
Logical OR. If c = 5 and d = (a == b) || (c < b) equals to 1
True only if 2 then, (a != b) || (c < b) equals to 0
|| either one expression ((c !(a != b) equals to 1
operand is == 5) || (d > 5)) !(a == b) equals to 0
true equals to 1.
Logical NOT. If c = 5 then, Explanation of logical operator program
True only if expression ! (c • (a == b) && (c > 5) evaluates to 1
!
the operand == 5) equals to because both operands (a == b) and (c
is 0 0. > b) is 1 (true).
• (a == b) && (c < b) evaluates to 0
because operand (c < b) is 0 (false).

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


18
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

• (a == b) || (c < b) evaluates to 1 because printf("Size of float=%lu bytes\n",sizeof(b));


(a = b) is 1 (true). printf("Size of double=%lu
• (a != b) || (c < b) evaluates to 0 because bytes\n",sizeof(c));
both operand (a != b) and (c < b) are 0 printf("Size of char=%lu byte\n",sizeof(d));
(false). printf("Size of integer type array having 10
• !(a != b) evaluates to 1 because operand elements = %lu bytes\n", sizeof(e));
(a != b) is 0 (false). Hence, !(a != b) is 1 return 0;
(true). }
• !(a == b) evaluates to 0 because (a ==
b) is 1 (true). Hence, !(a == b) is 0 (false). Output
Size of int = 4 bytes
Bitwise Operators Size of float = 4 bytes
During computation, mathematical operations Size of double = 8 bytes
like: addition, subtraction, addition and Size of char = 1 byte
division are converted to bit-level which makes Size of integer type array having 10 elements
processing faster and saves power. = 40 bytes

Bitwise operators are used in C programming C Ternary Operator (?:)


to perform bit-level operations. A conditional operator is a ternary operator,
Operators Meaning of operators that is, it works on 3 operands.
& Bitwise AND
| Bitwise OR Conditional Operator Syntax
^ Bitwise exclusive OR conditionalExpression ? expression1 :
~ Bitwise complement expression2
<< Shift left
>> Shift right The conditional operator works as follows:
• The first expression
Comma Operator conditionalExpression is evaluated first.
Comma operators are used to link related This expression evaluates to 1 if it's true
expressions together. and evaluates to 0 if it's false.
• If conditionalExpression is true,
For example: expression1 is evaluated.
int a, c = 5, d; • If conditionalExpression is false,
The sizeof operator expression2 is evaluated.
The sizeof is an unary operator which returns
the size of data (constant, variables, array, Example #7: C conditional Operator
structure etc). #include <stdio.h>
int main(){
Example #6: sizeof Operator char February;
#include <stdio.h> int days;
int main() printf("If this year is leap year, enter 1. If not
{ enter any integer: ");
int a, e[10]; scanf("%c",&February);
float b;
double c; // If test condition (February == 'l') is true,
char d; days equal to 29.
printf("Size of int=%lu bytes\n",sizeof(a)); // If test condition (February =='l') is false,
days equal to 28.

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


19
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

days = (February == '1') ? 29 : 28; • Here, stdio.h is a header file (standard input
output header file) and #include is a
printf("Number of days in February = preprocessor directive to paste the code
%d",days); from the header file when necessary. When
return 0; the compiler encounters printf() function
} and doesn't find stdio.h header file,
compiler shows error.
Output • The return 0; statement is the "Exit status"
If this year is leap year, enter 1. If not enter any of the program. In simple terms, program
integer: 1 ends.
Number of days in February = 29
Example #2: C Integer Output
Module
#include <stdio.h>
INPUT AND OUTPUT IN C int main()
C programming has several in-built library {
functions to perform input and output tasks. int testInteger = 5;
printf("Number = %d", testInteger);
Two commonly used functions for I/O return 0;
(Input/Output) are printf() and scanf(). }

The scanf() function reads formatted input Output


from standard input (keyboard) whereas the Number = 5
printf() function sends formatted output to the
standard output (screen). Inside the quotation of printf() function, there
is a format string "%d" (for integer). If the
Example #1: C Output format string matches the argument
(testInteger in this case), it is displayed on the
#include <stdio.h> //This is needed to run screen.
printf() function.
int main() Example #3: C Integer Input/Output
{ #include <stdio.h>
printf("C Programming"); //displays the int main()
content inside {
//quotation int testInteger;
return 0; printf("Enter an integer: ");
} scanf("%d",&testInteger);
printf("Number = %d",testInteger);
Output return 0;
C Programming }

Working of this program Output


• All valid C program must contain the main() Enter an integer: 4
function. The code execution begins from Number = 4
the start of main() function.
• The printf() is a library function to send The scanf() function reads formatted input
formatted output to the screen. The printf() from the keyboard. When user enters an
function is declared in "stdio.h" header file. integer, it is stored in variable testInteger.

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


20
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

Note the '&' sign before testInteger; Example #5: C ASCII Code
&testInteger gets the address of testInteger #include <stdio.h>
and the value is stored in that address. int main()
{
Example #3: C Floats Input/Output char chr;
#include <stdio.h> printf("Enter a character: ");
int main() scanf("%c",&chr);
{
float f; // When %c text format is used, character is
printf("Enter a number: "); displayed in case of character types
// %f format string is used in case of floats printf("You entered %c.\n",chr);
scanf("%f",&f);
printf("Value = %f", f); // When %d text format is used, integer is
return 0; displayed in case of character types
} printf("ASCII value of %c is %d.", chr, chr);
return 0;
Output }
Enter a number: 23.45
Value = 23.450000 Output
Enter a character: g
The format string "%f" is used to read and You entered g.
display formatted in case of floats. ASCII value of g is 103.

Example #4: C Character I/O The ASCII value of character 'g' is 103. When,
#include <stdio.h> 'g' is entered, 103 is stored in variable var1
int main() instead of g.
{
char chr; You can display a character if you know ASCII
printf("Enter a character: "); code of that character. This is shown by
scanf("%c",&chr); following example.
printf("You entered %c.",chr);
return 0; Example #6: C ASCII Code
} #include <stdio.h>
int main()
Output {
Enter a character: g int chr = 69;
You entered g. printf("Character having ASCII value 69 is
%c.",chr);
Format string %c is used in case of character return 0;
types. }

Little bit on ASCII code Output


When a character is entered in the above Character having ASCII value 69 is E.
program, the character itself is not stored.
Instead, a numeric value(ASCII value) is stored. More on Input/Output of floats and
And when we displayed that value using "%c" Integers
text format, the entered character is displayed. Integer and floats can be displayed in different
formats in C programming.

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


21
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

Example #7: I/O of Floats and Integers Simple if statement


#include <stdio.h> if (testExpression)
int main() {
{ // statements
}
int integer = 9876;
float decimal = 987.6543; The if statement evaluates the test expression
inside the parenthesis.
// Prints the number right justified within 6 If the test expression is evaluated to true
columns (nonzero), statements inside the body of if is
printf("4 digit integer right justified to 6 executed.
column: %6d\n", integer); If the test expression is evaluated to false (0),
statements inside the body of if is skipped
// Tries to print number right justified to 3 from execution.
digits but the number is not right adjusted
because there are only 4 numbers Flowchart of if statement
printf("4 digit integer right justified to 3
column: %3d\n", integer);

// Rounds to two digit places


printf("Floating point number rounded to 2
digits: %.2f\n",decimal);

// Rounds to 0 digit places


printf("Floating point number rounded to 0
digits: %.f\n",987.6543);

// Prints the number in exponential


notation(scientific notation)
printf("Floating point number in exponential
form: %e\n",987.6543); Example #1: C if statement
return 0; // Program to display a number if user enters
} negative number
// If user enters positive number, that number
Output won't be displayed
4 digit integer right justified to 6 column:
9876 #include <stdio.h>
4 digit integer right justified to 3 column: 9876 int main()
Floating point number rounded to 2 digits: {
987.65 int number;
Floating point number rounded to 0 digits: 988
Floating point number in exponential form: printf("Enter an integer: ");
9.876543e+02 scanf("%d", &number);

DECISION STATEMENTS // Test expression is true if number is less


Decision making is used to specify the order in than 0
which statements are executed. if (number < 0)
{

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


22
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

printf("You entered %d.\n", number); Flowchart of if...else statement


}

printf("The if statement is easy.");

return 0;
}

Output 1
Enter an integer: -2
You entered -2.
The if statement is easy.
When user enters -2, the test expression
(number < 0) becomes true. Hence, You
entered -2 is displayed on the screen.

Output 2
Enter an integer: 5
The if statement in C programming is easy. Example #2: C if...else statement
When user enters 5, the test expression // Program to check whether an integer
(number < 0) becomes false and the statement entered by the user is odd or even
inside the body of if is skipped.
#include <stdio.h>
if...else statement int main()
The if...else statement executes some code if {
the test expression is true (nonzero) and some int number;
other code if the test expression is false (0). printf("Enter an integer: ");
scanf("%d",&number);
Syntax of if...else
if (testExpression) { // True if remainder is 0
// codes inside the body of if if( number%2 == 0 )
} printf("%d is an even integer.",number);
else { else
// codes inside the body of else printf("%d is an odd integer.",number);
} return 0;
If test expression is true, codes inside the body }
of if statement is executed and, codes inside
the body of else statement is skipped. Output
If test expression is false, codes inside the body Enter an integer: 7
of else statement is executed and, codes inside 7 is an odd integer.
the body of if statement is skipped. When user enters 7, the test expression (
number%2 == 0 ) is evaluated to false. Hence,
the statement inside the body of else
statement printf("%d is an odd integer"); is
executed and the statement inside the body of
if is skipped.

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


23
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

Nested if...else statement (if...elseif....else //checks if two integers are equal.


Statement) if(number1 == number2)
The if...else statement executes two different {
codes depending upon whether the test printf("Result: %d =
expression is true or false. Sometimes, a choice %d",number1,number2);
has to be made from more than 2 possibilities. }

The nested if...else statement allows you to //checks if number1 is greater than
check for multiple test expressions and number2.
execute different codes for more than two else if (number1 > number2)
conditions. {
printf("Result: %d > %d", number1,
Syntax of nested if...else statement. number2);
if (testExpression1) }
{
// statements to be executed if // if both test expression is false
testExpression1 is true else
} {
else if(testExpression2) printf("Result: %d < %d",number1,
{ number2);
// statements to be executed if }
testExpression1 is false and testExpression2 is
true return 0;
} }
else if (testExpression 3)
{ Output
// statements to be executed if Enter two integers: 12
testExpression1 and testExpression2 is false 23
and testExpression3 is true Result: 12 < 23
}
. switch...case
. The if..else..if ladder allows you to execute a
else block code among many alternatives. If you
{ are checking on the value of a single variable
// statements to be executed if all test in if...else...if, it is better to use switch
expressions are false statement.
}
The switch statement is often faster than
Example #3: C Nested if...else statement nested if...else (not always). Also, the syntax of
// Program to relate two integers using =, > or switch statement is cleaner and easy to
< understand.

#include <stdio.h> Syntax of switch...case


int main() switch (n)
{ {
int number1, number2; case constant1:
printf("Enter two integers: "); // code to be executed if n is equal to
scanf("%d %d", &number1, &number2); constant1;

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


24
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

break; Example: switch Statement


// Program to create a simple calculator
case constant2: // performs addition, subtraction,
// code to be executed if n is equal to multiplication or division depending the input
constant2; from user
break;
. # include <stdio.h>
.
. int main() {
default:
// code to be executed if n doesn't match char operator;
any constant double firstNumber,secondNumber;
}
printf("Enter an operator (+, -, *, /): ");
When a case constant is found that matches scanf("%c", &operator);
the switch expression, control of the program
passes to the block of code associated with printf("Enter two operands: ");
that case. scanf("%lf %lf",&firstNumber,
&secondNumber);
In the above pseudo code, suppose the value
of n is equal to constant2. The compiler will switch(operator)
execute the block of code associate with the {
case statement until the end of switch block, case '+':
or until the break statement is encountered. printf("%.1lf + %.1lf =
%.1lf",firstNumber, secondNumber,
The break statement is used to prevent the firstNumber+secondNumber);
code running into the next case. break;
switch Statement Flowchart
case '-':
printf("%.1lf - %.1lf =
%.1lf",firstNumber, secondNumber,
firstNumber-secondNumber);
break;

case '*':
printf("%.1lf * %.1lf =
%.1lf",firstNumber, secondNumber,
firstNumber*secondNumber);
break;

case '/':
printf("%.1lf / %.1lf =
%.1lf",firstNumber, secondNumber,
firstNumber/firstNumber);
break;

// operator is doesn't match any case


constant (+, -, *, /)

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


25
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

default: terminated. But if the test expression is true


printf("Error! operator is not correct"); (nonzero), codes inside the body of for loop is
} executed and the update expression is
updated.
return 0;
} This process repeats until the test expression is
false.
Output The for loop is commonly used when the
Enter an operator (+, -, *,): - number of iterations is known.
Enter two operands: 32.5
12.4 for loop Flowchart
32.5 - 12.4 = 20.1

The - operator entered by the user is stored in


operator variable. And, two operands 32.5 and
12.4 are stored in variables firstNumber and
secondNumber respectively.

Then, control of the program jumps to


printf("%.1lf / %.1lf = %.1lf",firstNumber,
secondNumber, firstNumber/firstNumber);

Finally, the break statement ends the switch


statement.
If break statement is not used, all cases after
the correct case is executed.

Loops
Loops are used in programming to repeat a
specific block until some end condition is met.
There are three loops in C programming:
1. for loop Example: for loop
2. while loop // Program to calculate the sum of first n
3. do...while loop natural numbers
// Positive integers 1,2,3...n are known as
for Loop natural numbers
The syntax of for loop is:
for (initializationStatement; testExpression; #include <stdio.h>
updateStatement) int main()
{ {
// codes int num, count, sum = 0;
}
printf("Enter a positive integer: ");
Working of for loop scanf("%d", &num);
The initialization statement is executed only
once. // for loop terminates when n is less than
Then, the test expression is evaluated. If the count
test expression is false (0), for loop is

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


26
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

for(count = 1; count <= num; ++count)


{ Working of while loop
sum += count; The while loop evaluates the test expression.
} If the test expression is true (nonzero), codes
inside the body of while loop are exectued. The
printf("Sum = %d", sum); test expression is evaluated again. The process
goes on until the test expression is false.
return 0; When the test expression is false, the while
} loop is terminated.

Output Flowchart of while loop


Enter a positive integer: 10
Sum = 55

The value entered by the user is stored in


variable num. Suppose, the user entered 10.

The count is initialized to 1 and the test


expression is evaluated. Since, the test
expression count <= num (1 less than or equal
to 10) is true, the body of for loop is executed
and the value of sum will equal to 1.

Then, the update statement ++count is


executed and count will equal to 2. Again, the
test expression is evaluated. Since, 2 is also less
than 10, the test expression is evaluated to true
and the body of for loop is executed. Now, the
sum will equal 3.
Example #1: while loop
This process goes on and the sum is calculated // Program to find factorial of a number
until the count reaches 11. // For a positive integer n, factorial = 1*2*3...n

When the count is 11, the test expression is #include <stdio.h>


evaluated to 0 (false) as 11 is not less than or int main()
equal to 10. Therefore, the loop terminates {
and next, the total sum is printed. int number;
long long factorial;
while loop
The syntax of a while loop is: printf("Enter an integer: ");
while (testExpression) scanf("%d",&number);
{
//codes factorial = 1;
}
where, testExpression checks the condition is // loop terminates when number is less than
true or false before each loop. or equal to 0
while (number > 0)
{

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


27
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

factorial *= number; // factorial =


factorial*number;
--number;
}

printf("Factorial= %lld", factorial);

return 0;
}

Output
Enter an integer: 5
Factorial = 120

do...while loop
The do..while loop is similar to the while loop
Example #2: do...while loop
with one important difference. The body of
// Program to add numbers until user enters
do...while loop is executed once, before
zero
checking the test expression. Hence, the
do...while loop is executed at least once.
#include <stdio.h>
int main()
do...while loop Syntax
{
do
double number, sum = 0;
{
// codes
// loop body is executed at least once
}
do
while (testExpression);
{
printf("Enter a number: ");
Working of do...while loop
scanf("%lf", &number);
The code block (loop body) inside the braces
sum += number;
is executed once.
}
Then, the test expression is evaluated. If the
while(number != 0.0);
test expression is true, the loop body is
executed again. This process goes on until the
printf("Sum = %.2lf",sum);
test expression is evaluated to 0 (false).
When the test expression is false (nonzero),
return 0;
the do...while loop is terminated.
}

Output
Enter a number: 1.5
Enter a number: 2.4
Enter a number: -3.4
Enter a number: 4.2
Enter a number: 0
Sum = 4.70

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


28
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

break Statement Working of break statement


It is sometimes desirable to skip some
statements inside the loop or terminate the
loop immediately without checking the test
expression.

In such cases, break and continue statements


are used.
The break statement terminates the loop (for,
while and do...while loop) immediately when it
is encountered. The break statement is used
with decision making statement such as
if...else.

Syntax of break statement


break;

The simple code above is the syntax for break


statement.
Example #1: break statement
Flowchart of break statement // Program to calculate the sum of maximum
of 10 numbers
// Calculates sum until user enters positive
number
# include <stdio.h>
int main()
{
int i;
double number, sum = 0.0;

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


{
printf("Enter a n%d: ",i);
scanf("%lf",&number);

// If user enters negative number, loop is


terminated
if(number < 0.0)
{
break;
}

sum += number; // sum = sum + number;


}
printf("Sum = %.2lf",sum);
return 0;
}

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


29
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

Working of continue statement


Output
Enter a n1: 2.4
Enter a n2: 4.5
Enter a n3: 3.4
Enter a n4: -3
Sum = 10.30

This program calculates the sum of maximum


of 10 numbers. It's because, when the user
enters negative number, the break statement
is executed and loop is terminated.

In C programming, break statement is also


used with switch...case statement.

continue Statement
The continue statement skips some Example #2: continue statement
statements inside the loop. The continue // Program to calculate sum of maximum of 10
statement is used with decision making numbers
statement such as if...else. // Negative numbers are skipped from
calculation
Syntax of continue Statement
continue; # include <stdio.h>
int main()
Flowchart of continue Statement {
int i;
double number, sum = 0.0;

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


{
printf("Enter a n%d: ",i);
scanf("%lf",&number);

// If user enters negative number, loop is


terminated
if(number < 0.0)
{
continue;
}

sum += number; // sum = sum + number;


}

printf("Sum = %.2lf",sum);
return 0;
}

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


30
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

Output // If user enters negative number, the sum and


Enter a n1: 1.1 average of previously entered positive number
Enter a n2: 2.2 is displayed
Enter a n3: 5.5
Enter a n4: 4.4 # include <stdio.h>
Enter a n5: -3.4
Enter a n6: -45.5 int main()
Enter a n7: 34.5 {
Enter a n8: -4.2
Enter a n9: -1000 const int maxInput = 5;
Enter a n10: 12 int i;
Sum = 59.70 double number, average, sum=0.0;

In the program, when the user enters positive for(i=1; i<=maxInput; ++i)
number, the sum is calculated using sum += {
number; statement. printf("%d. Enter a number: ", i);
When the user enters negative number, the scanf("%lf",&number);
continue statement is executed and skips the
negative number from calculation. // If user enters negative number, flow of
program moves to label jump
goto statement if(number < 0.0)
The goto statement is used to alter the normal goto jump;
sequence of a C program.
sum += number; // sum = sum+number;
Syntax of goto statement }
goto label;
... .. ... jump:
... .. ...
... .. ... average=sum/(i-1);
label: printf("Sum = %.2f\n", sum);
statement; printf("Average = %.2f", average);
The label is an identifier. When goto statement
is encountered, control of the program jumps return 0;
to label: and starts executing the code. }

Output
1. Enter a number: 3
2. Enter a number: 4.3
3. Enter a number: 9.3
4. Enter a number: -2.9
Sum = 16.60
Reasons to avoid goto statement
Example: goto Statement
The use of goto statement may lead to code
that is buggy and hard to follow.
// Program to calculate the sum and average
of maximum of 5 numbers
For example:
one:
for (i = 0; i < number; ++i)

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


31
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

{ Declare An Array
test += i; data_type array_name[array_size];
goto two;
} For example,
two: float mark[5];
if (test > 5) { Here, we declared an array, mark, of floating-
goto three; point type and size 5. Meaning, it can hold 5
} floating-point values.
... .. ...
Elements of an Array and to access them
Also, goto statement allows you to do bad You can access elements of an array by indices.
stuff such as jump out of scope. Suppose you declared an array mark as above.
The first element is mark[0], second element
That being said, goto statement can be useful is mark[1] and so on.
sometimes.
For example: to break from nested loops.

If you think the use of goto statement


simplifies your program. By all means use it.
The goal here is to create code that your fellow • Arrays have 0 as the first index not 1. In this
programmers can understand easily. example, mark[0]
• If the size of an array is n, to access the last
Module 4 element, (n-1) index is used. In this
example, mark[4]
Arrays • Suppose the starting address of mark[0] is
2120d. Then, the next address, a[1], will be
2124d, address of a[2] will be 2128d and so
on. It's because the size of a float is 4 bytes.

Initialize an Array
It's possible to initialize an array during
declaration.

For example,
int mark[5] = {19, 10, 8, 17, 9};
An array is a collection of data that holds fixed
number of values of same type. Another method to initialize array during
declaration:
For example: if you want to store marks of 100 int mark[] = {19, 10, 8, 17, 9};
students, you can create an array for it.
float marks[100];
The size and type of arrays cannot be changed
after its declaration.

Arrays are of two types:


1. One-dimensional arrays Here,
2. Multidimensional arrays mark[0] is equal to 19
mark[1] is equal to 10

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


32
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

mark[2] is equal to 8 Output


mark[3] is equal to 17 Enter n: 5
mark[4] is equal to 9 Enter number1: 45
Enter number2: 35
Insert and Print Array Elements Enter number3: 38
int mark[5] = {19, 10, 8, 17, 9} Enter number4: 31
Enter number5: 49
// insert different value to third element Average = 39
mark[3] = 9;
Important thing to remember when
// take input from the user and insert in third working with C arrays
element Suppose you declared an array of 10 elements.
scanf("%d", &mark[2]); Let's say,
int testArray[10];
// take input from the user and insert in (i+1)th You can use the array members from
element testArray[0] to testArray[9].
scanf("%d", &mark[i]);
If you try to access array elements outside of
// print first element of an array its bound, let's say testArray[12], the compiler
printf("%d", mark[0]); may not show any error. However, this may
cause unexpected output (undefined
// print ith element of an array behavior).
printf("%d", mark[i-1]);
Multidimensional Arrays
Example: C Arrays In C programming, you can create an array of
// Program to find the average of n (n < 10) arrays known as multidimensional array.
numbers using arrays For example,
float x[3][4];
#include <stdio.h> Here, x is a two-dimensional (2D) array. The
int main() array can hold 12 elements. You can think the
{ array as table with 3 row and each row has 4
int marks[10], i, n, sum = 0, average; column.
printf("Enter n: ");
scanf("%d", &n);
for(i=0; i<n; ++i)
{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
sum += marks[i];
}
average = sum/n;

printf("Average marks = %d", average); Similarly, you can declare a three-dimensional


(3d) array.
return 0; For example,
} float y[2][4][3];
Here, The array y can hold 24 elements.

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


33
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

You can think this example as: Each 2 elements scanf("%d", &temperature[i][j]);
have 4 elements, which makes 8 elements and }
each 8 elements can have 3 elements. Hence, }
the total number of elements is 24.
printf("\nDisplaying values: \n\n");
Initialize a Multidimensional Array for (int i = 0; i < CITY; ++i) {
There is more than one way to initialize a for(int j = 0; j < WEEK; ++j)
multidimensional array. {
printf("City %d, Day %d = %d\n", i+1,
Initialization of a two dimensional array j+1, temperature[i][j]);
// Different ways to initialize two dimensional }
array }
return 0;
int c[2][3] = {{1, 3, 0}, {-1, 5, 9}}; }

int c[][3] = {{1, 3, 0}, {-1, 5, 9}}; Output


City 1, Day 1: 33
int c[2][3] = {1, 3, 0, -1, 5, 9}; City 1, Day 2: 34
Above code are three different ways to City 1, Day 3: 35
initialize a two dimensional arrays. City 1, Day 4: 33
City 1, Day 5: 32
Initialization of Three Dimensional Array. City 1, Day 6: 31
You can initialize a three dimensional array in City 1, Day 7: 30
a similar way like a two dimensional array. City 2, Day 1: 23
City 2, Day 2: 22
Here's an example, City 2, Day 3: 21
int test[2][3][4] = { City 2, Day 4: 24
{ {3, 4, 2, 3}, {0, -3, 9, 11}, City 2, Day 5: 22
{23, 12, 23, 2} }, City 2, Day 6: 25
{ {13, 4, 56, 3}, {5, 9, 3, 5}, City 2, Day 7: 26
{3, 1, 4, 9} }
}; Displaying values:

Example #1: Two Dimensional Array to City 1, Day 1 = 33


store and display values City 1, Day 2 = 34
// C program to store temperature of two cities City 1, Day 3 = 35
for a week and display it. City 1, Day 4 = 33
#include <stdio.h> City 1, Day 5 = 32
City 1, Day 6 = 31
const int CITY = 2; City 1, Day 7 = 30
const int WEEK = 7; City 2, Day 1 = 23
City 2, Day 2 = 22
int main() City 2, Day 3 = 21
{ City 2, Day 4 = 24
int temperature[CITY][WEEK]; City 2, Day 5 = 22
for (int i = 0; i < CITY; ++i) { City 2, Day 6 = 25
for(int j = 0; j < WEEK; ++j) { City 2, Day 7 = 26
printf("City %d, Day %d: ", i+1, j+1);

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


34
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

Example #2: Sum of two matrices using Two Ouput


dimensional arrays Enter elements of 1st matrix
Enter a11: 2;
C program to find the sum of two matrices Enter a12: 0.5;
of order 2*2 using multidimensional arrays. Enter a21: -1.1;
#include <stdio.h> Enter a22: 2;
int main() Enter elements of 2nd matrix
{ Enter b11: 0.2;
float a[2][2], b[2][2], c[2][2]; Enter b12: 0;
int i, j; Enter b21: 0.23;
Enter b22: 23;
// Taking input using nested for loop
printf("Enter elements of 1st matrix\n"); Sum Of Matrix:
for(i=0; i<2; ++i) 2.2 0.5
for(j=0; j<2; ++j) -0.9 25.0
{
printf("Enter a%d%d: ", i+1, j+1); Example #3: Three Dimensional Array
scanf("%f", &a[i][j]); C Program to store values entered by the
} user in a three-dimensional array and
display it.
// Taking input using nested for loop #include <stdio.h>
printf("Enter elements of 2nd matrix\n"); int main()
for(i=0; i<2; ++i) {
for(j=0; j<2; ++j) // this array can store 12 elements
{
printf("Enter b%d%d: ", i+1, j+1); int i, j, k, test[2][3][2];
scanf("%f", &b[i][j]);
} printf("Enter 12 values: \n");
// adding corresponding elements of two
arrays for(i = 0; i < 2; ++i) {
for(i=0; i<2; ++i) for (j = 0; j < 3; ++j) {
for(j=0; j<2; ++j) for(k = 0; k < 2; ++k ) {
{ scanf("%d", &test[i][j][k]);
c[i][j] = a[i][j] + b[i][j]; }
} }
// Displaying the sum }
printf("\nSum Of Matrix:");
// Displaying values with proper index.
for(i=0; i<2; ++i)
for(j=0; j<2; ++j) printf("\nDisplaying values:\n");
{
printf("%.1f\t", c[i][j]); for(i = 0; i < 2; ++i) {
for (j = 0; j < 3; ++j) {
if(j==1) for(k = 0; k < 2; ++k ) {
printf("\n"); printf("test[%d][%d][%d] = %d\n", i,
} j, k, test[i][j][k]);
return 0; }
} }

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


35
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

} Passing One-dimensional Array in Function


Single element of an array can be passed in
return 0; similar manner as passing variable to a
} function.

Output C program to pass a single element of an


Enter 12 values: array to function
1 #include <stdio.h>
2 void display(int age)
3 {
4 printf("%d", age);
5 }
6
7 int main()
8 {
9 int ageArray[] = { 2, 3, 4 };
10 display(ageArray[2]); //Passing array
11 element ageArray[2] only.
12 return 0;
}
Displaying Values:
test[0][0][0] = 1 Output
test[0][0][1] = 2 4
test[0][1][0] = 3
test[0][1][1] = 4 Passing an entire one-dimensional array to
test[0][2][0] = 5 a function
test[0][2][1] = 6 While passing arrays as arguments to the
test[1][0][0] = 7 function, only the name of the array is passed
test[1][0][1] = 8 (,i.e, starting address of memory area is passed
test[1][1][0] = 9 as argument).
test[1][1][1] = 10
test[1][2][0] = 11 C program to pass an array containing age
test[1][2][1] = 12 of person to a function. This function
should find average age and display the
Pass arrays to a function in C Programming average age in main function.
#include <stdio.h>
float average(float age[]);

int main()
{
float avg, age[] = { 23.4, 55, 22.6, 3, 40.5, 18
};
avg = average(age); /* Only name of array is
In C programming, a single array element or passed as argument. */
an entire array can be passed to a function. printf("Average age=%.2f", avg);
This can be done for both one-dimensional return 0;
array or a multi-dimensional array. }

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


36
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

float average(float age[]) Output


{ Enter 4 numbers:
int i; 2
float avg, sum = 0.0; 3
for (i = 0; i < 6; ++i) { 4
sum += age[i]; 5
} Displaying:
avg = (sum / 6); 2
return avg; 3
} 4
Output 5
Average age=27.08
Strings
Passing Multi-dimensional Arrays to In C programming, array of characters is called
Function a string. A string is terminated by a null
To pass two-dimensional array to a function as character /0.
an argument, starting address of memory area
reserved is passed as in one dimensional array For example:
"c string tutorial"
Example: Pass two-dimensional arrays to a Here, "c string tutorial" is a string. When,
function compiler encounter strings, it appends a null
#include <stdio.h> character /0 at the end of string.
void displayNumbers(int num[2][2]);
int main()
{
Declaration of strings
int num[2][2], i, j;
Before we actually work with strings, we need
printf("Enter 4 numbers:\n");
to declare them first. Strings are declared in a
for (i = 0; i < 2; ++i)
similar manner as arrays. Only difference is
for (j = 0; j < 2; ++j)
that, strings are of char type.
scanf("%d", &num[i][j]);
// passing multi-dimensional array to
Using arrays
displayNumbers function
char s[5];
displayNumbers(num);
return 0;
}

void displayNumbers(int num[2][2])


{ Using pointers
// Instead of the above line, Strings can also be declared using pointer.
// void displayNumbers(int num[][2]) is also char *p;
valid
int i, j; Initialization of strings
printf("Displaying:\n"); In C, string can be initialized in a number of
for (i = 0; i < 2; ++i) different ways.
for (j = 0; j < 2; ++j) For convenience and ease, both initialization
printf("%d\n", num[i][j]); and declaration are done in the same step.
}

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


37
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

Here, program ignores Ritchie because, scanf()


Using arrays function takes only a single string before the
char c[] = "abcd"; white space, i.e. Dennis.
OR,
char c[50] = "abcd"; Reading a line of text
OR, An approach to reading a full line of text is to
char c[] = {'a', 'b', 'c', 'd', '\0'}; read and store each character one by one.
OR,
char c[5] = {'a', 'b', 'c', 'd', '\0'}; Example #2: Using getchar() to read a line
of text

1. C program to read line of text character


The given string is initialized and stored in the by character.
form of arrays as above.
#include <stdio.h>
Using pointers int main()
String can also be initialized using pointers as: {
char *c = "abcd"; char name[30], ch;
int i = 0;
Reading Strings from user printf("Enter name: ");
You can use the scanf() function to read a while(ch != '\n') // terminates if user hit
string like any other data types. However, the enter
scanf() function only takes the first entered {
word. The function terminates when it ch = getchar();
encounters a white space (or just space). name[i] = ch;
i++;
Reading words from user }
char c[20]; name[i] = '\0'; // inserting null character
scanf("%s", c); at end
printf("Name: %s", name);
Example #1: Using scanf() to read a string return 0;
Write a C program to illustrate how to read }
string from terminal.
#include <stdio.h> In the program above, using the function
int main() getchar(), ch gets a single character from the
{ user each time. This process is repeated until
char name[20]; the user enters return (enter key). Finally, the
printf("Enter name: "); null character is inserted at the end to make it
scanf("%s", name); a string.
printf("Your name is %s.", name); This process to take string is tedious.
return 0;
} Example #3: Using standard library function
to read a line of text
Output
Enter name: Dennis Ritchie 2. C program to read line of text using
Your name is Dennis. gets() and puts()

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


38
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

To make life easier, there are predefined String handling functions


functions gets() and puts in C language to read You need to often manipulate strings
and display string respectively. according to the need of a problem. Most, if
not all, of the time string manipulation can be
#include <stdio.h> done manually but, this makes programming
int main() complex and large.
{ To solve this, C supports a large number of
char name[30]; string handling functions in the standard
printf("Enter name: "); library "string.h".
gets(name); //Function to read string from
user. Few commonly used string handling functions
printf("Name: "); are discussed below:
puts(name); //Function to display string. Function Work of Function
return 0; strlen() Calculates the length of string
} strcpy() Copies a string to another string
Both programs have the same output below: strcat() Concatenates(joins) two strings
strcmp() Compares two string
Output strlwr() Converts string to lowercase
Enter name: Tom Hanks strupr() Converts string to uppercase
Name: Tom Hanks Strings handling functions are defined under
"string.h" header file.
Passing Strings to Functions #include <string.h>
Strings are just char arrays. So, they can be Note: You have to include the code below to
passed to a function in a similar manner as run string handling functions.
arrays.
gets() and puts()
#include <stdio.h> Functions gets() and puts() are two string
void displayString(char str[]); functions to take string input from the user
and display it respectively as mentioned.
int main()
{ #include<stdio.h>
char str[50];
printf("Enter string: "); int main()
gets(str); {
displayString(str); // Passing string c to char name[30];
function. printf("Enter name: ");
return 0; gets(name); //Function to read string from
} user.
void displayString(char str[]){ printf("Name: ");
printf("String Output: "); puts(name); //Function to display string.
puts(str); return 0;
} }
Note: Though, gets() and puts() function
Here, string c is passed from main() function to handle strings, both these functions are
user-defined function displayString(). In defined in "stdio.h" header file.
function declaration, str[] is the formal
argument.

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


39
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

Pointers In above source code, value 5 is stored in the


memory location 2686778. var is just the name
given to that location.

Pointer variables
In C, there is a special variable that stores just
the address of another variable. It is called
Pointers are powerful features of C Pointer variable or, simply, a pointer.
programming that differentiates it from other
popular programming languages like: Java and Declaration of Pointer
Python. data_type* pointer_variable_name;
int* p;
Pointers are used in C program to access the
memory and manipulate the address. Above statement defines, p as pointer variable
of type int.
Address in C Reference operator (&) and Dereference
Before you get into the concept of pointers, operator (*)
let's first get familiar with address in C.
If you have a variable var in your program, As discussed, & is called reference operator.
&var will give you its address in the memory, It gives you the address of a variable.
where & is commonly called the reference Likewise, there is another operator that gets
operator. you the value from the address, it is called a
dereference operator (*).
You must have seen this notation while using Below example clearly demonstrates the use of
scanf() function. It was used in the function to pointers, reference operator and dereference
store the user inputted value in the address of operator.
var.
scanf("%d", &var); Note: The * sign when declaring a pointer is
not a dereference operator. It is just a similar
/* Example to demonstrate use of reference notation that creates a pointer.
operator in C programming. */
Example To Demonstrate Working of
#include <stdio.h> Pointers
int main() /* Source code to demonstrate, handling of
{ pointers in C program */
int var = 5;
printf("Value: %d\n", var); #include <stdio.h>
printf("Address: %u", &var); //Notice, the int main(){
ampersand(&) before var. int* pc;
return 0; int c;
} c=22;
printf("Address of c:%u\n",&c);
Output printf("Value of c:%d\n\n",c);
Value: 5 pc=&c;
Address: 2686778 printf("Address of pointer pc:%u\n",pc);
printf("Content of pointer pc:%d\n\n",*pc);
Note: You may obtain different value of c=11;
address while using this code. printf("Address of pointer pc:%u\n",pc);

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


40
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

printf("Content of pointer pc:%d\n\n",*pc); 5. Since, pointer pc points to the same


*pc=2; address as c, value pointed by pointer pc is
printf("Address of c:%u\n",&c); 11 as well. Printing the address and content
printf("Value of c:%d\n\n",c); of pc shows the updated content as 11.
return 0; 6. *pc=2; changes the contents of the
} memory location pointed by pointer pc to
2. Since the address of pointer pc is same
Output as address of c, value of c also changes to
Address of c: 2686784 2.
Value of c: 22
Common mistakes when working with
Address of pointer pc: 2686784 pointers
Content of pointer pc: 22 Suppose, you want pointer pc to point to the
address of c. Then,
Address of pointer pc: 2686784
Content of pointer pc: 11 int c, *pc;
// Wrong! pc is address whereas, c is not an
Address of c: 2686784 address.
Value of c: 2
pc = c;
// Wrong! *pc is the value pointed by address
whereas, %amp;c is an address.
*pc = &c;
// Correct! pc is an address and, %amp;pc is
Explanation of program and figure also an address.
1. int* pc; creates a pointer pc and int c; pc = &c;
creates a normal variable c. // Correct! *pc is the value pointed by address
Since pc and c are both not initialized, and, c is also a value.
pointer pc points to either no address or a *pc = c;
random address. Likewise, variable c is In both cases, pointer pc is not pointing to the
assigned an address but contains a address of c.
random/garbage value.
2. c=22; assigns 22 to the variable c, i.e., 22 is Pointers and Arrays
stored in the memory location of variable
c.
Note that, when printing &c (address of c),
we use %u rather than %d since address is
usually expressed as an unsigned integer
(always positive).
3. pc=&c; assigns the address of variable to c
Arrays are closely related to pointers in C
to the pointer pc.
programming but the important difference
When printing, you see value of pc is the between them is that, a pointer variable takes
same as the address of c and the content different addresses as value whereas, in case of
of pc (*pc) is 22 as well.
array it is fixed.
4. c=11; assigns 11 to variable c.
We assign a new value to c to see its effect
This can be demonstrated by an example:
on pointer pc. #include <stdio.h>

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


41
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

int main() Similarly,


{ &arr[1] is equivalent to (arr + 1) AND, arr[1]
char charArr[4]; is equivalent to *(arr + 1).
int i; &arr[2] is equivalent to (arr + 2) AND, arr[2]
is equivalent to *(arr + 2).
for(i = 0; i < 4; ++i) &arr[3] is equivalent to (arr + 3) AND, arr[3]
{ is equivalent to *(arr + 3).
printf("Address of charArr[%d] = %u\n", i,
&charArr[i]);
} &arr[i] is equivalent to (arr + i) AND, arr[i] is
equivalent to *(arr + i).
return 0;
} In C, you can declare an array and can use
When you run the program, the output will be: pointer to alter the data of an array.
Address of charArr[0] = 28ff44
Address of charArr[1] = 28ff45 Example: Program to find the sum of six
Address of charArr[2] = 28ff46 numbers with arrays and pointers
Address of charArr[3] = 28ff47
#include <stdio.h>
Note: You may get different address of an int main()
array. {
Notice, that there is an equal difference int i, classes[6],sum = 0;
(difference of 1 byte) between any two printf("Enter 6 numbers:\n");
consecutive elements of array charArr. for(i = 0; i < 6; ++i)
But, since pointers just point at the location of {
another variable, it can store any address. // (classes + i) is equivalent to &classes[i]
scanf("%d",(classes + i));
Relation between Arrays and Pointers
Consider an array: // *(classes + i) is equivalent to classes[i]
int arr[4]; sum += *(classes + i);
}
printf("Sum = %d", sum);
return 0;
}

In C programming, name of the array always Output


points to address of the first element of an Enter 6 numbers:
array. 2
3
In the above example, arr and &arr[0] points 4
to the address of the first element. 5
&arr[0] is equivalent to arr 3
Since, the addresses of both are the same, the 4
values of arr and &arr[0] are also the same. Sum = 21
arr[0] is equivalent to *arr (value of an address
of the pointer)

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


42
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

C Call by Reference: Using pointers pointers *n1 and *n2 accept those values. So,
now the pointer n1 and n2 points to the
address of num1 and num2 respectively.

When, the value of pointers are changed, the


value in the pointed memory location also
When a pointer is passed as an argument to a changes correspondingly. Hence, changes
function, address of the memory location is made to *n1 and *n2 are reflected in num1
passed instead of the value. This is because, and num2 in the main function.
pointer stores the location of the memory, and
not the value. This technique is known as Call by Reference
in C programming.
Example of Pointer and Functions
Program to swap two number using call by Module 5
reference. Functions
/* C Program to swap two numbers using A function is a block of code that performs a
pointers and function. */ specific task.
#include <stdio.h> Suppose, a program related to graphics needs
void swap(int *n1, int *n2); to create a circle and color it depending upon
the radius and color from the user.
int main()
{ You can create two functions to solve this
int num1 = 5, num2 = 10; problem:
• create a circle function
// address of num1 and num2 is passed to • color function
the swap function Dividing complex problem into small
swap( &num1, &num2); components makes program easy to
printf("Number1 = %d\n", num1); understand and use.
printf("Number2 = %d", num2);
return 0; Types of functions in C programming
} Depending on whether a function is defined by
the user or already included in C compilers,
void swap(int * n1, int * n2) there are two types of functions in C
{ programming
// pointer n1 and n2 points to the address
of num1 and num2 respectively There are two types of functions in C
int temp; programming:
temp = *n1; • Standard library functions
*n1 = *n2; • User defined functions
*n2 = temp;
} Standard library functions
The standard library functions are built-in
Output functions in C programming to handle tasks
Number1 = 10 such as mathematical computations, I/O
Number2 = 5 processing, string handling etc.

The address of memory location num1 and


num2 are passed to the function swap and the

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


43
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

These functions are defined in the header file. When the compiler encounters
When you include the header file, these functionName(); inside the main function,
functions are available for use. control of the program jumps to
void functionName()
For example: And, the compiler starts executing the codes
The printf() is a standard library function to inside the user-defined function.
send formatted output to the screen (display
output on the screen). This function is defined The control of the program jumps to
in "stdio.h" header file. statement next to functionName(); once all the
codes inside the function definition are
There are other numerous library functions executed.
defined under "stdio.h", such as scanf(),
fprintf(), getchar() etc. Once you include
"stdio.h" in your program, all these functions
are available for use.

User-defined functions
C allow programmers to define functions. Such
functions created by the user are called user-
defined functions.

Depending upon the complexity and


requirement of the program, you can create as
many user-defined functions as you want.
Remember, function name is an identifier and
Working of user-defined function should be unique.
#include <stdio.h> This is just an overview on user-defined
void functionName() function. Visit these pages to learn more on:
{ • User-defined Function in C
... .. ... programming
... .. ... • Types of user-defined Functions
}
Advantages of user-defined function
int main() 1. The program will be easier to
{ understand, maintain and debug.
... .. ... 2. Reusable codes that can be used in
... .. ... other programs
3. A large program can be divided into
functionName(); smaller modules. Hence, a large project
can be divided among many
... .. ... programmers.
... .. ...
} User-defined functions
Now learn to create user-defined functions in
The execution of a C program begins from the C programming in this article.
main() function.
A function is a block of code that performs a
specific task.

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


44
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

C allows you to define functions according to parameters and return type. It doesn't contain
your need. These functions are known as user- function body.
defined functions.
A function prototype gives information to the
compiler that the function may later be used
For example: in the program.
Suppose, you need to create a circle and color
it depending upon the radius and color. You
can create two functions to solve this problem: Syntax of function prototype
• createCircle() function returnType functionName(type1 arg1,
• color() function type2 argt2,...);

Example: User-defined function In the above example, int addNumbers(int a,


Here is a example to add two integers. To int b); is the function prototype which provides
perform this task, a user-defined function following information to the compiler:
addNumbers() is defined. 1. name of the function is addNumbers()
2. return type of the function is int
#include <stdio.h> 3. two arguments of type int are passed to
the function
int addNumbers(int a, int b); // function The function prototype is not needed if the
prototype user-defined function is defined before the
main() function.
int main()
{ Calling a function
int n1,n2,sum; Control of the program is transferred to the
user-defined function by calling it.
printf("Enters two numbers: ");
scanf("%d %d",&n1,&n2); Syntax of function call
functionName(arg1, arg2, ...);
sum = addNumbers(n1, n2); // function In the above example, function call is made
call using addNumbers(n1,n2); statement inside
the main().
printf("sum = %d",sum);
Function definition
return 0; Function definition contains the block of code
} to perform a specific task i.e. in this case,
adding two numbers and returning it.
int addNumbers(int a,int b) // function
definition Syntax of function definition
{ returnType functionName(type1 arg1,
int result; type2 argt2, ...)
result = a+b; {
return result; // return statement //body of the function
} }

Function prototype When a function is called, the control of the


A function prototype is simply the declaration program is transferred to the function
of a function that specifies function's name,

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


45
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

definition. And, the compiler starts executing


the codes inside the body of a function.

Passing arguments to a function


In programming, argument refers to the
variable passed to the function. In the above
example, two variables n1 and n2 are passed
during function call.

The parameters a and b accepts the passed


arguments in the function definition. These
arguments are called formal parameters of the
function.
Syntax of return statement
return (expression);

For example,
return a;
return (a+b);

The type of value returned from the function


and the return type specified in function
prototype and function definition must match.

Types of User-defined Functions in C


Programming
For better understanding of arguments and
return value from the function, user-defined
The type of arguments passed to a function functions can be categorized as:
and the formal parameters must match, • Function with no arguments and no return
otherwise the compiler throws error. value
• Function with no arguments and a return
If n1 is of char type, a also should be of char value
type. If n2 is of float type, variable b also • Function with arguments and no return
should be of float type. value
A function can also be called without passing • Function with arguments and a return
an argument. value.

Return Statement The 4 programs below check whether an


The return statement terminates the execution integer entered by the user is a prime number
of a function and returns a value to the calling or not. And, all these programs generate the
function. The program control is transferred to same output.
the calling function after return statement.
In the above example, the value of variable Example #1: No arguments passed and no
result is returned to the variable sum in the return Value
main() function. The checkPrimeNumber() function takes input
from the user, checks whether it is a prime
number or not and displays it on the screen.

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


46
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

#include <stdio.h> Here, the getInteger() function takes input


from the user and returns it. The code to check
void checkPrimeNumber(); whether a number is prime or not is inside the
main() function.
int main()
{ #include <stdio.h>
checkPrimeNumber(); // no argument is int getInteger();
passed to prime()
return 0; int main()
} {
int n, i, flag = 0;
// return type of the function is void becuase
no value is returned from the function // no argument is passed to the function
void checkPrimeNumber() // the value returned from the function is
{ assigned to n
int n, i, flag=0; n = getInteger();

printf("Enter a positive integer: "); for(i=2; i<=n/2; ++i)


scanf("%d",&n); {
if(n%i==0){
for(i=2; i <= n/2; ++i) flag = 1;
{ break;
if(n%i == 0) }
{ }
flag = 1;
} if (flag == 1)
} printf("%d is not a prime number.", n);
if (flag == 1) else
printf("%d is not a prime number.", n); printf("%d is a prime number.", n);
else
printf("%d is a prime number.", n); return 0;
} }

The empty parentheses in // getInteger() function returns integer


checkPrimeNumber(); statement inside the entered by the user
main() function indicates that no argument is int getInteger()
passed to the function. {
int n;
The return type of the function is void. Hence,
no value is returned from the function. printf("Enter a positive integer: ");
scanf("%d",&n);
Example #2: No arguments passed but a
return value return n;
The empty parentheses in n = getInteger(); }
statement indicates that no argument is
passed to the function. And, the value returned
from the function is assigned to n.

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


47
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

Example #3: Argument passed but no #include <stdio.h>


return value int checkPrimeNumber(int n);
The integer value entered by the user is passed
to checkPrimeAndDisplay() function. int main()
{
#include <stdio.h> int n, flag;
void checkPrimeAndDisplay(int n);
printf("Enter a positive integer: ");
int main() scanf("%d",&n);
{
int n; // n is passed to the checkPrimeNumber()
function
printf("Enter a positive integer: "); // the value returned from the function is
scanf("%d",&n); assigned to flag variable
flag = checkPrimeNumber(n);
// n is passed to the function
checkPrimeAndDisplay(n); if(flag==1)
printf("%d is not a prime number",n);
return 0; else
} printf("%d is a prime number",n);

// void indicates that no value is returned from return 0;


the function }
void checkPrimeAndDisplay(int n)
{ // integer is returned from the function
int i, flag = 0; int checkPrimeNumber(int n)
{
for(i=2; i <= n/2; ++i) /* Integer value is returned from function
{ checkPrimeNumber() */
if(n%i == 0){ int i;
flag = 1;
break; for(i=2; i <= n/2; ++i)
} {
} if(n%i == 0)
if(flag == 1) return 1;
printf("%d is not a prime number.",n); }
else
printf("%d is a prime number.", n); return 0;
} }
Here, the checkPrimeAndDisplay() function
checks whether the argument passed is a The checkPrimeNumber() function checks
prime number or not and displays the whether the passed argument is prime or not.
appropriate message. If the passed argument is a prime number, the
function returns 0. If the passed argument is a
Example #4: Argument passed and a return non-prime number, the function returns 1. The
value return value is assigned to flag variable.
The input from the user is passed to
checkPrimeNumber() function.

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


48
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

Then, the appropriate message is displayed Example: Sum of Natural Numbers Using
from the main() function. Recursion

A function should perform a specific task. The #include <stdio.h>


checkPrimeNumber() function doesn't take int sum(int n);
input from the user nor it displays the
appropriate message. It only checks whether a int main()
number is prime or not, which makes code {
modular, easy to understand and debug. int number, result;

Recursion printf("Enter a positive integer: ");


A function that calls itself is known as a scanf("%d", &number);
recursive function. And, this technique is
known as recursion. result = sum(number);

Working of recursion printf("sum=%d", result);


void recurse() }
{
... .. ... int sum(int num)
recurse(); {
... .. ... if (num!=0)
} return num + sum(num-1); // sum()
function calls itself
int main() else
{ return num;
... .. ... }
recurse();
... .. ... Output
} Enter a positive integer:
3
6

Initially, the sum() is called from the main()


function with number passed as an argument.

Suppose, the value of num is 3 initially. During


next function call, 2 is passed to the sum()
function. This process continues until num is
equal to 0.

The recursion continues until some condition


When num is equal to 0, the if condition fails
is met to prevent it. To prevent infinite
and the else part is executed returning the sum
recursion, if...else statement (or similar
of integers to the main() function.
approach) can be used where one branch
makes the recursive call and other doesn't.

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


49
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

Local Variable
The variables declared inside the function are
automatic or local variables.
The local variables exist only inside the
function in which it is declared. When the
function exits, the local variables are
destroyed.

int main() {
int n; // n is a local variable to main()
function
... .. ...
}

void func() {
int n1; // n1 is local to func() function
}

In the above code, n1 is destroyed when func()


exits. Likewise, n gets destroyed when main()
exits.

Global Variable
Variables that are declared outside of all
Advantages and Disadvantages of
functions are known as external variables.
Recursion
External or global variables are accessible to
Recursion makes program elegant and
any function.
cleaner. All algorithms can be defined
recursively which makes it easier to visualize
Example #1: External Variable
and prove.
#include <stdio.h>
void display();
If the speed of the program is vital then, you
should avoid using recursion. Recursions use
int n = 5; // global variable
more memory and are generally slow. Instead,
you can use loop.
int main()
{
Scope and Lifetime of a variable
++n; // variable n is not declared in the
Every variable in C programming has two
main() function
properties: type and storage class.
display();
return 0;
Type refers to the data type of a variable. And,
}
storage class determines the scope and
lifetime of a variable.
void display()
There are 4 types of storage class:
{
1. automatic
++n; // variable n is not declared in the
2. external
display() function
3. static
printf("n = %d", n);
4. register
}

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


50
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

Output Output
n=7 0 5

Suppose, a global variable is declared in file1. During the first function call, the value of c is
If you try to use that variable in a different file equal to 0. Then, it's value is increased by 5.
file2, the compiler will complain. To solve this
problem, keyword extern is used in file2 to During the second function call, variable c is
indicate that the external variable is declared not initialized to 0 again. It's because c is a
in another file. static variable. So, 5 is displayed on the screen.

Register Variable Structure


The register keyword is used to declare Structure is a collection of variables of different
register variables. Register variables were types under a single name.
supposed to be faster than local variables.
For example: You want to store some
However, modern compilers are very good at information about a person: his/her name,
code optimization and there is a rare chance citizenship number and salary. You can easily
that using register variables will make your create different variables name, citNo, salary to
program faster. store these information separately.

Unless you are working on embedded system However, in the future, you would want to
where you know how to optimize code for the store information about multiple persons.
given application, there is no use of register Now, you'd need to create different variables
variables. for each information per person: name1,
citNo1, salary1, name2, citNo2, salary2
Static Variable
A static variable is declared by using keyword You can easily visualize how big and messy the
static. For example; code would look. Also, since no relation
static int i; between the variables (information) would
The value of a static variable persists until the exist, it's going to be a daunting task.
end of the program.
A better approach will be to have a collection
Example #2: Static Variable of all related information under a single name
#include <stdio.h> Person, and use it for every person. Now, the
void display(); code looks much cleaner, readable and
efficient as well.
int main() This collection of all related information under
{ a single name Person is a structure.
display();
display(); Structure Definition in C
} Keyword struct is used for creating a structure.
void display()
{ Syntax of structure
static int c = 0; struct structure_name
printf("%d ",c); {
c += 5; data_type member1;
} data_type member2;
.

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


51
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

. Accessing members of a structure


data_type memeber; There are two types of operators used for
}; accessing members of a structure.
1. Member operator(.)
Note: Don't forget the semicolon }; in the 2. Structure pointer operator(->)
ending line.
We can create the structure for a person as Any member of a structure can be accessed as:
mentioned above as: structure_variable_name.member_name
struct person
{ Suppose, we want to access salary for variable
char name[50]; person2. Then, it can be accessed as:
int citNo; person2.salary
float salary;
}; Example of structure
This declaration above creates the derived Write a C program to add two distances
data type struct person. entered by user. Measurement of distance
should be in inch and feet. (Note: 12 inches
Structure variable declaration = 1 foot)
When a structure is defined, it creates a user-
defined type but, no storage or memory is #include <stdio.h>
allocated. struct Distance
For the above structure of a person, variable {
can be declared as: int feet;
struct person float inch;
{ } dist1, dist2, sum;
char name[50];
int citNo; int main()
float salary; {
}; printf("1st distance\n");

int main() // Input of feet for structure variable dist1


{ printf("Enter feet: ");
struct person person1, person2, scanf("%d", &dist1.feet);
person3[20];
return 0; // Input of inch for structure variable dist1
} printf("Enter inch: ");
Another way of creating a structure variable is: scanf("%f", &dist1.inch);
struct person
{ printf("2nd distance\n");
char name[50]; // Input of feet for structure variable dist2
int citNo; printf("Enter feet: ");
float salary; scanf("%d", &dist2.feet);
} person1, person2, person3[20];
// Input of feet for structure variable dist2
In both cases, two variables person1, person2 printf("Enter inch: ");
and an array person3 having 20 elements of scanf("%f", &dist2.inch);
type struct person are created.
sum.feet = dist1.feet + dist2.feet;

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


52
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

sum.inch = dist1.inch + dist2.inch; Structures within structures


Structures can be nested within other
if (sum.inch > 12) structures in C programming.
{ struct complex
//If inch is greater than 12, changing it {
to feet. int imag_value;
++sum.feet; float real_value;
sum.inch = sum.inch - 12; };
}
struct number
// printing sum of distance dist1 and dist2 {
printf("Sum of distances = %d\'-%.1f\"", struct complex comp;
sum.feet, sum.inch); int real;
return 0; } num1, num2;
}
Suppose, you want to access imag_value for
Output num2 structure variable then, following
1st distance structure member is used.
Enter feet: 12 num2.comp.imag_value
Enter inch: 7.9
2nd distance Passing structures to a function
Enter feet: 2 There are mainly two ways to pass structures
Enter inch: 9.8 to a function:
Sum of distances = 15'-5.7" 1. Passing by value
2. Passing by reference
Keyword typedef while using structure
Writing struct structure_name variable_name; Passing structure by value
to declare a structure variable isn't intuitive as A structure variable can be passed to the
to what it signifies, and takes some function as an argument as a normal variable.
considerable amount of development time. If structure is passed by value, changes made
So, developers generally use typedef to name to the structure variable inside the function
the structure as a whole. For example: definition does not reflect in the originally
typedef struct complex passed structure variable.
{
int imag; C program to create a structure student,
float real; containing name and roll and display the
} comp; information.

int main() #include <stdio.h>


{ struct student
comp comp1, comp2; {
} char name[50];
Here, typedef keyword is used in creating a int roll;
type comp (which is of type as struct };
complex).
Then, two structure variables comp1 and void display(struct student stu);
comp2 are created by this comp type.

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


53
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

// function prototype should be below to the void add(struct distance d1,struct distance d2,
structure declaration otherwise compiler struct distance *d3);
shows error
int main()
int main() {
{ struct distance dist1, dist2, dist3;
struct student stud;
printf("Enter student's name: "); printf("First distance\n");
scanf("%s", &stud.name); printf("Enter feet: ");
printf("Enter roll number:"); scanf("%d", &dist1.feet);
scanf("%d", &stud.roll); printf("Enter inch: ");
display(stud); // passing structure variable scanf("%f", &dist1.inch);
stud as argument
return 0; printf("Second distance\n");
} printf("Enter feet: ");
scanf("%d", &dist2.feet);
void display(struct student stu){ printf("Enter inch: ");
printf("Output\nName: %s",stu.name); scanf("%f", &dist2.inch);
printf("\nRoll: %d",stu.roll);
} add(dist1, dist2, &dist3);

Output //passing structure variables dist1 and dist2


Enter student's name: Kevin Amla by value whereas passing structure variable
Enter roll number: 149 dist3 by reference
Output printf("\nSum of distances = %d\'-%.1f\"",
Name: Kevin Amla dist3.feet, dist3.inch);
Roll: 149
return 0;
Passing structure by reference }
The memory address of a structure variable is void add(struct distance d1,struct distance d2,
passed to function while passing it by struct distance *d3)
reference. {
If structure is passed by reference, changes //Adding distances d1 and d2 and storing
made to the structure variable inside function it in d3
definition reflects in the originally passed d3->feet = d1.feet + d2.feet;
structure variable. d3->inch = d1.inch + d2.inch;

C program to add two distances (feet-inch if (d3->inch >= 12) { /* if inch is greater
system) and display the result without the or equal to 12, converting it to feet. */
return statement. d3->inch -= 12;
++d3->feet;
#include <stdio.h> }
struct distance }
{
int feet; Output
float inch; First distance
}; Enter feet: 12
Enter inch: 6.8

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


54
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

Second distance
Enter feet: 5 1. Referencing pointer to another address to
Enter inch: 7.5 access the memory
Consider an example to access structure's
Sum of distances = 18'-2.3" member through pointer.

In this program, structure variables dist1 and #include <stdio.h>


dist2 are passed by value to the add function typedef struct person
(because value of dist1 and dist2 does not {
need to be displayed in main function). int age;
float weight;
But, dist3 is passed by reference ,i.e, address };
of dist3 (&dist3) is passed as an argument.
int main()
Due to this, the structure pointer variable d3 {
inside the add function points to the address struct person *personPtr, person1;
of dist3 from the calling main function. So, personPtr = &person1; // Referencing
any change made to the d3 variable is seen in pointer to memory address of person1
dist3 variable in main function.
As a result, the correct sum is displayed in the printf("Enter integer: ");
output. scanf("%d",&(*personPtr).age);

Structure and Pointer printf("Enter number: ");


Structures can be created and accessed using scanf("%f",&(*personPtr).weight);
pointers. A pointer variable of a structure can
be created as below: printf("Displaying: ");
struct name {
member1; printf("%d%f",(*personPtr).age,(*personPtr).w
member2; eight);
.
. return 0;
}; }

int main() In this example, the pointer variable of type


{ struct person is referenced to the address of
struct name *ptr; person1. Then, only the structure member
} through pointer can can accessed.

Here, the pointer variable of type struct name Using -> operator to access structure
is created. pointer member
Structure pointer member can also be
Accessing structure's member through accessed using -> operator.
pointer (*personPtr).age is same as personPtr->age
A structure's member can be accesssed (*personPtr).weight is same as personPtr-
through pointer in two ways: >weight
1. Referencing pointer to another address
to access memory
2. Using dynamic memory allocation

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


55
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

return 0;
2. Accessing structure member through }
pointer using dynamic memory allocation
To access structure member using pointers, Output
memory can be allocated dynamically using Enter number of persons: 2
malloc() function defined under "stdlib.h" Enter name, age and weight of the person
header file. respectively:
Syntax to use malloc() Adam
ptr = (cast-type*) malloc(byte-size) 2
3.2
Example to use structure's member Enter name, age and weight of the person
through pointer using malloc() function. respectively:
Eve
#include <stdio.h> 6
#include <stdlib.h> 2.3
struct person { Displaying Information:
int age; Adam 2 3.20
float weight; Eve 6 2.30
char name[30];
}; Pass structure to a function
In C, structure can be passed to functions by
int main() two methods:
{ 1. Passing by value (passing actual value
struct person *ptr; as argument)
int i, num; 2. Passing by reference (passing address
of an argument)
printf("Enter number of persons: ");
scanf("%d", &num); Passing structure by value
A structure variable can be passed to the
ptr = (struct person*) malloc(num * function as an argument as a normal variable.
sizeof(struct person));
// Above statement allocates the memory for If structure is passed by value, changes made
n structures with pointer personPtr pointing to to the structure variable inside the function
base address */ definition does not reflect in the originally
passed structure variable.
for(i = 0; i < num; ++i) C program to create a structure student,
{ containing name and roll and display the
printf("Enter name, age and weight of the information.
person respectively:\n");
scanf("%s%d%f", &(ptr+i)->name, #include <stdio.h>
&(ptr+i)->age, &(ptr+i)->weight); struct student
} {
char name[50];
printf("Displaying Infromation:\n"); int roll;
for(i = 0; i < num; ++i) };
printf("%s\t%d\t%.2f\n", (ptr+i)->name,
(ptr+i)->age, (ptr+i)->weight); void display(struct student stu);

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


56
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

// function prototype should be below to the


structure declaration otherwise compiler int main()
shows error {
struct distance dist1, dist2, dist3;
int main()
{ printf("First distance\n");
struct student stud; printf("Enter feet: ");
printf("Enter student's name: "); scanf("%d", &dist1.feet);
scanf("%s", &stud.name); printf("Enter inch: ");
printf("Enter roll number:"); scanf("%f", &dist1.inch);
scanf("%d", &stud.roll);
display(stud); // passing structure variable printf("Second distance\n");
stud as argument printf("Enter feet: ");
return 0; scanf("%d", &dist2.feet);
} printf("Enter inch: ");
void display(struct student stu){ scanf("%f", &dist2.inch);
printf("Output\nName: %s",stu.name);
printf("\nRoll: %d",stu.roll); add(dist1, dist2, &dist3);
}
//passing structure variables dist1 and dist2
Output by value whereas passing structure variable
Enter student's name: Kevin Amla dist3 by reference
Enter roll number: 149 printf("\nSum of distances = %d\'-%.1f\"",
Output dist3.feet, dist3.inch);
Name: Kevin Amla
Roll: 149 return 0;
}
Passing structure by reference void add(struct distance d1,struct distance d2,
The memory address of a structure variable is struct distance *d3)
passed to function while passing it by {
reference. //Adding distances d1 and d2 and storing
If structure is passed by reference, changes it in d3
made to the structure variable inside function d3->feet = d1.feet + d2.feet;
definition reflects in the originally passed d3->inch = d1.inch + d2.inch;
structure variable.
if (d3->inch >= 12) { /* if inch is greater
C program to add two distances (feet-inch or equal to 12, converting it to feet. */
system) and display the result without the d3->inch -= 12;
return statement. ++d3->feet;
}
#include <stdio.h> }
struct distance
{
int feet;
float inch; Output
}; First distance
void add(struct distance d1,struct distance d2, Enter feet: 12
struct distance *d3); Enter inch: 6.8

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


57
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

Second distance char name[50];


Enter feet: 5 int price;
Enter inch: 7.5 };

Sum of distances = 18'-2.3"


int main()
In this program, structure variables dist1 and {
dist2 are passed by value to the add function union car car1, car2, *car3;
(because value of dist1 and dist2 does not return 0;
need to be displayed in main function). }

But, dist3 is passed by reference ,i.e, address of In both cases, union variables car1, car2 and
dist3 (&dist3) is passed as an argument. union pointer variable car3 of type union car
Due to this, the structure pointer variable d3 is created.
inside the add function points to the address
of dist3 from the calling main function. So, any Accessing members of a union
change made to the d3 variable is seen in dist3 Again, the member of unions can be accessed
variable in main function. in similar manner as structures.

As a result, the correct sum is displayed in the In the above example, suppose you want to
output. access price for union variable car1, it can be
accessed as:
Unions car1.price
Unions are quite similar to structures in C. Like Likewise, if you want to access price for the
structures, unions are also derived types. union pointer variable car3, it can be accessed
as:
union car (*car3).price
{ or;
char name[50]; car3->price
int price;
}; Difference between union and structure
Though unions are similar to structure in so
Defining a union is as easy as replacing the many ways, the difference between them is
keyword struct with the keyword union. crucial to understand.

Creating Union Variables The primary difference can be demonstrated


Union variables can be created in similar by this example:
manner as structure variables.
union car #include <stdio.h>
{ union unionJob
char name[50]; {
int price; //defining a union
} car1, car2, *car3; char name[32];
float salary;
OR int workerNo;
} uJob;
union car
{ struct structJob

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


58
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

{ But, in the case of union, only one of its


char name[32]; members can be accessed at a time and all
float salary; other members will contain garbage values.
int workerNo;
} sJob; #include <stdio.h>
union job
int main() {
{ char name[32];
printf("size of union = %d", sizeof(uJob)); float salary;
printf("\nsize of structure = %d", int workerNo;
sizeof(sJob)); } job1;
return 0;
} int main()
{
Output printf("Enter name:\n");
size of union = 32 scanf("%s", &job1.name);
size of structure = 40
printf("Enter salary: \n");
More memory is allocated to structures scanf("%f", &job1.salary);
than union
As seen in the above example, there is a printf("Displaying\nName :%s\n",
difference in memory allocation between job1.name);
union and structure. printf("Salary: %.1f", job1.salary);

The amount of memory required to store a return 0;


structure variable is the sum of memory size of }
all members.
Output
Enter name
Hillary
Enter salary
1234.23
Displaying
But, the memory required to store a union Name: f%Bary
variable is the memory required for the largest Salary: 1234.2
element of an union. Note: You may get different garbage value or
empty string for the name.

Initially in the program, Hillary is stored in


job1.name and all other members of job1, i.e.
salary, workerNo, will contain garbage values.
Only one union member can be accessed at But, when user enters the value of salary,
a time 1234.23 will be stored in job1.salary and other
In the case of structure, all of its members can members, i.e. name, workerNo, will now
be accessed at any time. contain garbage values.
Thus in the output, salary is printed accurately
but, name displays some random string.

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


59
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

Passing Union to a Function Here, ptr is pointer of cast-type. The malloc()


Union can be passed in similar manner as function returns a pointer to an area of
structures in C programming. memory with size of byte size. If the space is
insufficient, allocation fails and returns NULL
Dynamic Memory Allocation pointer.
In C, the exact size of array is unknown until ptr = (int*) malloc(100 * sizeof(int));
compile time, i.e., the time when a compiler
compiles your code into a computer This statement will allocate either 200 or 400
understandable language. So, sometimes the according to size of int 2 or 4 bytes
size of the array can be insufficient or more respectively and the pointer points to the
than required. address of first byte of memory.

Dynamic memory allocation allows your calloc()


program to obtain more memory space while The name calloc stands for "contiguous
running, or to release it if it's not required. allocation".
The only difference between malloc() and
In simple terms, Dynamic memory allocation calloc() is that, malloc() allocates single block
allows you to manually handle memory space of memory whereas calloc() allocates multiple
for your program. blocks of memory each of same size and sets
all bytes to zero.
Although, C language inherently does not
have any technique to allocate memory Syntax of calloc()
dynamically, there are 4 library functions under ptr = (cast-type*)calloc(n, element-size);
"stdlib.h" for dynamic memory allocation. This statement will allocate contiguous space
in memory for an array of n elements.
Function Use of Function
Allocates requested size of For example:
malloc() bytes and returns a pointer first ptr = (float*) calloc(25, sizeof(float));
byte of allocated space This statement allocates contiguous space in
Allocates space for an array memory for an array of 25 elements each of
elements, initializes to zero and size of float, i.e, 4 bytes.
calloc()
then returns a pointer to
memory free()
deallocate the previously Dynamically allocated memory created with
free() either calloc() or malloc() doesn't get freed on
allocated space
Change the size of previously its own. You must explicitly use free() to release
realloc() the space.
allocated space

malloc() Syntax of free()


The name malloc stands for "memory free(ptr);
allocation". This statement frees the space allocated in the
The function malloc() reserves a block of memory pointed by ptr.
memory of specified size and return a pointer
of type void which can be casted into pointer Example #1: Using C malloc() and free()
of any form.
Write a C program to find sum of n
Syntax of malloc() elements entered by user. To perform this
ptr = (cast-type*) malloc(byte-size)

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


60
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

program, allocate memory dynamically ptr = (int*) calloc(num, sizeof(int));


using malloc() function. if(ptr == NULL)
{
#include <stdio.h> printf("Error! memory not allocated.");
#include <stdlib.h> exit(0);
}
int main()
{ printf("Enter elements of array: ");
int num, i, *ptr, sum = 0; for(i = 0; i < num; ++i)
{
printf("Enter number of elements: "); scanf("%d", ptr + i);
scanf("%d", &num); sum += *(ptr + i);
}
ptr = (int*) malloc(num * sizeof(int));
//memory allocated using malloc printf("Sum = %d", sum);
if(ptr == NULL) free(ptr);
{ return 0;
printf("Error! memory not allocated."); }
exit(0);
} realloc()
If the previously allocated memory is
printf("Enter elements of array: "); insufficient or more than required, you can
for(i = 0; i < num; ++i) change the previously allocated memory size
{ using realloc().
scanf("%d", ptr + i);
sum += *(ptr + i); Syntax of realloc()
} ptr = realloc(ptr, newsize);

printf("Sum = %d", sum); Here, ptr is reallocated with size of newsize.


free(ptr);
return 0; Example #3: Using realloc()
} #include <stdio.h>
#include <stdlib.h>
Example #2: Using C calloc() and free()
Write a C program to find sum of n int main()
elements entered by user. To perform this {
program, allocate memory dynamically int *ptr, i , n1, n2;
using calloc() function. printf("Enter size of array: ");
scanf("%d", &n1);
#include <stdio.h>
#include <stdlib.h> ptr = (int*) malloc(n1 * sizeof(int));

int main() printf("Address of previously allocated


{ memory: ");
int num, i, *ptr, sum = 0; for(i = 0; i < n1; ++i)
printf("Enter number of elements: "); printf("%u\t",ptr + i);
scanf("%d", &num);
printf("\nEnter new size of array: ");

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


61
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

scanf("%d", &n2); Binary files


ptr = realloc(ptr, n2); Binary files are mostly the .bin files in your
for(i = 0; i < n2; ++i) computer. Instead of storing data in plain text,
printf("%u\t", ptr + i); they store it in the binary form (0's and 1's).
return 0;
} They can hold higher amount of data, are not
ADVANCE C readable easily and provides a better security
Files I/O than text files.
There are a large number of functions to
handle file I/O (Input Output) in C. you will File Operations
learn to handle standard I/O in C using In C, you can perform four major operations on
fprintf(), fscanf(), fread(), fwrite(), fseek.and the file, either text or binary:
more. 1. Creating a new file
2. Opening an existing file
In C programming, file is a place on your 3. Closing a file
physical disk where information is stored. 4. Reading from and writing information
to a file
Need for Files
• When a program is terminated, the Working with files
entire data is lost. Storing in a file will When working with files, you need to declare
preserve your data even if the program a pointer of type file. This declaration is
terminates. needed for communication between the file
• If you have to enter a large number of and program.
data, it will take a lot of time to enter
them all. FILE *fptr
However, if you have a file containing
all the data, you can easily access the Opening a file - for creation and edit
contents of the file using few Opening a file is performed using the library
commands in C. function in the "stdio.h" header file: fopen().
• You can easily move your data from one
computer to another without any The syntax for opening a file in standard I/O is:
changes. ptr = fopen("fileopen","mode")

Types of Files For Example:


When dealing with files, there are two types of fopen("E:\\cprogram\\newprogram.txt","
files you should know about: w");
1. Text files fopen("E:\\cprogram\\oldprogram.bin","r
2. Binary files b");

Text files • Let's suppose the


Text files are the normal .txt files that you can file newprogram.txt doesn't exist in the
easily create using Notepad or any simple text location E:\cprogram. The first function
editors. When you open those files, you'll see creates a new file
all the contents within the file as plain text. You named newprogram.txt and opens it for
can easily edit or delete the contents. They writing as per the mode 'w'.
take minimum effort to maintain, are easily The writing mode allows you to create and
readable, and provide least security and takes edit (overwrite) the contents of the file.
bigger storage space.

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


62
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

• Now let's suppose the second binary Open for


file oldprogram.bin exists in the both
If the file does not
location E:\cprogram. The second function reading
rb+ exist, fopen() returns
opens the existing file for reading in binary and writing
NULL.
mode 'rb'. in binary
The reading mode only allows you to read mode.
the file, you cannot write into the file. Open for If the file exists, its
both contents are
Opening Modes in Standard I/O w+ reading overwritten. If the file
File Meaning During Inexistence of and does not exist, it will be
Mode of Mode file writing. created.
If the file does not Open for
Open for If the file exists, its
r exist, fopen() returns both
reading. contents are
NULL. reading
wb+ overwritten. If the file
Open for and writing
If the file does not does not exist, it will be
reading in in binary
rb exist, fopen() returns created.
binary mode.
NULL.
mode. Open for
If the file exists, its both
If the file does not
contents are a+ reading
Open for exists, it will be created.
w overwritten. If the file and
writing.
does not exist, it will be appending.
created. Open for
If the file exists, its both
Open for
contents are reading
writing in If the file does not
wb overwritten. If the file ab+ and
binary exists, it will be created.
does not exist, it will be appending
mode.
created. in binary
Open for mode.
append.
If the file does not
a i.e, Data is Closing a File
exists, it will be created.
added to The file (both text and binary) should be closed
end of file. after reading/writing.
Open for Closing a file is performed using library
append in function fclose().
binary
If the file does not
ab mode. i.e, fclose(fptr);
exists, it will be created.
Data is //fptr is the file pointer associated with file
added to to be closed.
end of file.
Open for Reading and writing to a text file
both If the file does not For reading and writing to a text file, we use
r+ reading exist, fopen() returns the functions fprintf() and fscanf().
and NULL.
writing. They are just the file versions
of printf() and scanf(). The only difference is
that, fprint and fscanf expects a pointer to the
structure FILE.

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


63
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

Writing to a text file // Program exits if the file pointer returns


NULL.
Example 1: Write to a text file using exit(1);
fprintf() }
This program takes a number from user and
stores in the file program.txt. fscanf(fptr,"%d", &num);

#include <stdio.h> printf("Value of n=%d", num);


int main() fclose(fptr);
{
int num; return 0;
FILE *fptr; }
fptr = fopen("C:\\program.txt","w");
This program reads the integer present in
if(fptr == NULL) the program.txt file and prints it onto the
{ screen.
printf("Error!");
exit(1); If you successfully created the file
} from Example 1, running this program will get
you the integer you entered.
printf("Enter num: ");
scanf("%d",&num); Other functions like fgetchar(), fputc() etc. can
be used in similar way.
fprintf(fptr,"%d",num);
fclose(fptr); Reading and writing to a binary file
Functions fread() and fwrite() are used for
return 0; reading from and writing to a file on the disk
} respectively in case of binary files.

After you compile and run this program, you Writing to a binary file
can see a text file program.txt created in C To write into a binary file, you need to use the
drive of your computer. When you open the function fwrite(). The functions takes four
file, you can see the integer you entered. arguments: Address of data to be written in
disk, Size of data to be written in disk, number
Reading from a text file of such type of data and pointer to the file
Example 2: Read from a text file using where you want to write.
fscanf()
fwrite(address_data, size_data,
#include <stdio.h> numbers_data, pointer_to_file);
int main()
{ Example 3: Writing to a binary file using
int num; fwrite()
FILE *fptr;
#include <stdio.h>
if ((fptr = fopen("C:\\program.txt","r")) ==
NULL){ struct threeNum
printf("Error! opening file"); {

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


64
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

int n1, n2, n3;


}; Reading from a binary file
Function fread() also take 4 arguments similar
int main() to fwrite() function as above.
{
int n; fread(address_data, size_data,
struct threeNum num; numbers_data, pointer_to_file);
FILE *fptr;
Example 4: Reading from a binary file using
if ((fptr = fopen("C:\\program.bin","wb")) == fread()
NULL){
printf("Error! opening file"); #include <stdio.h>

// Program exits if the file pointer returns struct threeNum


NULL. {
exit(1); int n1, n2, n3;
} };

for(n = 1; n < 5; ++n) int main()


{ {
num.n1 = n; int n;
num.n2 = 5n; struct threeNum num;
num.n3 = 5n + 1; FILE *fptr;
fwrite(&num, sizeof(struct threeNum), 1,
fptr); if ((fptr = fopen("C:\\program.bin","rb")) ==
} NULL){
fclose(fptr); printf("Error! opening file");

return 0; // Program exits if the file pointer returns


} NULL.
exit(1);
In this program, you create a new }
file program.bin in the C drive.
We declare a structure threeNum with three for(n = 1; n < 5; ++n)
numbers - n1, n2 and n3, and define it in the {
main function as num. fread(&num, sizeof(struct threeNum), 1,
Now, inside the for loop, we store the value fptr);
into the file using fwrite. printf("n1: %d\tn2: %d\tn3: %d", num.n1,
num.n2, num.n3);
The first parameter takes the address }
of num and the second parameter takes the fclose(fptr);
size of the structure threeNum.
return 0;
Since, we're only inserting one instance }
of num, the third parameter is 1. And, the last
parameter *fptr points to the file we're storing In this program, you read the same
the data. file program.bin and loop through the records
Finally, we close the file. one by one.

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


65
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

In simple terms, you read int n;


one threeNum record of threeNum size from struct threeNum num;
the file pointed by *fptr into the FILE *fptr;
structure num.
You'll get the same records you inserted in if ((fptr = fopen("C:\\program.bin","rb")) ==
Example 3. NULL){
printf("Error! opening file");
Getting data using fseek()
If you have many records inside a file and need // Program exits if the file pointer returns
to access a record at a specific position, you NULL.
need to loop through all the records before it exit(1);
to get the record. }
This will waste a lot of memory and operation
time. An easier way to get to the required data // Moves the cursor to the end of the file
can be achieved using fseek(). fseek(fptr, sizeof(struct threeNum),
As the name suggests, fseek() seeks the cursor SEEK_END);
to the given record in the file.
for(n = 1; n < 5; ++n)
Syntax of fseek() {
fseek(FILE * stream, long int offset, int fread(&num, sizeof(struct threeNum), 1,
whence) fptr);
The first parameter stream is the pointer to the printf("n1: %d\tn2: %d\tn3: %d", num.n1,
file. The second parameter is the position of num.n2, num.n3);
the record to be found, and the third }
parameter specifies the location where the fclose(fptr);
offset starts.
return 0;
Different Whence in fseek }
Whence Meaning
SEKK_SET Starts the offset from the This program will start reading the records
beginning of the file. from the file program.bin in the reverse order
SEKK_END Starts the offset from the end of (last to first) and prints it.
the file.
SEKK_CUR Starts the offset from the Lab Cycle
current location of the cursor in BCA/B.Sc. Computer Science/B.Sc. CA Tripe
the file. Main/B.Sc. IT

Example of fseek() Syllabus


1. Programs to familiarize printf() and scanf()
#include <stdio.h> functions.
2. Programs Based on Decision statements,
struct threeNum break, goto, continue, switch and Loop
{ controls statements.
int n1, n2, n3; 3. Programs Based on One dimensional and
}; two dimensional arrays.
4. Programs on Strings and string handling
int main() functions.
{

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


66
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

5. Programs based on Pointers, operations on 12. Find the Largest Number among Three
pointers, Arrays & Pointers, Numbers Entered by User
6. Programs based on functions, Call by value, 13. Find all Roots of a Quadratic equation
Call by reference, Recursion, 14. Check Whether the Entered Year is Leap
7. Programs based on structure and union, Year or not
array of structures, Pointer to structure, 15. Check Whether a Number is Positive or
structure and functions Negative or Zero.
8. Simple programs using pointers and 16. Checker Whether a Character is an
malloc(). Alphabet or not
17. Find Sum of Natural Numbers
Scheme of Evaluation for software lab I 18. Find Factorial of a Number
external is as follows: 19. Generate Multiplication Table
20. Display Fibonacci Series
Division of Marks (Practical - 3 hours 21. Find HCF of two Numbers
External) 22. Find LCM of two numbers entered by user
23. Count Number of Digits of an Integer
First program from part 1& 2 – 25 marks 24. Reverse a Number
1. Flowchart – 5 marks 25. Calculate the Power of a Number
2. Logic – 10 marks 26. Check Whether a Number is Palindrome or
3. Successful compilation – 5 marks Not
4. Result – 5 marks 27. Check Whether an Integer is Prime or Not
28. Display Prime Numbers Between Two
Second program should be based on Intervals
advanced concepts, part 3 to part 8 29. Check Armstrong Number
– 35 marks 30. Display Armstrong Number between Two
1. Logic – 20 marks Intervals
2. Successful compilation – 10 marks 31. Display Factors of a Number
3. Result – 5 marks 32. Print Pyramids and Triangles in C
Viva Voce – 10 marks programming using Loops
Lab Record (min 25 Programs) – 10 marks 33. Make a Simple Calculator to Add, Subtract,
Total Marks – 80 marks Multiply or Divide Using switch...case
34. Find the Frequency of Characters in a String
Lab Cycle 35. Find the Number of Vowels, Consonants,
1. Print a Sentence Digits and White space in a String
2. Print an Integer Entered by a User 36. Reverse a String by Passing it to Function
3. Add Two Integers Entered by User 37. Find the Length of a String
4. Multiply two Floating Point Numbers 38. Concatenate Two Strings
5. Find ASCII Value of Character Entered by 39. Copy a String
User 40. Remove all Characters in a String except
6. Find Quotient and Remainder of Two alphabet
Integers Entered by User 41. Sort Elements in Lexicographical Order
7. Find Size of int, float, double and char of (Dictionary Order)
your System 42. Change Decimal to Hexadecimal Number
8. Demonstrate the Working of Keyword long and Vice Versa
9. Swap Two numbers Entered by User 43. Convert Hexadecimal to Octal and Vice
10. Check Whether a Number is Even or Odd Versa
11. Check Whether a Character is Vowel or 44. Convert Binary Number to Hexadecimal
consonant Vice Versa

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]


67
CS1CRT02 Methodology Of Programming And C Language (Core) MG University, Kottayam

45. Find Largest Number Using Dynamic 73. Calculate Difference Between Two Time
Memory Allocation Period
46. Store Information Using Structures with 74. Store Information of 10 Students Using
Dynamically Memory Allocation Structure
47. Calculate Average Using Arrays 75. Store Information Using Structures for n
48. Find Largest Element of an Array Elements Dynamically
49. Calculate Standard Deviation
50. Add Two Matrix Using Multi-dimensional
Arrays
51. Multiply to Matrix Using Multi-dimensional
Arrays
52. Find Transpose of a Matrix
53. Check a matrix symmetric or not.
54. Multiply two Matrices by Passing Matrix to
Function
55. Sort Elements of an Array
56. Access Elements of an Array Using Pointer
57. Swap Numbers in Cyclic Order Using Call
by Reference
58. Find Largest Number Using Dynamic
Memory Allocation
59. Display all prime numbers between two
Intervals
60. Check Prime and Armstrong Number by
making function
61. Check whether a number can be expressed
as the sum of two prime number
62. Find sum of natural numbers using
recursion
63. Calculate factorial of a number using
recursion
64. Find G.C.D using recursion
65. Reverse a sentence using recursion
66. Calculate the power of a number using
recursion
67. Convert binary number to decimal and
vice-versa
68. Convert octal Number to decimal and vice-
versa
69. Convert binary number to octal and vice-
versa
70. Store Information(name, roll and marks) of
a Student Using Structure
71. Add Two Distances (in inch-feet) System
Using Structures
72. Add Two Complex Numbers by Passing
Structure to a Function

Eugin Lopez. F, Asst. Prof. in Computer, CAS, IHRD, Peerumade [email protected]

You might also like