2nd Sem c Material(2019)

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 63

DEPARTMENT OF COMPUTER SCIENCE

YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018


SAMALKOT

First B.Sc Computer Science


2nd Sem 2017-18

programming in c

Y Jagadeesh
Department of Computer Science
924 66 666 46
Kakinada

ADIKAVI NANNAYA UNIVERSITY, RAJAHMUNDRY

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
CBCS/Semester System (W.e.f. 2015-16 Admitted Batch)
II SEMESTER COMPUTER SCIENCE SYLLABUS
PROGRAMMING IN C
UNIT I
Introduction to Algorithms and Programming Languages:
Algorithm – Key features of Algorithms – Some more Algorithms – Flow Charts – Pseudo code – Programming
Languages – Generation of Programming Languages – Structured Programming Language-Design and
Implementation of Correct, Efficient and Maintainable Programs.
Introduction to C:
Introduction – Structure of C Program – Writing the first C Program – File used in C Program – Compiling and
Executing C Programs – Using Comments – Keywords – Identifiers – Basic Data Types in C – Variables – Constants
– I/O Statements in C- Operators in C- Programming Examples – Type Conversion and Type Casting
UNIT II
Decision Control and Looping Statements:
Introduction to Decision Control Statements –Conditional Branching Statements – Iterative Statements – Nested
Loops – Break and Continue Statement – Goto Statement
Functions:
Introduction – Function declaration/ prototype – Function definition – function call – return statement – Passing
parameters – Scope of variables – Storage Classes – Recursive functions – Type of recursion –Recursion vs
Iteration
UNIT III
Arrays:
Introduction – Declaration of Arrays – Accessing elements of the Array – Storing Values in Array – Calculating the
length of the Array – Operations that can be performed on Array – one dimensional array for inter-function
communication – Two dimensional Arrays – Operations on Two Dimensional Arrays - Two Dimensional Arrays for
inter-function communication – Multidimensional Arrays – Sparse Matrices
Strings:
Introduction –Suppressive Input – String Taxonomy – Miscellaneous String and Character functions
UNIT IV
Pointers:

Understanding Computer Memory – Introduction to Pointers – declaring Pointer Variables – Pointer Expressions and
Pointer Arithmetic – Null Pointers – Generic Pointers - Passing Arguments to Functions using Pointer – Pointer and
Arrays – Passing Array to Function – Difference between Array Name and Pointer – Pointers and Strings – Array of
pointers – Pointer and 2D Arrays – Function Pointers – Array 0f Function Pointer – Pointers to Pointers – Memory
Allocation in C Programs – Dynamic Memory Allocation – Drawbacks of Pointers
Structure, Union, and Enumerated Data Types:
Introduction – Nested Structures – Arrays of Structures – Structures and Functions – Self referential Structures –
Union – Arrays of Unions Variables – Unions inside Structures – Enumerated Data Types
UNIT V
Files: Introduction to Files – Using Files in C – Reading Data from Files – Writing Data from Files – Detecting the

End-of-file – Error Handling during File Operations – Accepting Command Line Arguments – Functions for Selecting
a Record Randomly - Remove() – Renaming a File – Creating a Temporary File

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
PROGRAMMING IN C LAB
1. Find out the perfect number using c program.

2. Write a C program to check whether a number is Armstrong or not.

3. Write a C program to find the sum of individual digits of a positive integer.

4. Write a C program to generate the Fibonacci sequence of n terms of the sequence.

5. Write a C program to generate all the prime numbers between 1 and n

6. Write a C program to find both the largest and smallest number in a list of integers.

7. Write a C program that uses functions to perform the following:

a. Addition of Two Matrices b. Multiplication of Two Matrices

8. Write a program to perform various string operations

9. Write C program that implements searching of given item in given list

10.Write a C program to sort a given list of integers in ascending orde r

ADIKAVI NANNAYA UNIVERSITY, RAJAHMUNDRY


CBCS/Semester System (W.e.f. 2015-16 Admitted Batch)
II SEMESTER, COMPUTER SCIENCE
Model Question Paper - Programming in C
Section – A
Answer Any Five Questions
5 X 5 = 25 Marks

1. Explain the various data types available in C


2. What is type casting ? Explain
3. Explain switch statement with example
4. What is recursive function? Explain
5. Explain various string handling functions
6. Explain the difference between Structure and Union
7. Explain pointer and structures
8. What are the different types of data files? Explain
Section – B
Answer All Questions
5 X 10 = 50 Marks
1. A. Write algorithm and draw flowchart to find the roots of quadratic equation
OR
B. Explain the various operators in C

2. A. Explain the various looping structures


OR
B. Write a C program to generate prime numbers up to 20

3. A. Explain the various types of arrays


OR
B. Write a C program to find the product of the two matrices

4. A. Explain structure arrays and structure within structures


OR
B. Write a C program to find the smallest of the given numbers using pointers

5. A. Explain the various file handling functions


OR
B. Write a C program to create student data file

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT

CONTENTS

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT

Chapter Page
S.No. Unit.No Topic
No. No.
1 Introduction to Algorithms and Programming Languages
2 Algorithm
3 Key features of Algorithms
4 Some more Algorithms
5 Flow Charts
1
6 Pseudo code
7 Programming Languages
8 Generation of Programming Languages
9 Structured Programming Language
Design and Implementation of Correct, Efficient and Maintainable
10.
Programs.
11 Introduction to C:
12 1 Introduction
13 Structure of C Program
14 Writing the first C Program
15 File used in C Program – Compiling and Executing C Programs
16 Using Comments Identifiers
17 2 Keywords
18 Basic Data Types in C - Operators in C
19 Variables
20 Constants
21 I/O Statements in C

22 Operators in C
23 Programming Examples – Type Conversion and Type Casting

24 Decision Control and Looping Statements


25 Introduction to Decision Control Statements
26 Conditional Branching Statements
2 1
27 Iterative Statements
28 Break and Continue Statement
29 Goto Statement

ALGORITHM:

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
An algorithm (pronounced AL-go-rith-um) is a procedure or formula for solving a problem, based
on conductiong a sequence of specified actions. A computer program can be viewed as an elaborate algorithm. In
mathematics and computer science, an algorithm usually means a small procedure that solves a recurrent problem.

KEY FEATURES OF ALGORITHM:


1. The algorithm is the basic technique used to get the job done.
2. Step by step procedure designed to perform an operation, and which (like a map or Flowchart) will lead to the
sought result if followed correctly.
3. Algorithms have a definite beginning and a definite end, and a finite number of steps.
4. An algorithm produces the same output information given the same input information.
5. Algorithms can be combined to perform complex tasks such as writing a computer
program.

SOME MORE ALGORITHMS:


1. Write an Algorith to accept any two number and print addition of given two numbers:

Step 1: START

Step 2: DECLARE VARIABLES A, B, C AS INTEGER DATA TYPES


Step 3: WRITE ' ENTER ANY TWO NUMBERS '
Step 4: READ A, B
Step 5: C<- A+B
Step 6: WRITE ' THE ADDITION OF GIVEN TWO NUMBER ' C
Step 7: STOP
2. Write an Algorith to accept any number and print reverse,sum, length of the of the given number

Step 1: START

Step 2: DECLARE VARIABLES N, R, SUM, S, L AS INTEGER DATA TYPES


Step 3: S<-0, SUM<-0 , L<-1
Step 4: WRITE ' ENTER ANY INTEGER NUMBER '
Step 5: READ N
Step 6: CHECK ( N NOT=0 ) THEN DO STEPS 7 TO 12 OTHERWISE GOTO STEP 13
Step 7: R<-N MOD 10
Step 8: S<-Sx10+R
Step 9: SUM<-SUM+R
Step10: l<-L+1
Step11: N<-N/10
Step12: GOTO STEP 6
Step13: WRITE ' THE REVRSE OF THE GIVEN INTEGER ' S
Step14: WRITE ' THE SUM OF THE GIVEN INTEGER ' SUM
Step15: WRITE ' THE LENGTH OF THE GIVEN INTEGER ' L
Step16: STOP

FLOWCHART:

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
Flowchart is a graphical or pictorial representation of an algorithm. Flowchart symbols are specific shapes
used to create a visual representation of a program. Flowcharts can be categorized into four main types.
1. Document flowchart
2. System flowchart
3. Data flowchart
4. Program flowchart
But the core principals of drawing a flowchart remain the same.

GUIDLINES FOR DRAWING FLOWCHARTS:


We need to consider few things when drawing flowcharts, before you start.
1. Using standard symbols will make it understandable for a wide audience.
2. Data flow in flocharts must be Top to Bottom or Left to Write
3. Keeping the arrow flow to one side
4. Drawing a flowchart, use same size symbols
5. Naming the decision blocks, processes, arrows etc are few things you can do to make it better.

FLOWCHART SYMBOLS:
Before drawing flowcharts you need to understand the different symbols used in Flowcharts. There are
many more symbols to make flowchart more meaningful. Below are standard flowchart symbols and thir meaning.

Draw a Flowchart to accept any two number and print addition of given two numbers:

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT

START

DECLARE
A, B, C AS
INTEGERS

WRITE '
ENTER
ANY TWO
NUMBERS '

READ A, B

C<- A + B

WRITE ' THE


ADDITION
OF GIVEN
TWO
NUMBERS '
C

STOP

DEFINING PSEUDOCODE:
Pseudocode is a simple way of writing programming code in English. Pseudocode is not actual programming

language. It uses short phrases to write code for programs before you actually create it in a specific language. Once
you know what the program is about and how it will function, then you can use pseudocode to create statements to
achieve the required results for your program
Pseudocode is a compact and informal high-level description of a program using the conventions of a
programming language, but intended more for humans.
Examples of Pseudocode:

Pseudocode to create a program to add 2 numbers together and then display the result.
Start Program
Enter two numbers, A, B
Add the numbers together
Print Sum
End Program
PROGRAMMING LANGUAGES:
Computer programming is almost always done by means of Programming Language.There exists more than
2500 programming languages in the world. Some of them are known by only their developers

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
GENERATIONS OF PROGRAMMING LANGUAGES:
A programming language is a set of rules that tells the computer what operations to do. These languages
are used by the programmers to create other kinds of software. There are five levels, Generations, of programming
languages, ranging from low-level to high-level.
The five generation of programming languages start at the lowest level with (l) Machine Language. (2)
Assembly Language (3) High Level Languages (Procedural and Object-Oriented Languages), and (4) Very High Level

Languages (Problem-Oriented Languages), (5) Natural Languages.

First Generation: Machine Language


Machine language is the basic language of the computer, representing data as 1s and Os. Each CPU model
has its own machine language: Machine language programs vary from computer to computer, i.e., they are
machine-dependent. . These binary digits, which correspond to the on and off electrical states of the computer, are
clearly not convenient for people to read and use.
Advantages:

1. Very efficient
2. Require less storage space
Disadvantages:

1. Machine dependent
2. Programming is difficult
Second Generation: Assembly Language
Assembly language is a low-level programming language that allows a computer user to write a program
using abbreviations or more easily remembered words instead of numbers, A programmer can write instructions in
assembly language more quickly than in machine language, In these languages, each numeric instruction is
assigned a short name (called a mnemonic) that is easier to remember than a number.
Advantages:

1. It is easier to modify than machine language


2. Easier to understand and use
Disadvantages:

1. The coding to assembly language is time consuming


2. They are also machine dependent
ASSEMBLER:
An assembler, or assembler program, is a program that translates the assembly-language program into
machine language.
Third Generation: High-Level or Procedural Languages:

A high level or procedural language resembles some human language such as English. For example, COBOL,
which is used for business applications A procedural language allow users to write in a familiar notation, rather than
numbers or abbreviations, Also, unlike machine and assembly languages, most of procedural languages are not
machinedependent- i.e., they can be used on more than one kind of computer. Few examples, are FORTRAN,
COBOL, BASIC and Pascal.
For a procedural language we need language translator to translate it into machine language. Depending on
the procedural language we may use either of the following types of translators compiler or an interpreter
COMPILER:

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
The compiler is a computer program that translates the source code written in a high-level language into the

corresponding object code of the low-level language. This translation process is called compilation. The entire high-

level program is converted into the executable machine code file. Compiled languages include COBOL, FORTRAN, C,
C++, etc.

1. Scans the entire program first and translates it into machine code.
2. Converts the entire program to machine code
3. Slow for debugging (removal of mistakes from a program).
4. Execution time is less.
INTERPRETER:
The interpreter is a translation program that converts each high-level program statement into the
corresponding machine code. This translation process is carried out just before the program statement is executed.

Instead of the entire program, one statement at a time is translated and executed immediately. The commonly
used interpreted language is BASIC and PERL.
1. Translates the program line by line.
2. Each time the program is executed; every line is checked for syntax error and then converted to
equivalent machine code.
3. Good for fast debugging.
Advantages of Third Generation: High-Level or Procedural Languages:
1. These are easy to learn.
2. Easier to maintain.
3. They are not machine dependent.
4. Programs are portable.
Fourth Generation: Problem Oriented Languages
Fourth generation languages, in contrast, tell the computer what to do. Very high-level or problem-oriented
languages, also called fourth-generation languages (4 GLs), are much more user-oriented and allow users to
develop programs with fewer commands compared with procedural languages, although they require more
computing power. These languages are known as problem-oriented because they are designed to solve specific
problems, whereas procedural languages are more general-purpose languages.
Three types of problem-oriented languages are report generators, query languages, and application
generators.
Fifth Generation: Natural Languages:
Natural languages are of two types. The first are ordinary human languages: English, Spanish etc. The
second are programming languages that use human language to provide people a more natural connection with
computers.
BASIC: (Beginner's All-purpose Symbolic Instruction Code):

BASIC used to be the most popular microcomputer language and is considered the easiest programming
language to learn. Although it is available in compiler form, the interpreter form is more popular with first-time and
casual users. This is because it is interactive, meaning that user and computer can communicate with each other
during the writing and executing (running) of the program.
Advantage: The primary advantage of BASIC is its ease of use.
Disadvantages: Its processing speed is slow.
COBOL: (Common Business-Oriented Language):

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
COBOL is the language of business and it was formally adopted in 1960, COBOL is the most frequently
used business programming language for large computers. Its most significant attribute is that it is extremely
readable.
Advantages:

1. It is machine independent.
3. Its English-like statements are easy to understand, even for a nonprogrammer.
4. It can handle many files, records, and fields.
5. It easily handles input/output operations.
Disadvantages:

1. Because it is so readable, it is wordy. Thus, even simple programs are lengthy, and programmer productivity is
slowed.
2. It cannot handle mathematical processing as well as FORTRAN
FORTRAN:

FORTRAN is the language of mathematics and the first high-level language. It was developed in 1954 by
IBM; FORTRAN (for FORmula TRANslator) was the first high-level language. Originally designed to express
mathematical formulas, it is still the most widely used language for mathematical, scientific, and engineering
problems. FORTRAN has both advantages and disadvantages:
Advantages:

1 FORTRAN can handle complex mathematical and logical expressions


2 Its statements are relatively short and simple.
3 FORTRAN programs developed on one type of computer can often be easily modified to
work on other types.
Disadvantages:

1 FORTRAN does not handle input and output operations to storage devices as efficiently as some
other higher-level languages.
2 It has only a limited ability to express and process non-numeric data.
3 It is not as easy to read and understand as some other high-level languages.
PASCAL:
Pascal is the simple language. Named after the 17th-century French mathematician Blaise Pascal, Pascal is
an alternative to BASIC as a language for teaching purposes and is relatively easy to learn. A difference form BASIC
is that Pascal uses structured programming. A compiled language, Pascal offers these advantages and
disadvantages:
Advantages:

1. Pascal is easy to learn.


2. It has extensive capabilities for graphics programming.
3. It is excellent for scientific use.
Disadvantage:

1. Pascal has limited input/output programming capabilities, which limits its business applications.
C++ :
C++ is an Object Oriented Programming (OOP) language. In C++-the plus signs stand for "more than C"-
which combines the traditional C programming language with object-oriented capability. C++ was created by Bjame
Stroustrup. Three important concepts of OOP are: Encapsulation, Inheritance, Polymorphism

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
Advantages:

1. It is portable.
2. Once the programmer has written a block of program code, it can be reused in number of
program.
STRUCTURED PROGRAMMING LANGUAGE:
Structured programming takes a top-down approach that breaks programs into modular forms. T he main
objectives of structured programming are
a. Efficiency
b. Readability
c. Clarity of programs
d. Easy modification
e. Reduced testing problems.
The goto statement should be avoided so far as possible. The three basic building blocks are given below
1. Sequential flow Control Structure:

It consists of a single statement or a sequence of statements with a single entry and single exit as shown in
Figure

2. Repeatativeflow or Loop or Iteration:

It consists of a condition ( simple or compound ) and sequence structure which is executed condition
based as shown below

3. Conditional flow or Binary decision structure:

It consists of a condition (simple or compound ) and two branches out of which one is to be followed
depending on the condition being true or false as shown below:-

INTRODUCTION TO THE DESIGN AND IMPLEMENTATION OF CORRECT, EFFICIENT AND MAINTAINABLE PROGRAMS:
The design and development of a correct, efficient, and maintainable program depends on the approach
followed by the programmer. A programmer should follow standard methodologies throughout the life cycle of
program development. The entire program development process is divided into a number of phases, with each

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
phase serving a definite purpose. Also, the output of one phase acts as an input for the next phase. Now to
understand these standard set of phases in the program development process:
1. Analysis Phase:

As the name suggests, the first phase of program development involves analyzing the problem in order to
ascertain the objectives that the program is supposed to meet. All the identified requirements are documented so
as to avoid any doubts or uncertainties pertaining to the functionality of the program.
2. Designing Phase:

This phase involves making the plan of action before actually starting the development work. The plan is
made on the basis of the program specifications identified in the previous phase. Different programs require
different designing patterns depending on the program specifications.
3. Development Phase:

This phase involves writing the instructions or code for the program on the basis of the design document
created in the previous phase. The choice of the programming language in which the program will be developed is
made on the basis of the type of program.
4. Implementation and Testing:

In this stage, the developed program is implemented in its target environment and its key parameters are
closely observed in order to ensure that the program runs correctly. Apart from ensuring the correct functioning of
the program this phase primarily focuses on identifying the hidden bugs in the program.

CHARACTERISTICS OF A GOOD PROGRAM:


The different aspects of evaluating a program are : efficiency, flexibility , reliability, portability and
robustness etc. These characteristics are given below :
1. Efficiency:

It is of three type: programmer effort, execution time and memory space utilization. The high level
languages are used for programmer efficiency but, a program written in machine language or assembly language is
quite compact and takes less machine time, and memory space. So depending on the requirement a compromise
between programmer effort and execution time can be made.
2. Flexibility:

A program that can serve many purposes is called a flexible program. For example, CAD (computer aided
design) software are used for different purposes such as : Engineering drafting, printed circuit board layout and
design architectural design. CAD can also be used in execution time can be made.
3. Reliability:

It is the ability of a program to work its intended function accurately even if there are temporary or
permanent changes in the computer system. Programs having such ability are known as reliable.
4. Portability:

It is desirable that a program written on a certain type of computer should run on different type of
computer systems. A program is called portable if it can be transferred from one system to anther with ease.

5. Robustness:

A program is called robust if in provides meaningful results for all inputs. If correct data is supplied at run
time, it will provide the correct result. In case the entered data is incorrect, the robust program given an
appropriate message with no run time errors.

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
6. User friendly:

A program that can be easily understood even by a novice is called user friendly. This characteristic makes
the program easy to modify if the need arises.
7. Self documenting Code:

The source code which uses suitable names for the for identifiers is called self-documenting code. A cryptic
name for identifiers makes the program complex and difficult to debug later on (even the programmer may forget
the purpose of the identifiers). So, a good program must have self-documenting code.

INTRODUCTION:
HISTORY OF C LANGUAGE
C Programming Language was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T
(American Telephone & Telegraph), located in U.S.A. Dennis Ritchie is known as the founder of c language. It
was developed to overcome the problems of previous languages such as B, BCPL etc. Initially, C language was
developed to be used in UNIX Operating System. It inherits many features of previous languages such as B and

BCPL. Programming languages that were developed before C language.


LANGUAGE YEAR DEVELOPED BY
ALGOL 1960 International Group
BCPL 1967 Martin Richard
B 1970 Ken Thompson
Traditional C 1972 Dennis Ritchie

FEATURES OF C LANGUAGE:

C is the widely used language. It provides a lot of features that are given below.
1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. Structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible
1. Simple:

C is a simple language in the sense that it provides Structured Approach (to break the problem into

parts), rich set of Library Functions, Data Types, Operators etc.


2. Machine Independent or Portable:

C Programs can be executed in many machines with little bit or no change. But it is not platform-
independent.
3. Mid-level Prorgramming language:

C is also used to do low level programming. It is used to develop system applications such as Kernel, Driver

etc. It also supports the feature of High Level Language. That is why it is known as Mid-Level Language.

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
4. Structured prorgramming language:

C is a structured programming language in the sense that we can break the program into parts using
functions. So, it is easy to understand and modify.
5. Rich Library:

C provides a lot of inbuilt functions that makes the development fast.


6. Memory Management:

It supports the feature of Dynamic Memory Allocation. In C language, we can free the allocated memory at
any time by calling the free() function.
7. Speed:

The compilation and execution time of C language is fast.


8. Pointer

C provides the feature of pointers. We can directly interact with the memory by using the pointers. We can
use pointers for memory, Structures, functions, array etc.
9. Recursion

In c, we can call the function within the function. It provides code reusability for every function.
10. Extensible

C language is extensible because it can easily adopt new features.


STRUCTURE OF C PROGRAM:
A C program basically consists of the following parts −
1. Preprocessor Commands
2. Functions
3. Variables
4. Statements & Expressions
5. Comments
In Structure of a C program, the following are various parts
1. Preprocessor Commands:

The first line of the program #include <stdio.h> is a preprocessor command, which tells a C compiler to include stdio.h
file before going to actual compilation.
2. Functions:

The next line int main( ) is the main function where the program execution begins.
3. Variables:

A Variable is a name of memory location. It is used to store data. Its value can be changed and it can be
reused many times.
It is a way to represent memory location through symbol so that it can be easily identified.
Ex1: int a; Ex2: float b; Ex3: char c; Ex4: char n[10]; Ex5: int a,b,c;
4. Statements & Expressions:

The body of the function contains valid C statements and expressions. These statements are solve the given
task.

5. Comments:

Comments /*...*/ will be ignored by the compiler and it has been put to add additional comments in the
program. So such lines are called comments in the program.

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
WRITING THE FIRST C PROGRAM:
Simple code that would print the words "Hello World"
#include<stdio.h>
main()
{
/* My First Program in C */
printf(“ HELLOW, WELCOME TO C WORLD “);
}
Let us take a look at the various parts of the above program −
1. The first line of the program #include <stdio.h> is a preprocessor command, which tells a C
compiler to include stdio.h file before going to actual compilation.
2. The next line int main() is the main function where the program execution begins.
3. The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments
in the program. So such lines are called comments in the program.
4. The next line printf(...) is another function available in C which causes the message " HELLOW,
WELCOME TO C WORLD" to be displayed on the screen.
FILE USED IN C PROGRAM AND COMPILING AND EXECUTING C PROGRAMS :

To save the source code in a file, and how to compile and run it. Following are the simple steps −
1. Open a text editor and add the above-mentioned code.
2. Save the file as hello.c
3. Open a command prompt and go to the directory where you have saved the file.
4. open hello.c and press Ctrl F9 to compile your code.
5. If there are no errors in your code, the command prompt will take you to the next line and would
generate hello.bak and hello.exe executable file.
6. Now, type hello.exe to execute your program.
7. You will see the output "HELLOW, WELCOME TO C WORLD" printed on the screen.

COMMENTS IN C:
Comments in C language are used to provide information about lines of code. It is widely used for
documenting code. There are 2 types of comments in C language.
1. Single Line Comments 2. Multi Line Comments
1. Single Line Comments:

Single line comments are represented by double slash \\. An example of single line comment in C.
#include <stdio.h>
#include <conio.h>
void main()
{
clrscr(); //printing information
printf("Hello C");
getch(); } Output: Hello C
2. Multi Line Comments:

Multi line comments are represented by slash asterisk \* ... *\. It can occupy many lines of code but it can't
be nested. The Syntax is

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
Syntax: /*
code
to be commented
*/
An example of multi line comment in C
#include <stdio.h>
#include <conio.h>
void main()
{ clrscr(); /*printing information*/
printf("Hello C");
getch(); }
Output:
Hello C
C CHARACTER SET:
C character Set consists of 1. Source Characters and 2. Excution or White space or Backslah or Escape
Sequences.
1. Source Characters:

A source character is a character that represents itself when used. In C language, Source Character Set
consists of following catagerious of characters.
S.No. Category Characters
1. Alphabets A to Z and UnderScore ( _)
2. Digits 0 to 9
3. Special Symbols ~, !, #, $, %, ^, &, *, @, /, etc.,
4. Punctuations ., ,, ‘, ”, :, :, (, ), [, ], {, }, etc.,

2. Excution or White Space or Backslah or Escape Sequences:

An escape sequence in C language is a sequence of characters that doesn't represent itself when used
inside string literal or character. It is composed of two or more characters starting with backslash \. For example: \
n represents new line.

List of Escape Sequences in C:


S.No. Escape Sequence Meaning
1. \a Alarm or Beep
2. \b Backspace
3. \f Form Feed
4. \n New Line
5. \r Carriage Return
6. \t Tab (Horizontal)
7. \v Vertical Tab
8. \\ Backslash
9. \' Single Quote
10. \" Double Quote
11. \? Question Mark
12. \nnn octal number
13. \xhh hexadecimal number
14. \0 Null

WORDS IN C LANGUAGE:
A word is nothing but group of characters. In C Language words are classified into two types.

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
1. Key Words or Reserved Words 2. User defined Words or Programmer supplied words
1. Keywords in C:

Key words are defined by the scientists. A Key Word is fixed and predefined meaning to the compiler. A keyword is
a reserved word. You cannot use it as a variable name, constant name etc. There are only 32 reserved words (keywords) in C
language. A list of 32 keywords in c language is given below:

auto break case char const continue default do


double else enum extern float for goto if
int long register return short signed sizeof static
struct switch typedef union unsigned void volatile while

2. User defined Words or Programmer supplied words in C (Identifiers):

These words are defined by the User or programmer. The Variable names, Data Names, Constant names,
Etc., are user defined words.
Ex1 : int a,b,c; Ex2: float jack, rose;
In the above statements int, float are Key Words and a, b, c, jack and rose are user defined words.

VARIABLES or IDENTIFIERS IN C:

A Variable or Identifier is a name of memory location. It is used to store data. Its value can be
changed and it can be reused many times.
It is a way to represent memory location through symbol so that it can be easily identified. The
syntax to declare a variable or Identifier:
Syntax:
DataType Variable_nameor variables_list;
Where the Data types can be int (integer), char (character), float (real) etc

The example of declaring variable is given below:


Example1: int a; Example2: float b; Example3: char c; Example4: char n[10]; Example5: int a,b,c;
Here, a, b, c are variables and int, float, char are data types. We can also provide values while
declaring the variables as given below:
int a=10,b=20; //declaring 2 variable of integer type
Rules for defining variables or Identifiers:

1. A variable can have alphabets, digits and underscore.


2. A variable name can start with alphabet and underscore only. It can't start with digit.
3. No white space is allowed within variable name.
4. A variable name must not be any reserved word or keyword e.g. int, float etc.

Types of Variables in C:
There are many types of variables in c:
1. local variable 2. global variable 3. static variable
4. automatic variable 5. external variable 6. register variable
1. Local Variable:

A variable that is declared inside the function or block is called local variable.

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
It must be declared at the start of the block.
void function1()
{
int x=10; // local variable
}
You must have to initialize the local variable before it is used.
2. Global Variable:

A variable that is declared outside the function or block is called global variable. Any function can change
the value of the global variable. It is available to all the functions. It must be declared at the start of the block.

int value=20; //global variable


void function1()
{
int x=10; //local variable
}

3. Static Variable:

A variable that is declared with static keyword is called static variable. It retains its value between multiple
function calls.
void function1()
{
int x=10; //local variable
static int y=10; //static variable
x=x+1;
y=y+1;
printf("%d,%d",x,y);
}
If you call this function many times, local variable will print the same value for each function call e.g,
11,11,11 and so on. But static variable will print the incremented value in each function call e.g. 11,12,13 and so on.

4. Automatic Variable:

All variables in C that is declared inside the block, are automatic variables by default. By we can explicitly
declare automatic variable using auto keyword.
void main()
{
int x=10;//local variable (also automatic)
auto int y=20;//automatic variable
}
5. External Variable:

We can share a variable in multiple C source files by using external variable. To declare a external variable,
you need to use extern keyword.
myfile.h
extern int x=10; //external variable (also global)

Example:
#include "myfile.h"

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
#include <stdio.h>
void printValue()
{
printf("Global variable: %d", global_variable);
}
6. Register Variable:

The register variable allocates memory in register than RAM. Its size is same of register size. It has a faster
access than other variables. It is recommended to use register variable only for quick access such as in counter.
Note: We can not get the address of register variable
Syntax:

register int variable=value;


Example:

register int counter=0;

C - CONSTANTS & LITERALS:


Constants refer to fixed values that the program may not alter during its execution. These fixed values are
also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a character
constant, or a string literal. There are enumeration constants as well. Constants are treated just like regular
variables except that their values cannot be modified after their definition.
1. Integer Constants or Literals:

An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x
or 0X for hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and long,
respectively. The suffix can be uppercase or lowercase and can be in any order.
Examples of integer literals:
85 /* decimal */ 0213 /* octal */ 0x4b /* hexadecimal */
30 /* int */ 30u /* unsigned int */ 30l /* long */ 30ul /* unsigned long */

2. Floating-point Constants or Literals:

A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can
represent floating point literals either in decimal form or exponential form. While representing decimal form, you
must include the decimal point, the exponent, or both; and while representing exponential form, you must include
the integer part, the fractional part, or both. The signed exponent is introduced by e or E. Here are some examples
of floating-point literals
3.14159 /* Legal */ 314159E-5L /* Legal */

3. Character Constants or Literals:

Character literals are enclosed in single quotes, e.g., 'x' can be stored in a simple variable of char type. A
character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character (e.g., '\
u02C0').

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT

4. String Constants or Literals:

String literals or constants are enclosed in double quotes "". A string contains characters that are similar to
character literals: plain characters, escape sequences, and universal characters. You can break a long line into
multiple lines using string literals and separating them using white spaces.
Examples: of string literals.
“ YRL COLLEGE “ “ JAGADEESH ” “ A9*ABC “
Defining Constants:
There are two simple ways in C to define constants
1. Using #define preprocessor.
2. Using const keyword.
1. #define Preprocessor:

Given below is the syntax to use #define preprocessor to define a constant


Syntax:

#define identifier or variable value


Example:

The following example explains it in detail:


#include <stdio.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main()
{
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
}
When the above code is compiled and executed, it produces the following result value of area : 50
2. The const Keyword:

You can use const prefix to declare constants with a specific type as follows
Syntax:

const type variable Name = value;


Example:

The following example explains it in detail


#include <stdio.h>
int main()
{
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE); }
When the above code is compiled and executed, it produces the result value of area : 50

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
DATA TYPES IN C:
A data type specifies the type of data that a variable can store such as integer, floating, character etc.

There are 4 types of data types in C language.

TYPES DATA TYPES


Basic Data Type int, char, float, double
Derived Data Type array, pointer, structure, union
Enumeration Data Type enum
Void Data Type void
1. Basic Data Types :
The basic data types are integer-based and floating-point based. C language supports both signed and
unsigned literals. The memory size of basic data types may change according to 32 or 64 bit operating system. the
following are basic data types. Its size is given according to 32 bit architecture.

S.NO. DATA TYPES MEMORY SIZE RANGE


I char 1 byte −128 to 127
a. signed char 1 byte −128 to 127
b. unsigned char 1 byte 0 to 255
II short 2 byte −32,768 to 32,767
a. signed short 2 byte −32,768 to 32,767
b. unsigned short 2 byte 0 to 65,535
III int 2 byte −32,768 to 32,767
a. signed int 2 byte −32,768 to 32,767
b. unsigned int 2 byte 0 to 65,535
IV short int 2 byte −32,768 to 32,767
a. signed short int 2 byte −32,768 to 32,767
b. unsigned short int 2 byte 0 to 65,535
V long int 4 byte -2,147,483,648 to 2,147,483,647
a. signed long int 4 byte -2,147,483,648 to 2,147,483,647
b. unsigned long int 4 byte 0 to 4,294,967,295
VI float 4 byte
a. double 8 byte
b. long double 10 byte

I O STATEMENTS IN C

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
Formatted Input And Output Functions (printf & scanf) In C :
The printf() and scanf() functions are used for input and output in C language. Both functions are inbuilt
library functions, defined in stdio.h (header file) These functions are known as formatted Input and Output
functions.
Formatted Output or Output function (printf()):
The printf() function is used for output. It prints the given statement to the console. The syntax of printf()
function is given below:
Syntax1:
printf(" message / comment ");
Example: Printf(" welcome to C world ");
Syntax2:
printf("format string", argument_list);
Where the format string can be %d (integer), %c (character), %s (string), %f (float) etc.
Example:1: printf(" %d ", a );
Example:2: printf(" %d %f %c", a,b,c );
Example:3: printf(" %d\n %d\n %d\n", x,y,z);
Syntax3:

printf("message or comment with format string", argument_list);


Where the format string can be %d (integer), %c (character), %s (string), %f (float) etc
Example:1: printf(" The result is %d ", R);
Example:2: printf("%d is result ", R);
Example:3: Printf(" The result %d is", R);

Formatted Input function or Input function (scanf()):


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

scanf("format string", Address of Argument_list);


Where the format string can be %d (integer), %c (character), %s (string), %f (float) etc.
Example:1: scanf(" %d ", &a );
Example:2: printf(" %d %f %c", &a,&b,&c );
Example:3: printf(" %d\n %d\n %d\n",&x,&y,&z);

C OPERATORS:
An operator is simply a symbol that is used to perform operations. There can be many types of operations
like Arithmetic, Relational, Logical and Bitwise Operators etc. The following types of operators are performs different
types of operations in C language.
1. Arithmetic Operators 2. Relational Operators 3. Logical Operators
4. Bitwise Operators 5. Ternary or Conditional Operators 6. Assignment Operator
7. Shift Operators 8. Misc Operator

1. ARITHMETIC OPERATORS:

Arithmetic operators performs basic arithmetic operations like Addition, Subtraction, Multiplication,
Division and Modulus division etc., Assume variable a holds 10 and variable b holds 20, then:

S.NO. OPERATOR DESCRIPTION EXAMPLE

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
1. + Addition - Adds values on either side of the operator a + b will give 30
2. - Subtraction - Subtracts right hand operand from left hand operand a - b will give -10
3. * Multiplication - Multiplies values on either side of the operator a * b will give 200
4. / Division - Divides left hand operand by right hand operand b / a will give 2
Modulus - Divides left hand operand by right hand operand and
5. % b % a will give 0
returns remainder

6. ++ (Increment)- Increases an integer value by one A++ will gives 11

7 -- (Decrement) - Decreases an integer value by one A-- will gives 9

2. RELATIONAL OR COMPARISON OPERATORS:

These Operators are used to compare two or more Operands or Variables and then produce either True or
False. These Operators are used to build Relational Or Boolean Expressions. Assume variable a holds 10 and
variable b holds 20, then:
S.NO. OPERATOR DESCRIPTION EXAMPLE

Checks if the values of two operands are equal or not, if yes then
1. == (a == b) is not true.
condition becomes true.
Checks if the values of two operands are equal or not, if values are not
2. != (a != b) is true.
equal then condition becomes true.
Checks if the value of left operand is greater than the value of right
3. > (a > b) is not true.
operand, if yes then condition becomes true.
Checks if the value of left operand is less than the value of right operand,
4. < (a < b) is true.
if yes then condition becomes true.
Checks if the value of left operand is greater than or equal to the value of
5. >= (a >= b) is not true.
right operand, if yes then condition becomes true.
Checks if the value of left operand is less than or equal to the value of
6. <= (a <= b) is true.
right operand, if yes then condition becomes true.

3. LOGICAL OPERATORS:

C Language supports the following logical operators – Logical Operators are used to combine two or more
Relational expressions in to a Logical expression. These Logical expressions produce either True or False. Assume
variable A holds 10 and B holds 20, then –
S.NO OPERATOR AND DESCRIPTION
1 && (Logical AND) If both the operands are non-zero, then the condition becomes true. Ex: (A && B) is true.

2 || (Logical OR) If any of the two operands are non-zero, then the condition becomes true. Ex: (A || B) is true.

! (Logical NOT) Reverses the logical state of its operand. If a condition is true, then the Logical NOT operator will
3
make it false. Ex: !(A && B) is false.

4. BITWISE OPERATORS:

Bitwise Operators are used to perform operations on Bits and Bytes, these operations are called Boolean
Operations. C Language supports the following Bitwise Operators −Assume variable A holds 2 and B holds 3, then –
S.No Operator and Description
1 & (Bitwise AND) It performs a Boolean AND operation on each bit of its integer arguments. Ex: (A & B) is 2.

2 | (BitWise OR) It performs a Boolean OR operation on each bit of its integer arguments. Ex: (A | B) is 3.

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
^ (Bitwise XOR) It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR means
3
that either operand one is true or operand two is true, but not both. Ex: (A ^ B) is 1.

4 ~ (Bitwise Not) It is a unary operator and operates by reversing all the bits in the operand. Ex: (~B) is -4.

<< (Left Shift) It moves all the bits in its first operand to the left by the number of places specified in the second
5 operand. New bits are filled with zeros. Shifting a value left by one position is equivalent to multiplying it by 2, shifting two
positions is equivalent to multiplying by 4, and so on. Ex: (A << 1) is 4.

>> (Right Shift) Binary Right Shift Operator. The left operand’s value is moved right by the number of bits specified by
6
the right operand. Ex: (A >> 1) is 1.

>>> (Right shift with Zero) This operator is just like the >> operator, except that the bits shifted in on the left are
7
always zero. Ex: (A >>> 1) is 1.

5. ASSIGNMENT OPERATORS:

C Language supports the following assignment operators −


S.No Operator and Description
= (Simple Assignment ) Assigns values from the right side operand to the left side operand Ex: C = A + B will assign
1
the value of A + B into C

6. Conditional Operator (? :):

conditional operator ? : which can be used to replace if...else statements. It has the following general form
Syntax:

Numeric_Variable=(Test-Condition) ? (const1/Variable1/Exp1) : (const2/Variable2/Exp2);

Where const1,2 or Variable1,2 or Exp1,2 Numeric values. In the above syntax If Test condition is true then
const1/Variable1/Exp1 is evaluated and then result is assigned to Numeric_Variable otherwise
const2/Variable2/Exp2 is evaluated and then result is assigned to Numeric_Variable.
Example1: K=(A>B && A>C) ? A : B; Example2: R=(X==Y) ? (X+Y) : (X-Y); Example3: N=(A>B) ? 100 : 200;

TYPE CONVERSION OR TYPE CASTING IN C:


Type casting allows us to convert one data type into other. In C language, we use cast operator for type
casting which is denoted by (type). The syntax of the Type Casting is
Syntax: (type)value;
Example: Without Type Casting:
int f= 9/4;
printf("f : %d\n", f );//Output: 2
Example: With Type Casting:
float f=(float) 9/4;
printf("f : %f\n", f ); //Output: 2.250000

Type Casting example:


A simple example to cast int value into float
#include <stdio.h>
void main()
{
clrscr(); float f= (float)9/4;
printf("f : %f\n", f );
getch(); ` }

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
UNIT-II
CONTROL STATEMENTS:
While writing a program, there may be a situation when you need to adopt one out of a given set of paths.
In such cases, you need to use Control statements that allow our program to make correct decisions and right
actions. These Statements are
1. Decision Making and Branching Statements 2. Decision Making and Looping Statements
1. Decision Making & Branching Statements:

C Language supports Decision Making and Branching Statements which are used to perform different
actions based on different conditions. C Language supports the following forms.
If statements:
The if statement in C language is used to perform operation on the basis of condition. These statements can
perform operations either condition is true or false. There are many ways to use if statement in C language:
1. Simple if statement 2. if...else statement 3. if...else if... statement.(Nested if )
4. Conditional or Terinory Operator 5. switch-case and default statement

1. Simple if statement:
The simple if statement in C language is used to execute the code if condition is true. The syntax of if
statement is given below:
Syntax:

if(Test-Condition)
{
Single Statement; or Group of Statements; //code to be executed
}
Flowchart:

Example:

#include<stdio.h>
main()
{ int n; clrscr();
printf("enter any number:"); scanf("%d",&n);
if(n%2==0) {
printf("%d is even number",n); } getch(); }
2. if-else Statement:

The if-else statement in C language is used to execute the code if condition is true or false. The syntax of if-
else statement is given below:

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
Syntax:

if(Test-Condition)
{
Single Statement; or Group of Statements; // code to be executed if condition is true
}
else
{
Single Statement; or Group of Statements; // code to be executed if condition is false
}
Flowchart:

Example:

#include<stdio.h>
main()
{
int n; clrscr();
printf("enter any number:"); scanf("%d",&n);
if(n%2==0)
printf("%d is even number",n);
else
printf("%d is odd number",n);
getch(); }
3. Nested if ( if else-if ladder ) Statement:

The Nested if ( if else-if ladder ) is used to execute one code from multiple conditions. The syntax of Nested
if ( if else-if ladder )statement is given below:
Syntax:

if(Test-condition1)
{
Statement or Statements block //code to be executed if condition1 is true
}
else
if(condition2)
{
Statement or Statements block //code to be executed if condition2 is true
}
else
if(condition3)
{
Statement or Statements block //code to be executed if condition3 is true
}
---
---
else
{
Statement or Statements block //code to be executed if all the conditions are false
}

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
Flowchart:

Example:
#include<stdio.h>
void main()
{
int a,b,c;
clrscr();
printf("enter a, b and c values:");
scanf(" %d %d %d ",&a,&b,&c);

if(a>b && a>c) { printf("The Biggest Number is : %d “, a); }


else
if(b>a && b>c) { printf("The Biggest Number is : %d “, b); }
else
{ printf("The Biggest Number is : %d “, c); }
getch();
}

4. Conditional Operator (? :):


conditional operator ? : which can be used to replace if...else statements. It has the following general form
Syntax:

Numeric_Variable=(Test-Condition) ? (const1/Variable1/Exp1) : (const2/Variable2/Exp2);

Where const1,2 or Variable1,2 or Exp1,2 Numeric values. In the above syntax If Test condition is true then
const1/Variable1/Exp1 is evaluated and then result is assigned to Numeric_Variable otherwise
const2/Variable2/Exp2 is evaluated and then result is assigned to Numeric_Variable.
Example1: K=(A>B && A>C) ? A : B;
Example2: R=(X==Y) ? (X+Y) : (X-Y);
Example3: N=(A>B) ? 100 : 200;

5. switch-case-default Statement:

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
The switch statement in C language is used to execute the code from multiple conditions. It is like Nested if(
if else-if ladder) statement. The syntax of switch statement in c language is given below:
Syntax:

switch(Variable orConstant or any expression)


{
case value1: Statement or Statements block; //code to be executed;
break; //optional
case value2: Statement or Statements block; //code to be executed;
break; //optional
case value3: Statement or Statements block; //code to be executed;
break; //optional
------------- -------------
------------- -------------
------------- -------------
default: Statement or Statements block;
// code to be executed if all cases are not matched;
}
Example:

#include<stdio.h>
void main()
{
char ch;
clrscr();
printf("enter any character:");
scanf("%c", &ch);
switch(ch)
{
case ‘v’ : printf(“ Violet “); break;
case ‘i’ : printf(“ Indigo “); break;
case ‘b’ : printf(“ Blue “); break;
case ‘g’ : printf(“ Green “); break;
case ‘y’ : printf(“ Yellow “); break;
case ‘o’ : printf(“ Orange “); break;
case ‘r’ : printf(“ Red “); break;
default : printf(“ Enter right choice”);
}
getch();
}
Flowchart:

2. Decision Making and Looping Statements: (Iterative Statements or Control Structures):

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
While writing a program, you may encounter a situation where you need to perform an action over and over
again. In such situations, you would need to write looping statements to reduce the number of lines. C language
supports all the necessary loops to ease down the pressure of programming. ‘C’ supports following Looping
Structures
1. The while Loop ( Enty Controlled Loop ) 2. The do...while Loop (Exit Controlled Loop)
3. The for Loop ( Enty Controlled Loop ) 4. The Nested Loop
1. The while Loop:

The most basic loop in C language is the while loop. The purpose of a while loop is to execute a statement
or statement block repeatedly as lon g as an expression or Test-condition is true. Once the expression becomes false,
the loop terminates. It iterates the code until condition is false.
The while loop checks the Tes condition at the beginning of the loop. This means that this loop will always
be executed if the condition is True. So, it is called Entry Controlled Loop.
Syntax:
Exp1;
while (Test-condition)
{
Statement or Statements;
----------
---------- //body of the loop code to be executed
Exp2;
}
Where Test-condition is Boolean Expression, Exp1 is initialization expression and Exp2 is Increment or
Decrement expressions. Exp1 and Exp2 are optional.
Example:

#include<stdio.h>
void main()
{
int i,n; clrscr();
printf("Enter upto how many numbers do you wnt to print:"); scanf("%d", &n);
i=1;
while(i<=n)
{
printf(“%d \n “, i);
i++;
}
getch();
}

2. The do...while Loop:


The do...while loop is similar to the while loop except that the condition check happens at the end of the
loop. This means that the loop will always be executed at least once, even if the condition is false. So, it is called
Exit Controlled Loop.

Syntax:
Exp1;

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
do
{
Statement or Statements;
----------
---------- //body of the loop and code to be executed
Exp2;
} while (Test-condition);
Where Test-condition is Boolean Expression, Exp1 is initialization expression and Exp2 is Increment or
Decrement expressions. Exp1 and Exp2 are optional
Example:

#include<stdio.h>
void main()
{
int i,n; clrscr();
printf("Enter upto how many numbers do you wnt to print:"); scanf("%d", &n);
i=1;
do
{
printf(“%d \n “, i);
i++;
} while(i<=n);
getch();
}

Difference Between Entry Controlled & Exit Controlled Loops:


The following C progrming code shoes the difference between entry controlled and exit controlled loops
i=6; i=6;
while(i<=5) do
{ {
printf(“%d \n “, i); printf(“%d \n “, i);
i++; i++;
} } while(i<=5);
This code does not produce the output. This code produces the output 6.

3. C language - for( ) Loop:


The 'for' loop is the most compact form of looping. It includes the following three
important parts
1. The loop initialization where we initialize our counter to a starting value. The
initialization statement is executed before the loop begins.
2. The Test Condition which will test if a given condition is true or not. If the condition is true, then the code
given inside the loop will be executed, otherwise the control will come out of the loop.
3. The Iteration statement (Increment or Decrement) can increase or decrease counter. We can put all the
three parts in a single line separated by semicolons.
Syntax:
The syntax of for loop is C language is as follows

for (Initialization Statements; Test Condition; Iteration Statements)


{

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
Statement or Statements;
----------
---------- //body of the loop code to be executed
}

Example:
#include<stdio.h>
void main()
{
int i, n; clrscr();
printf("Enter upto how many numbers do you wnt to print:"); scanf("%d", &n);
for( i=1; i<=n; i++)
{
printf(“%d \n “, i);
}
getch();
}
}

4. Nested Loops:

In C language, Loop inside the loop is called Nested loops. We can write nested loops by using while(), do-
while() and for() structures. The syntax of Nested loop is
Syntax:
The syntax of for Nested loops using for() loop as follows
for (Initialization Statements; Test Condition1; Iteration Statements)
{
for (Initialization Statements; Test Condition2; Iteration Statements)
{
Statement or Statements;
----------
---------- //body of the Inner loop code to be executed
}
Statement or Statements;
----------
---------- //body of the Outer loop code to be executed
}
The following program demonstrate the working of nested loops (or) Generation of Prime Numbers
Example:

#include<stdio.h>
void main()
{
int i, j, n, c;
clrscr();
printf("Enter Upto How Many Prime Numbers Do You Wnt To Print:"); scanf("%d", &n);
for( i=1; i<=n; i++)
{
c=0; for(j=2;j<i;j++)
{
if( i % j == 0) c++;
}
if ( c == 0) printf(“%d \n “, i);
} getch(); }

C Transfer statements: (break & continue):

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
C Language provides transfer statements ( break and continue) to change the default sequential order of
execution of looping Statements and Switch-Case-Default Statement.
break Statement:
The break statement in C language is used to break the execution of loop (while, do while and for) and
switch case. In case of inner loops, it terminates the control of inner loop only. There can be two uses of C break
keyword: is
1. With loop 2. With switch case
1. break Statement with Loop:
Syntax:
The syntax of for loop is C language is as follows
for (Initialization Statements; Test Condition; Iteration Statements)
{
Statement or Statements;
----------
---------- //body of the loop code to be executed
jumping Statement
break;
}
The jump statement and c break Statement can be write in while loop, do while loop, for loop and switch
case statements.
Example:
#include<stdio.h>
void main()
{
int i, n; clrscr();
printf("Enter upto how many numbers do you wnt to print:"); scanf("%d", &n);
for( i=1; i<=n; i++)
{
if (i==10) break;
printf(“%d \n “, i);
}
getch();
} }
1. break statement with switch case:
The break statement in switch case is not must. It is optional. If there is no break statement found in switch
case, all the cases will be executed after matching the case value. It is known as fall through state of C switch
statement. The syntax of break statement with switch case default is.
Syntax:
switch(Variable orConstant or any expression)
{
case value1: Statement or Statements block; //code to be executed;
break; //optional
case value2: Statement or Statements block; //code to be executed;
break; //optional
case value3: Statement or Statements block; //code to be executed;
break; //optional
------------- -------------
------------- -------------
default: Statement or Statements block;
// code to be executed if all cases are not matched;
}

Example:
#include<stdio.h>

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
void main()
{
char ch;
clrscr();
printf("enter any character:");
scanf("%c", &ch);
switch(ch)
{
case ‘v’ : printf(“ Violet “); break;
case ‘i’ : printf(“ Indigo “); break;
case ‘b’ : printf(“ Blue “); break;
case ‘g’ : printf(“ Green “); break;
case ‘y’ : printf(“ Yellow “); break;
case ‘o’ : printf(“ Orange “); break;
case ‘r’ : printf(“ Red “); break;
default : printf(“ Enter right choice”);
}
getch();
}

continue statement:
The continue statement in C language is used to continue the execution of loop (while, do while and for).
It is used with if condition within the loop. In case of inner loops, it continues the control of inner loop only.
Syntax:

for(Initialization Statements; Test Condition; Iteration Statements)


{
Statement or Statements;
----------
---------- //body of the loop code to be executed
if( Test Condition )
continue;
---------- }

The if statement and continue Statement can be write in while loop, do while loop, for loop statements.

Example:
#include<stdio.h>
void main()
{
int i, n; clrscr();
printf("Enter upto how many numbers do you wnt to print:"); scanf("%d", &n);
for( i=1; i<=n; i++)
{
if (i==10)
continue;
printf(“%d \n “, i);
}
getch();
}
}

C goto statement(Unconditional Transfer or Jumping Statement):

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
The goto statement is known as jump statement in C language. It is used to unconditionally jump to other
label. It transfers control to other parts of the program.
It is rarely used today because it makes program less readable and complex.
Syntax:
goto label Name;
goto Jack;

#include<stdio.h>
main()
{
int age; clrscr();
Jack:
printf("You are not eligible to vote!\n");
printf("Enter you age:\n"); scanf("%d", &age);
if(age<18)
goto Jack;
else
printf("You are eligible to vote!\n");
getch();
}

ARRAYS
Array:

Array in C language is a collection or group of elements (data). All the elements of c array

are homogeneous (similar). It has contiguous memory location.


C array is beneficial if we have to store similar elements. Suppose we have to store marks of 50
students, one way to do this is allotting 50 variables. So it will be typical and hard to manage. For
example we can not access the value of these variables with only 1 or 2 lines of code.

Advantage of C Arrays:

1. Code Optimization: Less code to the access the data.


2. Easy to traverse data: By using thefor loop, we can retrieve the elements of an array easily.

3. Easy to sort data: To sort the elements of array, we need a few lines of code only.
4. Random Access: We can access any element randomly using the array.
Disadvantage of C Arrays:

1. Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the limit.
So, it doesn't grow the size dynamically like LinkedList.
2. All the elements of c array are homogeneous (similar).
Types of Arrays:

Arrays can be broadly classified in to two ways. They are


a. Single Dimensional Arrays
b. Two Dimensional or Multi Dimensional Arrays

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
a. Single Dimensional Arrays:
Single Dimensional Arrays in C language is a collection or group of elements (data). All the

elements of c array are homogeneous (similar). It has contiguous memory location.


Declaration of Single Dimensional Arrays in C:

We can declare Single Dimensional Arrays in C language in the following way. The general format
Syntax: data_type array_name[array_size];
Example: int N[5];

Here, int is the data_type, N is the array_name and 5 is the array_size.

Initialization of Single Dimensional Arrays in C:


A simple way to initialize array is by index. Array index starts from 0 and ends with [SIZE - 1].
Example:

marks[0]=80; //initialization of array


marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;

Accessing and Storing elements of the Array:


#include <stdio.h>
void main()
{
int i=0;
int N[5]; //declaration of array
clrscr();
//initialization of array
N[0]=80; //StoringValues in Array
N[1]=60;
N[2]=70;
N[3]=85;
N[4]=75;
//traversal of array or
//Accessing elements of the Array
for(i=0;i<5;i++)
{
printf("%d \n",N[i]);
} //end of for loop
getch();
}
Output
80 60 70 85 75

Declaration with Initialization of Single Dimensional Arrays in C:

We can declare Single Dimensional Arrays in C language in the following way. The general format is

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
int N[5]={20,30,40,50,60};

In such case, there is no requirement to define size. So it can also be written as the following code.
int N[]={20,30,40,50,60};

Two Dimensional or Multidimensional Array in C:


The two dimensional array in C language is represented in the form of rows and columns, also known as
matrix. It is also known as array of arrays or list of arrays. The two dimensional, three dimensional or other
dimensional arrays are also known as multidimensional arrays.
Declaration of two dimensional Array in C:
We can declare an array in the c language in the following way. The general format is
Syntax: data_type array_name[size1][size2];
Example: int N[4][3];

Here, int is the data type, N is array name 4 is the row size and 3 is the column size.

Initialization of Two dimensional Arrays in C:


We can initialize the two dimensional array at the time of declaration in the following way
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Two dimensional array example in C
#include <stdio.h>
#include <conio.h>
void main()
{
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
clrscr();
for(i=0;i<4;i++) //traversing 2D array
{
for(j=0;j<3;j++)
{
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
} //end of j
} //end of i

getch();
}

Output:

arr[0][0] = 1 arr[0][1] = 2 arr[0][2] = 3 arr[1][0] = 2 arr[1][1] = 3 arr[1][2] = 4


arr[2][0] = 3 arr[2][1] = 4 arr[2][2] = 5 arr[3][0] = 4 arr[3][1] = 5 arr[3][2] = 6

One or Two dimensional array for inter-function communication:


Passing Array to Functions in C:

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
To reuse the array operation, we can create functions that receives array as argument. To pass array in
function, we need to write the array name only in the function call. The general format is
Syntax: Functionname(arrayname); //passing array

There are 3 ways to declare function that receives array as argument.


First way: return_type function(type arrayname[])

Declaring blank subscript notation [] is the widely used technique.


Second way: return_type function(type arrayname[SIZE])

Optionally, we can define size in subscript notation [].


Third way: return_type function(type *arrayname)
Example:

Passing array values to function:


#include <stdio.h>
void main()
{
int i=0,min=0;
int N[]={4,5,7,3,8,9}; //declaration of array
clrscr();
min=minarray(N,6); //passing array with size
printf("minimum number is %d \n",min);
getch();
}
int minarray(int arr[],int size)
{
int min=arr[0], i=0;
for(i=1;i<size;i++)
{
if(min>arr[i])
{
min=arr[i];
}
} //end of for
return min;

} //end of function

Output: minimum number is 3

Operations that can be performed on Arrays:


Following operations can be performed on arrays:
1. Traversing 2. Searching 3. Insertion 4. Deletion 5. Sorting 6. Merging

C Program to generate sparse matrix:


A sparse matrix is a matrix that allows special techniques to take advantage of the large number of zero
elements. Sparse matrix is very useful in engineering field, when solving the partial differentiation equations.

C Program to generate sparse matrix:

#include<stdio.h>
#include<conio.h>

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
void main()
{
int A[10][10],B[10][3],m,n,s=0,i,j;
clrscr();
printf("\nEnter the order m x n of the sparse matrix\n");
scanf("%d%d",&m,&n);
printf("\nEnter the elements in the sparse matrix(mostly zeroes)\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("\n%d row and %d column: ",i,j);
scanf("%d",&A[i][j]);
}
}
printf("The given matrix is:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d ",A[i][j]);
}
printf("\n");
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(A[i][j]!=0)
{
B[s][0]=A[i][j];
B[s][1]=i;
B[s][2]=j;
s++;
}
}
}
printf("\nThe sparse matrix is given by");
printf("\n");
for(i=0;i<s;i++)
{
for(j=0;j<3;j++)
{
printf("%d ",B[i][j]);
}
printf("\n");
}
getch();
}

FUNCTIONS IN C

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
The Function is a set of instructions. which are used to solve a specific type. The function in C language is also
known as procedure or subroutine in other programming languages. To perform any task, we can create function. A
function can be called many times. It provides modularity and code reusability.

Advantage of functions:
There are many advantages of functions.
1. Code Reusability:

By creating functions in C, we can call it many times. So we don't need to write the same code again and
again.
2. Code optimization:

It makes the code optimized, we don't need to write much code.


Types of Functions:
There are two types of functions in C programming:

1. Library Functions:

These functions which are declared in the C header files such as scanf(),printf(), gets(), puts(), ceil(),
floor() etc.
2. User-defined functions:

These functions which are created by the C programmer, so that we can use it many times. It reduces
complexity of a big program and optimizes the code. These functions are again classified into three types
a. Function with no arguments
b. Function with arguments
c. Function with arguments and return value
a. Function with no arguments:

These functions have no parameters or arguments and to solve a specific task. The general format for
declaration of function with no arguments is
Syntax:
<prototype> <name of the function>( ) // function declaration or definition
{
--------;
--------; Body of the function
--------;
}
The general format for calling of function with no arguments is
Syntax:
main()
{
--------;
--------; Body of the mainfunction
--------;
<name of the function>( ); // function calling
}

Example:
#include<stdio.h>
main( )

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
{
clrscr();
hellow(); // function calling
getch();
}
hellow( ) // function declaration
{
printf(“Hellow how r u ?”);
}

b. Function with arguments:

A function may have 0 or more parameters or arguments. These functions can have any type of
parameters such as int, float, char etc. The parameters are also known as formal arguments. The general format of
Declaration of a function with arguments or parameters is
Syntax: // function Declaration or Definition
<return_type or proto type><function_name>(data_type1 parameter1, data_type2 parameter2, ...)
{
--------;
--------; Body of the function
}
The general format for calling of function with arguments is

Syntax:
main()
{
--------;
--------; Body of the main function
<name of the function>( parameter1, parameter2, …..); // function calling
}
Example:
#include<stdio.h>
main( )
{
int a=10,b=20;
clrscr();
add(a,b); // function calling
getch();
}

add(int x, int y) // function declaration


{
int z;
z=x+y;
printf(“The addition of two numbers is %d”, z);
}

c. Function with arguments and return value: (Return Value):

To return any value from the function, We need to use any data type such as int, float,char etc. The return
type depends on the value to be returned from the function. A function may or may not return a value from the
function. If a function don't have to return any value use void for the return type. The general format of Declaration
of a function with arguments or parameters and return value is

Syntax:
<return_type or proto type> <function_name>(data_type1 parameter1, data_type2 parameter2, ...)
{

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
--------;
--------; Body of the function
return Statement;
}
The general format for calling of function with arguments is
Syntax:
main()
{
--------;
--------; Body of the main function
<parameter>=<name of the function>( parameter1, parameter2, …..); // function calling
}
Example:
#include<stdio.h>
main( )
{
int a=10.b=20,c;
clrscr();
c=add(a,b); // function calling
printf(“The addition of two numbers is %d”, c);
getch();
}

add(int x, int y) // function declaration


{ return(x+y);
}

Passing Parameters in C Function:


A function may have 0 or more parameters. Functions can have any type of parameters such as int, float,
char etc. The parameters are also known as formal arguments.

Example1:
void hello()
{
printf("hello c");
}
Example2: A function that has 1 parameter:
int cube(int n)
{
return n*n*n;
}

Example3: A function that has 2 parameters:


int add(int a, int b)
{
return a+b;
}

Calling a function in C:
A function returns any value, we need to call function to get the value returned from the function. The
syntax of calling a function in c is given below:
Syntax:
variable=function_name(argument1, argument2,...);
1. variable: The variable is not mandatory. If function return type is void, we must not provide the variable because

void functions doesn't return any value.


2. function_name: The function_name is name of the function to be called.

3. arguments: We need to provide arguments while calling the C function. It is also known as actual arguments.

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
Examples to call a function:
hello(); //calls function that doesn't return a value
int value=get(); //calls function that returns value
int value2=add(10,20); //calls parameterized function by passing 2 values

Passing parameters:
There are two ways to pass value or data to function in C language. They are Call by value and call by
reference in C. Original value is not modified in call by value but it is modified in call by reference.

Call by value and Call by reference:


Call by value in C:
In call by value, Original value is not modified and value being passed to the function is locally stored by the
function parameter in stack memory location. If we change the value of function parameter, it is changed for the
current function only. It will not change the value of variable inside the caller method such as main(). The concept
of call by value in c language by the example given below:
#include <stdio.h>
main()
{
int x=100, y=200;
clrscr();
printf("Before swap in main x=%d and y=%d \n", x,y);
swap(x,y); //passing values to function
printf("After swap in main x=%d and y=%d\n", x,y);
getch(); }
swap(int x, int y)
{
int t;
printf("Before swap in swap function x=%d and y=%d \n", x,y);
t=x;
x=y;
y=t;
printf("After swap in swap function x=%d and y=%d\n", x,y);
}
Output:
Before swap in main x=100 and y=200
After swap in main x=100 and y=200
Before swap in swap function x=100 and y=200
After swap in swap function x=200 and y=100

Call by reference in C:
In call by reference, original value is modified because we pass reference (address). Here, address of the
value is passed in the function, so actual and formal arguments share the same address space. Hence, value
changed inside the function, is reflected inside as well as outside the function. The following program demonstrate
this concept

#include <stdio.h>
main()
{

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
int *x=100, *y=200;
clrscr();
printf("Before swap in main x=%d and y=%d \n", x,y);
swap(*x, *y); //passing references to function
printf("After swap in main x=%d and y=%d\n", x,y);
getch(); }
swap(int &x, int &y)
{
int *t;
printf("Before swap in swap function x=%d and y=%d \n", x,y);
*t=*x;
*x=*y;
*y=*t;
printf("After swap in swap function x=%d and y=%d\n", x,y);
}
Output:
Before swap in main x=100 and y=200
After swap in main x=200 and y=100
Before swap in swap function x=100 and y=200
After swap in swap function x=200 and y=100

Difference between call by value and call by reference in c:

No. Call by Value Call by Reference

1 A copy of value is passed to the function An address of value is passed to the function
Changes made inside the function is not reflected Changes made inside the function is reflected outside
2
on other functions the function also
Actual and formal arguments will be created in Actual and formal arguments will be created in same
3
different memory location memory location

Recursive functions:
A function calls itself certain number of times. A function which calls itself is called a recursive function, the

call is recursive call and the process of function implementation is recursion . A function it self calling that function is
called Recursive function. The general format of Recursive function is
Syntax:
Name of the Recursive function()
{
Body of the function;
reursionfunction(); //calling self function
}
Example of recursive function:
int factorial (int n)
{
if ( n < 0)
return -1; /*Wrong value*/
if (n == 0)
return 1; /*Terminating condition*/
return (n * factorial (n -1));
}

Example of tail recursion in C:


An example to print factorial number using tail recursion in C language.

#include<stdio.h>
void main()

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
{
int fact=0;
clrscr();
fact=factorial(5);
printf("\n factorial of 5 is %d",fact);
getch();
}
int factorial (int n)
{
if ( n < 0)
return -1; /*Wrong value*/
if (n == 0)
return 1; /*Terminating condition*/
else
return (n * factorial (n -1));
}
Output:
factorial of 5 is 120
We can understand the above program of recursive method call by the figure given below:

Types of Recursion:
A function is recursive if it makes a call to itself directly or indirectly. If a function f() calls itself within from
its own body, it is called recursive. Secondly, if a function f() calls another function g() that ultimately calls back to
f(), then it can also be considered a recursive function. Following are ypes of recursions
1. Linear Recursion 2. Binary Recursion 3. Tail Recursion 4. Mutual Recursion
5. Nested Recursion

1. Linear Recursion:

This recursion is the most commonly used. In this recursion a function call itself in a simple manner and by
termination condition it terminates. This process called 'Winding' and when it returns to caller that is called 'Un-
Winding'.Termination condition also known as Base condition.
2. Binary Recursion:

Binary Recursion is a process where function is called twice at a time inplace of once at a time. Mostly it's
using in data structure like operations for tree as traversal, finding height,merging,etc.
3. Tail Recursion:

In this method, recursive function is called at the last. So it's more efficient than linear recursion method.
Means we can say termination point will come(100%) only we have to put that condition.

4. Mutual Recursion:

Functions calling each other. Let's say FunA calling FunB and FunB calling FunA recursively. This is not
actually not recursive but it's doing same as recursive. So we can say Programming languages which are not
supporting recursive calls, mutual recursion can be applied there to fulfill the requirement of recursion.
5. Nested Recursion:

It's very different than all recursions. All recursion can be converted to iterative (loop) except nested
recursion. We can understand this recursion by example of Ackermann function.

Recursion vs Iteration: or Difference between Recursion and Iteration:

1. In recursion, function calls itself until the base condition is reached. On other hand iteration means
repetition of process until the condition fails. For example, looping Structures like for, while, etc. in

C programs.

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
2. Iterative approach involves four steps, initialization, condition, execution and updation. In recursive
function, only base condition (terminate condition) is specified.
3. Recursion keeps code in short and simple Whereas iterative approach makes code longer.
4. Recursion is slower than iteration due to overhead of maintaining stack whereas iteration is faster.
5. Recursion takes more memory than iteration due to overhead of maintaining stack .

Towers of Hanoi Program:


This C Program uses recursive function & solves the tower of Hanoi. The tower of Hanoi is a mathematical puzzle. It
consists of threerods, and a number of disks of different sizes which can slideonto any rod. The puzzle starts with
the disks in a neat stack in ascending order of size on one rod, the smallest at the top. We have to obtain the same
stack on the third rod. The following is the source code for solving towers of hanoi.
#include<stdio.h>
#include<conio.h>
void hanoi(int, char, char, char);
void main()
{
int disks;
char source, destination, aux;
clrscr();
printf("\nEnter No. of Disks:");
scanf("%d",&disks);
printf("\nEnter Source, Destination and Auxillary Disk Names:");
scanf("%s%s%s",source, destination, aux);
hanoi(disks,source,destination,aux);
getch();
}

void hanoi(int n, char s, char d, char a)


{
if(n>0)
{
hanoi(n-1,s,a,d);
printf("\n%d is moved from %s to %s",n,s,d);
hanoi(n-1,a,d,s);
}
}

Scope of variables or Storage Classes in C:


Storage classes are used to define scope and life time of a variable. There are four storage classes in C
programming.

1. auto 2. extern 3. static 4. register

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
Storage Storage
Default Value Scope Life-time
Classes Place
auto RAM Garbage Value Local Within function
Till the end of main program, May be declared anywhere
extern RAM Zero Global
in the program
Till the end of main program, Retains value between
static RAM Zero Local
multiple functions call
register Register Garbage Value Local Within function
1. auto:

The auto keyword is applied to all local variables automatically. It is the default storage class that is why it
is known as automatic variable. The following examples shows the working of auto storage class.
Example:

#include <stdio.h>
void main()
{
int a=10;
auto int b=10; //same like above
printf("%d %d",a,b);
}
Output: 10 10

2. register:

The register variable allocates memory in register than RAM. Its size is same of register size. It has a faster
access than other variables. The use of register variable only for quick access such as in counter.
Example: register int counter=0;

3. static:

The static variable is initialized only once and exists till the end of the program. It retains its value between
multiple functions call. The static variable has the default value 0 which is provided by compiler. The following
examples shows the working of static storage class.
Example:
#include <stdio.h>
void main()
{
jack();
jack();
jack(); }
void jack()
{
static int i=0; //static variable
int j=0; //local variable
i++; j++; printf("i= %d and j= %d\n", i, j); }
Output: i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1
4. extern:

The extern variable is visible to all the programs. It is used if two or more files are sharing same variable or
function.
Example: extern int counter=0;
C STRINGS
String:
String in C language is an array of characters that is terminated by \0 (null character). There are two ways

to declare string in c language.


1. By char array

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
2. By string literal
Declaring Strings in C Language:
Example of declaring string by char array in C language.
char ch[10]={ 'j', 'a', 'g', 'a', 'd', 'e', 'e', 's', 'h', '\0'};

Array index starts from 0, so it will be represented as in the figure given below.
0 1 2 3 4 5 6 7 8 9
j a g a d e e s h \0

While declaring string, size is optional, We can write the above code as given below:
char ch[]={'j', 'a', 'g', 'a', 'd', 'e', 'e', 's', 'h', '\0'};

We can also define string by string literal in C language. For example:


char ch[]="jagadeesh";
In such case, '\0' will be appended at the end of string by the compiler.
Difference between char array and string literal:
The only difference is that string literal cannot be changed whereas string declared by char array can be
changed.
Example: We can declare and print string, the '%s' is used to print string in c language.
#include <stdio.h>
void main ()
{
char ch[10]={'j', 'a', 'g', 'a', 'd', 'e', 'e', 's', 'h', '\0'};
char ch2[10]="jagadeesh";
printf("Char Array Value is: %s\n", ch);
printf("String Literal Value is: %s\n", ch2);
}
Output:
Char Array Value is: jagadeesh
String Literal Value is: jagadeesh

C gets() and puts() functions(Unformatted Input/Output functions):


The gets() and puts() functions are unformatted String Input and Output functions. Both functions are
defined in <stdio.h> header file.
gets() function:
The gets() function reads string from user. The general format of gets() function is
Syntax: gets(string variable);
Example: gets(name);
puts() function:
The puts() function prints the string. The general format of puts() function is
Syntax: puts(string variable);
Example: puts(name);

The following program to read and write strings using gets() and puts() functions.
#include<stdio.h>
void main()
{
char name[50];
printf("Enter your name: ");
gets(name); //reads string from user

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
printf("Your name is: ");
puts(name); //displays string
}

String Taxonomy – String Operations OR String Functions


There are many important string functions defined in "string.h" library.

NO. FUNCTION DESCRIPTION

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


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

The following program illustrates the various String operations in C language.


#include <stdio.h>
#include <string.h>
void main()
{
char ch[20]={'j', 'a', 'g', 'a', 'd', 'e', 'e', 's', 's', 'h', '\0'};
char n1[20];
char n2]20];
char n3[40];
int l,k;
clrscr();
// to check given String is Palindrome or not
puts(“Enter any String”); // String output
gets(n1); // String input
n2=strrev(n1); // reverse of the given string
k=strcmp(n1,n2); // comparision of two strings
if(k==0)
puts(“Given String is Palindrome”);
else
puts(“Given String is Not Palindrome”);
l=strlen(ch); // length of the given string
printf("Length of the string is: %d",l);
puts(“Enter any String in lowercase”);
gets(n1);
n2=strupr(n1); // upper case of the given string
printf(“ The upper case of given string is: %s\n”,n2);
puts(“Enter any String in Uppercase”);
gets(n1);
n2=strlwr(n1); // lower case of the given string
printf(“ The Lower case of given string is: %s\n”,n2);

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
puts(“Enter any two Strings”);
gets(n1);
gets(n2);
n3=strcat(n1,n2); // concat of given two strings
printf(“ The Concat of given two strings are string is: %s\n”,n3);
getch();
}
C Character Functions:

There are many important Character functions defined in "ctype.h" library that are useful for testing and
mapping characters.

S.NO. FUNCTION & DESCRIPTION

1 isalnum(character): This function checks whether the passed character is alphanumeric.


2 isalpha(character): This function checks whether the passed character is alphabetic.
3 isdigit(character): This function checks whether the passed character is decimal digit.
4 islower(character): This function checks whether the passed character is lowercase letter.
5 isprint(character): This function checks whether the passed character is printable.
6 ispunct(character): This function checks whether the passed character is a punctuation character.
7 isspace(character): This function checks whether the passed character is white-space.
8 isupper(character): This function checks whether the passed character is an uppercase letter.

Conversion Functions:

C language supports two conversion functions that accepts and returns an "int".
S.NO. FUNCTION & DESCRIPTION
1 tolower(character): This function converts uppercase letters to lowercase.
2 toupper(character): This function converts lowercase letters to uppercase.

C Mathematical Functions:

The commonly used functions math functions of math.h header file are given below.
S.NO. FUNCTION DESCRIPTION

rounds up the given number. It returns the integer value which is greater than or
1 ceil(number)
equal to given number.
rounds down the given number. It returns the integer value which is less than or
2 floor(number)
equal to given number.
3 sqrt(number) returns the square root of given number.
pow ( base,
4 returns the power of given number.
exponent)
5 abs(number) returns the absolute value of given number.
6 log(number) Returns the natural logirthm of given number
7 sin(degres) Returns sin value
8 cos(degres) Returns cosine value

C – Miscellaneous functions:

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT

C language supports the following


Miscellaneous functions
S.NO. FUNCTION DESCRIPTION
1 getenv() This function gets the current value of the environment variable
2 setenv() This function sets the value for environment variable
3 putenv() This function modifies the value for environment variable
4 perror() Displays most recent error that happened during library function call
5 rand() Returns random integer number range from 0 to at least 32767
6 delay() Suspends the execution of the program for particular time

C POINTERS
Pointer:

A Pointer is a variable whose value is the address of another variable, i.e., direct address of the memory
location. Like any variable or constant, we must declare a pointer before using it to store any variable address

Declaring Pointer Variables:


In C language pointer variables can be declared in the following format. The general form of a pointer
variable declaration is
Syntax:
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the
pointer variable. The asterisk * used to declare a pointer is the same asterisk used for multiplication. However, in
this statement the asterisk is being used to designate a variable as a pointer. The following are some of the valid
pointer declarations
int *ip; /* pointer to an integer */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
The actual data type of the value of all pointers, whether integer, float, character, that represents a
memory address. The only difference between pointers of different data types is the data type of the variable or
constant that the pointer points to address.

The following example makes use of pointer operations:


#include <stdio.h>
int main ()
{
int b = 20; /* actual variable declaration */
int *a; /* pointer variable declaration */
a = &b; /* store address of var in pointer variable*/
printf("Address of b variable: %x\n", &b ); /* address stored in pointer variable */
printf("Address stored in a variable: %x\n", a ); /* access the value using the pointer */
printf("Value of *a variable: %d\n", *a );
return 0;
}
Output:
Address of b variable: bffd8b3c

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
Address stored in a variable: bffd8b3c
Value of *a variable: 20
Pointer Expression and Pointer Airthmetic:
In C , like other variables pointer variables can be used in expressions. For example if p1 and p2 are
properly declared and initialized pointers, then the following statements are valid.
y=*p1**p2;
sum=sum+*p1;
z= 5* - *p2/p1;
*p2= *p2 + 10;
C allows us to add integers to or subtract integers from pointers as well as to subtract one pointer from the other.
we can also compare pointers by using relational operators the expressions such as p1 >p2 , p1==p2 and p1!=p2
are allowed.
/*Program to illustrate the pointer expression and pointer arithmetic*/
#include< stdio.h >
main()
{
int ptr1,ptr2;
int a,b,x,y,z;
a=30;b=6;
ptr1=&a;
ptr2=&b;
x=*ptr1+ *ptr2 –6;
y=6*- *ptr1/ *ptr2 +30;
printf(“Address of a +%u\n”,ptr1);
printf(“Address of b %u\n”, ptr2);
printf(“a=%d, b=%d\n”, a,b);
printf(“x=%d,y=%d\n”,x,y);
ptr1=ptr1 + 70;
ptr2= ptr2;
printf(“a=%d, b=%d\n”,a,b);
}

NULL Pointers:

A pointer that is assigned NULL is called a null pointer. This is done at the time of variable declaration. The
NULL pointer is a constant with a value of zero defined in several standard libraries. Consider the following program
#include <stdio.h>
main ()
{
int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr );
return 0;
}
Output:
The value of ptr is 0

if a pointer contains the null(zero) value, it is assumed to point to nothing. To check for a null pointer,We
can use an 'if' statement as follows
if(ptr) /* succeeds if p is not null */
if(!ptr) /* succeeds if p is null */

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT

Generic Pointer:
When a variable is declared as being a pointer to type void it is known as a generic pointer. Since We

cannot have a variable of type void, the pointer will not point to any data and therefore cannot be dereferenced.
Generic Pointer is very useful when we want a pointer to point to data of different types at different times.
The following program describes the use of void pointer or Generic Pointer:
int main()
{
int i;
char c;
void *the_data;
i = 6;
c = 'a';
the_data = &i;
printf("the_data points to the integer value %d\n", *(int*) the_data);
the_data = &c;
printf("the_data now points to the character %c\n", *(char*) the_data);
return 0;
}
Passing Arguments to Functions using Pointers:
If we want to pass arguments(Single dimensional array) to a function, We have to declare a formal
parameter in one of following three ways and all three declaration methods produce similar results because each
tells the compiler that an integer pointer is going to be received. Similarly, We can pass multi-dimensional arrays as
formal parameters.
Way-1:
Formal parameters as a pointer
Syntax:
void myFunction(int *parameter)
{
…..
…..
}
Way-2:
Formal parameters as a sized array
Syntax:
void myFunction(int parameter[10])
{
…..
…..
}
Way-3:
Formal parameters as an unsized array −
Syntax:
void myFunction(int parameter[])
{
…..
…..
}

Example:
double getAverage(int arr[], int size)
{
int i;
float avg;
float sum = 0;
for (i = 0; i < size; ++i)
{
sum += arr[i];

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
}
avg = sum / size;
return avg;
}
Now, let us call the above function as follows
#include <stdio.h> /* function declaration */
double getAverage(int arr[], int size);
int main ()
{
int balance[5] = {1000, 2, 3, 17, 50}; /* an int array with 5 elements */
double avg;
avg = getAverage( balance, 5 ); /* pass pointer to the array as an argument */
printf( "Average value is: %f ", avg ); /* output the returned value */
return 0;
}
Output:
Average value is: 214.400000

Difference between Array and Pointer in C:


POINTER ARRAY
1. A pointer is a place in memory that keeps 1. An array is a single, pre allocated chunk of contiguous elements
address of another place inside (all of the same type), fixed in size and location.
2. Pointer can’t be initialized at definition. 2. Array can be initialized at definition. Ex: int num[]={2,3 }

3. Pointer is dynamic in nature. The memory 3. They are static in nature. Once memory is allocated , it
allocation can be resized or freed later. cannot be resized or freed dynamically.
4. The assembly code of Pointer is different
4. The assembly code of Array is different than Pointer.
than Array

Dynamic memory allocation in C:


The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at
runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.
1. malloc() 2. calloc() 3. realloc() 4. free()

The functions used for dynamic memory allocation.


malloc() allocates single block of requested memory.
calloc() allocates multiple block of requested memory.
realloc() reallocates the memory occupied by malloc() or calloc() functions.
free() frees the dynamically allocated memory.
1. malloc():

The malloc() function allocates single block of requested memory. It doesn't initialize memory at execution
time, so it has garbage value initially. It returns NULL if memory is not sufficient.
Syntax: ptr=(cast-type*)malloc(byte-size);
2. calloc():

The calloc() function allocates multiple block of requested memory. It initially initialize all bytes to zero. It
returns NULL if memory is not sufficient.
Syntax: ptr=(cast-type*)calloc(number, byte-size);

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
3. realloc():

If memory is not sufficient for malloc() or calloc(), we can reallocate the memory by realloc() function. In
short, it changes the memory size.
Syntax: ptr=realloc(ptr, new-size);
4. free():

The memory occupied by malloc() or calloc() functions must be released by calling free() function.
Otherwise, it will consume memory until program exit.
Syntax: free(ptr);

Difference between static memory allocation and dynamic memory allocation

STATIC MEMORY ALLOCATION DYNAMIC MEMORY ALLOCATION

memory is allocated at compile time. memory is allocated at run time.


memory can't be increased while executing program. memory can be increased while executing program.
used in array. used in linked list.

STRUCTURE IN C
Structure in c language is a user defined datatype that allows we to hold different type of elements. Each

element of a structure is called a member. It is widely used to store student information, employee information,
product information, book information etc.
Defining structure:
The struct keyword is used to define structure. The syntax to define structure in c is

struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};

Example:

struct book
{
int p;
float c;
char n[10;
};
Here, struct is the keyword, book is the tag name of structure; p, c and n are the members or fields of the
structure.
Declaring structure variable:
We can declare variable for the structure, so that we can access the member of structure easily. There are
two ways to declare structure variable:
1. By struct keyword within main() function
2. By declaring variable at the time of defining structure.
1 way:
st

Let's see the example to declare structure variable by struct keyword. It should be declared within the main
function. struct employee
{
int id;

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
char name[50];
float salary;
};
Now write given code inside the main() function. struct employee e1, e2;
2 nd
way:

Another way to declare variable at the time of defining structure.


struct employee
{
int id;
char name[50];
float salary;
}e1,e2;

Accessing members of structure:


There are two ways to access structure members:
1. By . (member or dot operator)

2. By -> (structure pointer operator)

The code to access the id member of p1 variable by . (member) operator p1.id


Example of C Structure:
#include <stdio.h>
#include <string.h>
struct employee
{
int id;
char name[50];
}e1; //declaring e1 variable for structure
int main( )
{
e1.id=101; //store first employee information
strcpy(e1.name, "Jagadeesh"); //copying string into char array
printf( "employee 1 id : %d\n", e1.id); //printing first employee information
printf( "employee 1 name : %s\n", e1.name);
return 0;
}
Output:
employee 1 id : 101
employee 1 name : Jagadeesh
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James
employee 2 salary : 126000.000000

Array of Structures in C:
There can be array of structures in C programming to store many information of different data types. The
array of structures is also known as collection of structures. This program shows the structure with array that stores
information of 3 students and prints it.
#include<stdio.h>
#include<string.h>
struct student
{
int rollno;
char name[10];
};
void main()
{

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
int i;
struct student st[2];
clrscr();
printf("Enter Records of 3 students");

for(i=0;i<2;i++)
{
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}

printf("\nStudent Information List:");


for(i=0;i<2;i++)
{
printf("\nRollno:%d\n, Name:%s\n",st[i].rollno,st[i].name);
}
getch();
}
Output:
Enter Records of 3 students
Enter Rollno:1
Enter Name:Jagadeesh
Enter Rollno:2
Enter Name:Jack
Student Information List:
Rollno:1, Name:Jagadeesh
Rollno:2, Name:Jack

Nested Structure in C:
Nested Structure can have another structure as a member. There are two ways to define nested structure in
c language:
1. By separate structure
2. By Embedded structure
1. Separate structure:

We can create 2 structures, but dependent structure should be used inside the main structure as a member.
Let's see the code of nested structure.
struct Date
{
int d;
int m;
int y;
};

struct Employee
{
int id;
char n[20];
struct Date doj;
} emp1;
In the above example, doj (date of joining) is the variable of type Date. Here doj is used as a member in
Employee structure. In this way, we can use Date structure in many structures.
2. Embedded structure:

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
We can define structure within the structure also. It requires less code than previous way. But it can't be
used in many structures.

struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}emp1;
Accessing Nested Structure:
We can access the member of nested structure by Outer Structure. Nested_ Structure.member as given
below:
e1.doj.dd
e1.doj.mm
e1.doj.yyyy

Example:
#include <stdio.h>
#include <string.h>
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}e1;

main( )
{
e1.id=101; //storing employee information
strcpy(e1.name,"Jagadeesh"); //copying string into char array
e1.doj.dd=10;
e1.doj.mm=11;
e1.doj.yyyy=2014;
printf( "employee id : %d\n", e1.id); //printing first employee information
printf( "employee name : %s\n", e1.name);
printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,1.doj.yyyy); return 0;
}
Output:
employee id : 101
employee name : Jagadeesh
employee date of joining (dd/mm/yyyy) : 10/11/2014

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT

C UNION
C Union:
In C, like structure, Union in c language is a user defined datatype that is used to hold different type of elements.
But it doesn't occupy sum of all members size. It occupies the memory of largest member only. It shares memory
of largest member.

Advantage of union over structure:


 It occupies less memory because it occupies the memory of largest member only.
Disadvantage of union over structure:

 It can store data in one member only.


Defining Union:
The union keyword is used to define union.
Syntax:
union union_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
Example:
union employee
{
int id;
char name[50];
float salary;
};
Example:
#include <stdio.h>
#include <string.h>
union employee
{
int id;
char name[50];
}e1; //declaring e1 variable for union
int main( )
{
e1.id=101; //store first employee information
strcpy(e1.name, "Jagadeesh"); //copying string into char array
printf( "employee 1 id : %d\n", e1.id); //printing first employee information
printf( "employee 1 name : %s\n", e1.name);
return 0;

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
}
Output: employee 1 id : 1869508435
employee 1 name : Jagadeesh

ENUMERATED DATA TYPES:

Enumerated data type variables can only assume values which have been previously declared.
enum month { jan = 1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec };

enum month m;

m = feb;
In the above declaration, month is declared as an enumerated data type. It consists of a set of values, jan
to dec. Numerically, jan is given the value 1, feb the value 2, and so on. The variable m is declared to be of the
same type as month, then is assigned the value associated with feb. m cannot be assigned any values outside those
specified in the initialization list for the declaration of month.
#include <stdio.h>
main()
{
char *pwest = "west";
*pnorth = "north";
*peast="east",;
*psouth = "south";
enum location { east=1, west=2, south=3, north=4};
enum location direction;
direction = east;
if( direction == east )
{
printf("Cannot go %s\n", peast);

}
getch();
}
The variables defined in the enumerated variable location should be assigned initial values.

FILE HANDLING IN C
File Handling in c language is used to open, read, write, search or close file. It is used for permanent storage.
Advantage of File:
It will contain the data even after program exit. Normally we use variable or array to store data, but data is
lost after program exit. Variables and arrays are non-permanent storage medium whereas file is permanent storage
medium.
File Handling Functions:

There are many functions in C library to open, read, write, search and close file. A list of file functions
are given below:
S.No. FUNCTION DESCRIPTION
1 fopen() opens new or existing file
2 fprintf() write data into file
3 fscanf() reads data from file
4 fputc() writes a character into file
5 fgetc() reads a character from file
6 fclose() closes the file
7 fseek() sets the file pointer to given position

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
8 fputw() writes an integer to file
9 fgetw() reads an integer from file
10 ftell() returns current position
11 rewind() sets the file pointer to the beginning of the file

We can use one of the following modes in the fopen() function.

MODE DESCRIPTION
r opens a text file in read mode
w opens a text file in write mode
a opens a text file in append mode
r+ opens a text file in read and write mode
w+ opens a text file in read and write mode
a+ opens a text file in read and write mode
rb opens a binary file in read mode
wb opens a binary file in write mode
ab opens a binary file in append mode
rb+ opens a binary file in read and write mode
wb+ opens a binary file in read and write mode
ab+ opens a binary file in read and write mode

1. Opening File: fopen():

The fopen() function is used to open a file. The syntax of fopen() function is
Syntax: FILE *fopen( const char * filename, const char * mode );
Example: fptr = fopen("emp.txt", "w+");
2. Closing File: fclose():

The fclose() function is used to close a file. The syntax of fclose() function is

Syntax: int fclose( FILE *fp );


Example: fclose(fptr);
3. Reading Files:

The following File Handling functions are used to read data from files.
a. fscanf() b. fgetc() c. fgets()

a. fscanf() function:

The fscanf() function is used to read data from files. It sends formatted input from a stream.
Syntax: int fscanf(FILE *stream, const char *format [, argument, ...]);
Example: fscanf(fptr, "Id= %d\n", id);
b. fgetc() function:
The fgetc() function returns a single character from the file. It gets a character from the stream. It returns
EOF at the end of file.
Syntax: int fgetc(FILE *stream);
Example: c=fgetc(fp);
c. fgets() function:

The fgets() function reads a line of characters from file. It gets string from a stream.
Syntax: char* fgets(char *s, int n, FILE *stream);
Example: printf("%s",fgets(text,200,fp));
4. Writing Files:

The following File Handling functions are used to write data into files.
a. fprintf() b. fputc() c. fputs()

a. fprintf() function:
The fprintf() function is used to write set of characters into file. It sends formatted output to a stream.

Syntax: int fprintf(FILE *stream, const char *format [, argument, ...]);

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
Example: fprintf(fptr, "Id= %d\n", id);
b. fputc() function:

The fputc() function is used to write a single character into file. It outputs a character to a stream.
Syntax: int fputc(int c, FILE *stream);
Example: fputc(ch, fp);

c. fputs() function:
The fputs() function writes a line of characters into file. It outputs string to a stream.
Syntax: int fputs(const char *s, FILE *stream);
Example: fputs("hello c programming",fp);

5. fseek() function:

The fseek() function is used to set the file pointer to the specified offset. It is used to write data into file at
desired location.
Syntax: int fseek(FILE *stream, long int offset, int whence);
Example: fseek( fp, 7, SEEK_SET );
There are 3 constants used in the fseek() function for whence: SEEK_SET, SEEK_CUR and SEEK_END.
6. rewind() function:

The rewind() function sets the file pointer at the beginning of the stream. It is useful if we have to use
stream many times.
Syntax: void rewind(FILE *stream);
Example: rewind(fp);
7. ftell() function:

The ftell() function returns the current file position of the specified stream. We can use ftell() function to get
the total size of a file after moving file pointer at the end of file. We can use SEEK_END constant to move the file
pointer at the end of file.
Syntax: long int ftell(FILE *stream);
Example: length = ftell(fp);

Storing employee information in C Files:


A file handling example to store employee information as entered by user from console. We are going to
store id, name and salary of the employee.
#include <stdio.h>
void main()
{
FILE *fptr;
int id;
char name[30];
float salary;
fptr = fopen("emp.txt", "w+"); /* open for writing */
if (fptr == NULL)
{
printf("File does not exists \n");
return;
}
printf("Enter the id\n");
scanf("%d", &id);
fprintf(fptr, "Id= %d\n", id);
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name= %s\n", name);
printf("Enter the salary\n");
scanf("%f", &salary);
fprintf(fptr, "Salary= %.2f\n", salary);
fclose(fptr); }
Output:
Enter the id
1
Enter the name
Jagadeesh

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13


DEPARTMENT OF COMPUTER SCIENCE
YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, 2017-2018
SAMALKOT
Enter the salary
emp.txt
Id= 1
Name= Jagadeesh
Salary= 25000

Sem-2, Programming in ‘ c ‘ By Y Jagadeesh, 92 46 66 66 46 13

You might also like