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

YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

Final B.Com Computer


Applications
5th Sem, 2018

programming in c

very Graduate should leave the College with a Degree in one hand
and a Placement order in other hand
Y Jagadeesh
Department of Computer Science
924 66 666 46
Kakinada
ADIKAVI NANNAYA UNIVERSITY, RAJAHMUNDRY

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

CBCS/Semester System (W.e.f. 2015-16 Admitted Batch)


V 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. Introduction to C: 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 – Go to
Statement

UNIT-III:
Functions: Introduction – using functions – Function declaration/ prototype – Function definition –

function call – return statement – Passing parameters – Scope of variables – Storage Classes –
Recursive function

UNIT- IV:
Arrays: Introduction – Declaration of Arrays – Accessing elements of the Array – Storing Values in

Array – Calculating the length of the Array – Operations on Array – one dimensional array for inter-
function communication – Two dimensional Arrays –Operations on Two Dimensional Arrays, Strings:
Introduction String and Character functions

UNIT-V:
Pointers: Understanding Computer Memory – Introduction to Pointers – declaring Pointer Variables – -

Passing Arguments to Functions using Pointer – Pointer and Arrays – Passing Array to Function.
Structure, Union, and Enumerated Data Types: Introduction – Nested Structures – Arrays of Structures
– Structures and Functions - Unions – Enumerated Data Types.

ADIKAVI NANNAYA UNIVERSITY: RAJAMAHENDRAVARAM

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

QUESTION PAPER PATTERN FOR ALL SEMESTER W.E. FROM 2016-17 ADMITTED BATCH
(For all Papers except Foundation Course papers & Special English Paper )
Time: 3 Hours Maximum Marks: 75
Section - A
I. Answer any Five questions
5 X 5 = 25 Marks
1. Unit- I
2. Unit- II
3. Unit-III
4. Unit- IV
5. Unit-V
6.
7.
8. Each one from any of
the three units out of
five units.

Section- B
II. Answer All the Questions
5 X 10 = 50 Marks
1. (a) or (b) from Unit -I
2. (a) or (b) from Unit -II
3. (a) or (b) from Unit -III
4. (a) or (b) from Unit -IV
5. (a) or (b) from Unit -V
ADIKAVI NANNAYA UNIVERSITY, RAJAHMUNDRY
CBCS/Semester System (W.e.f. 2015-16 Admitted Batch)
V SEMESTER, COMPUTER APPLICATIONS
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 [Page No.13 to14]
2. What is type casting ? Explain [Page No.13 to14]
3. Explain switch statement with example [Page No.21 to22]
4. What is recursive function? Explain [Page No.33 to34]
5. Explain various string handling functions [Page No.32 to33]
6. Explain the difference between Structure and Union [Page No.45 & 49]
7. Explain pointer and structures [Page No.42 to 43& 45]
8. Write a short notes on Enmurated data types [Page No. 50]
Section – B
Answer All Questions
5 X 10 = 50 Mark
A. Write algorithm and draw flowchart to find the roots of quadratic equation [Notes] OR
B. Explain the various operators in C [Page No.16 to 19]
A. Explain the various looping structures [Page No.22 to 24] OR
B. Write a C program to generate prime numbers up to 20 [Notes]
A. Explain the various types of arrays [Page No.36 to 38] OR
B.Write a C program to find the product of the two matrices [Notes]
A. Explain structure arrays and structure within structures [Page No.46 to 47] OR
B. Write a C program to find the smallest of the given numbers using pointers [Notes]
A. Differentiate Structures and Unions. [Page No.45 & 49] OR
B. Write about array of structures with suitable example. [Page No.45]
ADIKAVI NANNAYA UNIVERSITY, RAJAHMUNDRY

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

CBCS/Semester System (W.e.f. 2015-16 Admitted Batch)


V SEMESTER, COMPUTER SCIENCE
NOVEMBER-2017 Programming in C
Section – A
Answer Any Five Questions
5 X 5 = 25 Marks
1. Draw FlowChart for comparision Of three numbers [Notes]
2. Write Syntax of C Program with suitable example[Page No.9 & 10]
3. Differentiate break and continue [Page No.24 to 25]
4. Describe about different Storage classes [Page No.34 to 35]
5. Write a C progam to find factorial of a given number using recursion [Page No.34]
6. How to declare and initialize the arrays? give an example [Page No.36 to 38]
7. What is pointer What are the advantages of Pointers [Page No.42 to 43]
8. Write a short notes on Enmurated data types [Page No. 50]
Section – B
Answer All Questions
5 X 10 = 50 Marks
1. A. Discuss various categories of Operators in C. [Page No.16 to 19] OR
B. What is an Algorithm? Describe key features of Algorithm? Write an algorithm to find
sum of N natural number. [Page No.7 & Notes]

2. A. Explain about while, do-while and for loop with suitable examples [Page No.22 to 24] OR
B. Write a C program to compute sum of individual digits of given number( 123=1+2+3=10) [Notes]

3. A. Discuss different categories of user define functions illustrate with examples [Page No.26 &27 to 29 ]
OR
B. Explain about the different paratemer passing mechanism of the functions [Page No.30 to 31]

4. A. Write about various String handling functions used in with syntax [Page No.32 to33] OR
B. Write a C program to find the multiplication of two matrics. [Notes]

5. A. Explain the following: 1.Pointer Function. 2. Nested Structures. [Page No.31 & 47] OR
B. 1. Differentiate Structures and Unions. [Page No.45 & 49]
2. Write about array of structures with suitable example [Page No.45]

UNIT-I
ALGORITHM:

An algorithm is a procedure or formula for solving a problem, based on conducting 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. Algorithms can be combined to perform complex tasks such as writing a computer

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

programs.
5.It is a step by step repetition of a solution to a given problem, which is very easy to understand.
6.It has got a definite procedure.
7.It easy to first develop an algorithm & then covert it into a flowchart& then into a computer program.
8.It is independent programming language.
9.It is easy to debug as every step is got its own logical sequence
ALGORITHM REPRESENTATION OF COMPUTER FUNCTIONS:

 INPUT - get information-input

 STORAGE- storage information-given/result

 PROCESS-arithmetic -let(assignment command)

Repeat instructions -loop


Branching conditional - if
DISADVANTAGES OF ALGORITHM

 It is time consuming
 It is more complexity
 it as an algorithm is developed first which is converted into flowchart and then in to a computer
program.

what is flowchart? explain about various flowchart symbols and features of flowchart?
FLOWCHART:

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.
Guidelines 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 flowcharts must be Top to Bottom or Left to Write
3. Keeping the arrow flow to one side
5. Drawing a flowchart, use same size symbols
6. Naming the decision blocks, processes, arrows etc are few things you can do to make it
better.
Flowchart Symbols:

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

Flowchart is a graphical or pictorial representation of an algorithm. 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 their meaning.

PROGRAM FLOWCHART:

It shows the sequence of instructions in a program or subroutine. These instructions are


followed to procedure the needed program.

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.

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

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)
2. Machine Independent or Portable:

C Programs can be executed in many machines with little bit or no change.


3. Mid-level Prorgramming language:

C is also used to do low level programming . It also supports the feature of high level language . That is
why it is known as mid-level language.
4. Structured prorgramming language:

C is a structured programming language in the sense that we can break the program into parts using

functions.

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.

7. Speed:

The compilation and execution time of C language is fast.

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

8. Pointers:

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.

10. Extensible:

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

[STRUCTURE OF A C -PROGRAM:

A C program basically consists of the following parts Preprocessor Commands


1. Functions 2. Variables
3. Statements & Expressions 4. 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. ]
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.

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

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 Open a

text editor and add the above-mentioned code.


1. Save the file as hello.c

2. Open a command prompt and go to the directory where you have saved the file.
3. open hello.c and press Ctrl F9 to compile your code.
4. 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.
5. Now, type hello.exe to execute your program.
6. 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
Example:

//printing information
printf("Hello C");
2. Mult Line Comments:

Multi line comments are represented by slash asterisk \* ... *\. It can occupy many lines of code
but it can't be nested.
An example of multi line comment in C.
/*printing
information*/
printf("Hello C");
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:

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

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.
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):

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

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_name or variables_list;

Where the Data types can be int (integer), char (character), float (real) etc
The example of declaring variable is given below:
Ex1: int a; Ex2: float b; Ex3: char c; Ex4: char n[10]; Ex5: 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 Ex:. int, float etc.

C - CONSTANTS and 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 constant is known as a string of digits without decimal point. It can be a decimal,
octal, or hexadecimal constant.
Examples of integer literals:
1. 85 /* decimal */ 2. 0213 /* octal */ 3. 0x4b /* hexadecimal */
4. 30 /* int */ 5. 30u /* unsigned int */ 6. 30l /* long */
7. 30ul /* unsigned long */
2. Floating-point Constants or Literals:

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

A float constant is known as a string of digits with decimal point. A floating-point literal has an
integer part, a decimal point or a fractional part, and an exponent part. Examples of floating-point literals
1. 3.14159 2. 314159E-5L
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').
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.
1. “ YRL COLLEGE “ 2. “ JAGADEESH ” 3. “ A9*ABC “
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.
They are 4 types of data types are there (1) integer (2)character (3 )flaot (4)double

(1)Integer datatype:

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

 Integer datattype allow a variable a store numerical value.


 Int keyword are used in integer datatype.
 Int(2 byte) can store value from -32768 to +32767
 Int(4 byte) can store value from -2,147,483,648 to + 2,147,483,647.
 Here, “%d” is a format specification for integer variables.
(2) character datattype:
 character datatype allow a variable to store only one character.
 Size of character datatype is 1.we can store only one character using character datatype.
 “char” keyword is used to refer character datatype.
 For example,’a’ can be stored using char datatype. you data can’t store more then one
charcter using character datatype .
 Charcter datatype store value singed charcter are -127 to +128 and unsigned characters
are 0 to 255.
Here, “%ch” is a format specification for character datatype.
(3)float datatype:
 float datatype allows a variable to store decimal values.
 Storage of float datatype is 4.
 We can use upto 6 digits after decimal using as int datatype.
 Eg.10.546789 can stored in variable using float datatype.
 The range of float 1.2e-3.8 to3.4e-3.8.
 Here,”%f” is a format specification for float datatype.

(4)double datatype:
 Double datatype is also same as flaot datatype which allows upto 10 digits after
decimal.
 The range of 8bytes 1e-3.7 to1e-3.7
 Here, “%lf” is a format specification for double datatype.
Enumerated datatype:
 Enumeration datatype consists named integers constant as a list.
 It starts with 0 by default and value is incremented by 1 for the sequential identifiers list.
 Enumerated sytax in c
Enum identifier[ optional{enumerated list}];
 Here you want use “#define” is preprocessor directive.
Void datatype:
 Void is an empty datatype that has no value.

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

 This can be used in functions and pointers.

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

INPUT & OUT PUT STATEMENTS IN C:


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 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 ");


Ex: 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.
Ex1: printf(" %d ", a );
Ex2: printf(" %d %f %c", a,b,c );
Ex3: printf(" %d\n %d\n %d\n", x,y,z);
Syntax3:

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

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

Where the format string can be %d (integer), %c (character), %s (string), %f (float) etc
Ex1: printf(" The result is %d ", R);
Ex2: printf("%d is result ", R);
Ex3: Printf(" The result %d is", R);

Formatted 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.
Ex1: scanf(" %d ", &a );
Ex2: printf(" %d %f %c", &a,&b,&c );
Ex3: printf(" %d\n %d\n %d\n",&x,&y,&z);
Unformatted String Input and Output Functions (gets(): and puts())in C :

The gets() and puts() functions are unformatted String Input and Output functions. Both
functions are defined in <stdio.h> header file.
Unformatted String Input gets() function:

In C language, the gets()function reads string from user. The general format of gets() function is
Syntax:
gets(string variable);
Example:
gets(name);

Unformatted String Output puts() function:

In C language, the puts() function prints the string. The general format of puts() function is
Syntax:
puts(string variable);
Example:
puts(name);

Unformatted Character Input and Output (getchar() & putchar()) functions:

The getchar() and putchar() functions are unformatted character Input and Output functions. Both
functions are defined in <stdio.h> header file.

Unformatted Character Input getchar() function:

The getchar() function reads a character from the terminal and returns it as an integer. This
function reads only single character at a time. You can use this method in a loop in case you want to
read more than one character. The syntax is
Syntax:
<character Variable>=getchar();
Example:
c=getchar();

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

Unformatted Character Output putchar() function:

The putchar() function displays the character passed to it on the screen and returns the same
character. This function displays only a single character at a time. In case you want to display more
than one characters, use putchar() method in a loop.
Syntax:
putchar(character Variable);
Example:
putchar(C);

[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
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
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.
3. > Checks if the value of left operand is greater than the value of right (a > b) is not true.

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

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
&& (Logical AND) If both the operands are non-zero, then the condition becomes true. Ex: (A && B)
1
is true.

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

! (Logical NOT) Reverses the logical state of its operand. If a condition is true, then the Logical NOT
3
operator will 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 O perators −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.

^ (Bitwise XOR) It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR
3
means 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
6
specified by 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
7
are always zero. Ex: (A >>> 1) is 1.

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

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
1
assign the value of A + B into C

+= (Add and Assignment) It adds the right operand to the left operand and assigns the result to the left operand.
2
Ex: C += A is equivalent to C = C + A

−= (Subtract and Assignment)It subtracts the right operand from the left operand and assigns the result to the
3
left operand. Ex: C -= A is equivalent to C=C–A

*= (Multiply and Assignment) It multiplies the right operand with the left operand and assigns the result to the
4
left operand. Ex: C *= A is equivalent to C = C * A

/= (Divide and Assignment) It divides the left operand with the right operand and assigns the result to the left
5
operand. Ex: C /= A is equivalent to C = C / A

%= (Modules and Assignment) It takes modulus using two operands and assigns the result to the left operand.
6
Ex: C %= A is equivalent to C = C % A

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 AND 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;

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

printf("f : %d\n", f );//Output: 2


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>
#include <conio.h>
void main()
{
clrscr();
float f= (float)9/4;
printf("f : %f\n", f );
getch();
}
Two types of conversions are there implicit and explicit.
Implicit: when the type coversion is performed automatically by the compiler with out programmers
intervention.
Ex:int x
For(x=97;x<=122;x++)
{
Printf(“%ch”,x);
}
Explicit:the type conversion performed by the programmer by passing the datatype of the expression
of specific type is known as explicit conversion
Ex: int x;
For(x=97;x<=122;x++)
{
Printf(“%ch”,(char)x);
}
 All the integers are converted to float
 All float types to be converted to double.
 All character types to be converted to integer.
 Examples, int x=7,y=5;
Float z;
Z=(float)x\(float)y;

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

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

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 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
}
Example:
if(a<b)
printf("%d is is small",a);
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:
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
Example:
if(a<b)
printf("%d is small",a);
else
printf("%d is small",b);

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

Example:

if(a<b && a<c)

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

printf("The Smallest Number is : %d “, a);


else
if(b<a && b<c)
printf("The Smallest Number is : %d “, b);
else
printf("The Smallest Number is : %d “, c);

4. Conditional Operator( ? : ): which can be used to replace if...else statements.


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:
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;
}
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.


Example:
char ch='b';
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”);}]
[2. Decision Making and Looping Statements:

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

(Iterative Statements or Control Structures):


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 long 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:
i=1;
while(i<=n)
{
printf(“%d \n “, i);
i++; }
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;

do
{
Statement or Statements;
----------
---------- //body of the loop 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: i=1;
do
{
printf(“%d \n “, i);

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

i++;
}while(i<=n);
Difference Between Entry Controlled And 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); i++; } printf(“%d \n “, 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)
{
Statement or Statements;
----------
----------
---------- //body of the loop code to be executed
}
Example:
for( i=1; i<=n; i++)
{
printf(“%d \n “, i);
}
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
}
Example:

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


{
for(j=1;j<=2;j++)
{
printf(“%d \n “, j);

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

}
} ]
[C Transfer statements: ( break & continue ):
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:
1. 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.
Syntax: for (Initialization Statements; Test Condition; Iteration Statements)
{
Statement or Statements;
----------
---------- //body of the loop code to be executed
if( Test Condition )
break;
}
Example:
for( i=1; i<=5; i++)
{if (i==3)
break;
printf(“%d \n “, i);}

C 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:
for( i=1; i<=5; i++)
{
if (i==3)
continue;]
}
C goto statement(Unconditional Transfer or Jumping Statement):
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.
Syntax:

gotolabel Name;
goto Jack;
Example to use goto statement in C language.
#include <stdio.h>
main()
{
int age;

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

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();
}

UNIT-III

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

FUNCTIONS
Function:

A function is a group of statements that together perform a specific task. Every C program has
at least one function, which is main(). A function can also be referred as a method or a sub-routine or a
procedure, etc. A function definition in C programming consists of a function header and a function
body. Here are all the parts of a function
1. Return Type: A function may return a value. The return_type is the data type of the value the function
returns. Some functions perform the desired operations without returning a value. In this case, the
return_type is the keyword void.

2. Function Name: This is the actual name of the function. The function name and the parameter list
together constitute the function signature.
3. Parameters: A parameter is like a placeholder. When a function is invoked, We pass a value to the
parameter. This value is referred to as actual parameter or argument. The parameter list refers to the
type, order, and number of the parameters of a function. Parameters are optional; that is, a function
may contain no parameters.
4. Function Body: The function body contains a collection of statements that define what the function
does.
Types of functions:

In C, afunctions are basically two types namely


1. Library functions
2. User defined functions
1. Library functions:

The C standard library provides various built-in functions that your program can call. For
example, strcat() to concatenate two strings, sqrt() to find squareroot of the given number and many
more functions.
[2. User defined functions:

These functions are defined by user. User can divide up code into separate functions. How the
user divide up the code among different functions is users choice, but logically the division is such that
each function performs a specific task.]
Function Declarations:

A function declaration tells the compiler about a function name and how to call the function. The
actual body of the function can be defined separately. The general format of the
function declaration is
Syntax:
<retur type or prototype> <name of the function>( with or without parameters list);
Example:
int add(int x, int y);

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

Defining a Function or Function declaration:

A function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function. The general form of a function definition in C
programming language is as follows
Syntax:

<return type or prototype> <name of the function>( with or without parameters list)
{
body of the function /* function defination */
}
Example:
int jack(int x, int y)
{
int z; / * function defination */
z=x+y;
return(z);
}
Calling a Function:

When a program calls a function, the program control is transferred to the called function. A
called function performs a defined task and when its return statement is executed or when its
function-ending closing brace is reached, it returns the program control back to the main program. To
call a function, you simply need to pass the required parameters along with the function name, and if
the function returns a value, then you can store the returned value.
Syntax:
<name of the function>(with or without parameters);
Example:
main()
{
int a=10;
int b=20;
int c;
c=jack(a,b); /* function calling */
printf(" The addition of given two Numbers is : %d", c);
}
[Types of user defined Functions:
User defined or Library functions are basically classified into three types. They are
1. Function without arguments
2. Function with arguments
3. Function with arguments and return value
1. Function without arguments:

In Function without arguments,function defination consists of function's name, return type


only . A function definition provides the actual body of the function. The general form of a function
definition in C programming language is as follows
Syntax:
<return type or prototype> <name of the function>() /* No parameters */
{
body of the function /* function defination */
}

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

Example:
int jack()
{
int z; / * function defination */
z=x+y;
Printf("The Addition of the given two numbers is %d", z);
}
Sample program for Function without parameters:
Example:
#include<stdio.>
main()
{
clrscr();
add();
sub();
getch();
}
void add()
{
int a,b,c;
printf(" Enter any Two values ");
scanf("%d %d",&a,&b);
c=a+b;
printf(" The Addition of the given two numbers is %d", c);
}
void sub()
{
int a,b,c;
printf(" Enter any Two values ");
scanf("%d %d",&a,&b);
c=a-b;
printf(" The Subtraction of the given two numbers is %d", c);
}

2. Function with Arguments:

A function may one or more parameters or arguments. These functions can have type
parameters such as int, float, char, String,. These parameters are also known as formal parameters or
arguments. The general format Declaration of Function with arguments is
Syntax:
<return type or prototype> <name of the function>(data type parameter1, data type parameter1,....
, data type parameter-n)
{
------------;
------------; Body of the function
------------;}
Example:
#include<stdio.>
main()
{
int a,b,c;
printf(" Enter any Two values ");
scanf("%d %d",&a,&b);
clrscr();
add(int a, int b);
sub(int a, int b);
getch();
}

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

void add(int x, int y)


{
int z;
z=x+y;
printf(" The Addition of the given two numbers is %d", z);
}
void sub(int x, int y)
{
int z;
z=x-y;
printf(" The Subtraction of the given two numbers is %d", z);
}

2. Function with Arguments and return value:

To return any value from the function, We need to use any data type such as int, float, char,
String,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 dont't return a value use void for the return
type. The general format Declaration of Function with arguments and return is

Syntax:
<return type or prototype> <name of the function>(data type parameter1, data type parameter1,....
, data type parameter-n)
{
------------;
------------; Body of the function
------------;
return(exp/const/var); / *Syntax of return statement */
}

Example:
#include<stdio.>
main()
{
int a,b,c;
printf(" Enter any Two values ");
scanf("%d %d",&a,&b);
clrscr();
c=add(int a, int b);
printf(" The Addition of the given two numbers is %d", c);
c=sub(int a, int b);
printf(" The Addition of the given two numbers is %d", c);
getch();
}
void add(int x, int y)
{
int z;
z=x+y;
return(z); / *Example of return statement */
}
void sub(int x, int y)
{ return(x-y);
}
]

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

[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.

a. 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 you 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 is
Example:
#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

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

b. 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 shares the same address space.
Hence, value changed inside the function, is reflected inside as well as outside the function. The
concept of call by reference in c language is
#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 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
2 Changes made inside the function is not Changes made inside the function is reflected outside the
reflected on other functions function also
3 Actual and formal arguments will be created Actual and formal arguments will be created in same
in different memory location memory location

By default, C uses call by value to pass arguments. In general, it means the code within a
function cannot alter the arguments used to call the function. ]

2. Library Functions:

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

The C standard library provides various built-in functions that your program can call. For
example, strcat() to concatenate two strings, sqrt() to find squareroot of the given number and many more
functions.

[String Functions:
String: In C language is an array of characters that is terminated by \0 (null character). There
many important string functions defined in "string.h" library.
String Taxonomy or String Operations or String functions:

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.

strcat(first_string, concats or joins first string with second string. The result of the string
3
second_string) is stored in first string.

strcmp(first_string, compares the first string with second string. If both strings are same,
4
second_string) 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);

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

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);

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:
The ctype.h header file of the C Standard Library declares several functions that are useful for testing and
mapping characters.
All the functions accepts int as a parameter, whose value must be EOF or representable as an unsigned
char. All the functions return non-zero (true) if the argument c satisfies the condition described, and zero(false) if
not. Following are the functions defined in the header ctype.h
S.N. Function & Description
1 int isalnum(int c): This function checks whether the passed character is alphanumeric.
2 int isalpha(int c): This function checks whether the passed character is alphabetic.
3 int isdigit(int c): This function checks whether the passed character is decimal digit.
4 int islower(int c): This function checks whether the passed character is lowercase letter.
5 int ispunct(int c): This function checks whether the passed character is a punctuation character.
6 int isspace(int c): This function checks whether the passed character is white-space.
7. int isupper(int c): This function checks whether the passed character is an uppercase letter.

Conversion Functions:

The library also contains two conversion functions that accepts and returns an "int".
S.N. Function & Description
1 int tolower(int c): This function converts uppercase letters to lowercase.
2 int toupper(int c): This function converts lowercase letters to uppercase.

[Recursive functions:
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. The general format of recursive function is
Syntax:
<prototype> <name of the Recursive function>( with or without arguments)

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

{
body of the function;
------------; Body of the function
------------;
recursion 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()
{
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

Types of Recursions:

Following variants of recursion tell us making recursive calls in different ways depending upon the problem .

1. Linear Recursion 2. Binary Recursion 3. Tail Recursion


4. Mutual Recursion 5. Nested Recursion]

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-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

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

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

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;


UNIT-IV
C 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.
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

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 is
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.

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

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
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:

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

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 Function in C:

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:

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

return_type function(type arrayname[SIZE])

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


Third way:
return_type function(type *arrayname)
Example:
C language passing array 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

1. Traversing: It is used to access each data item exactly once so that it can be processed.
Example:

We have linear array A as below:


1 2 3 4 5
10 20 30 40 50
Here we will start from beginning and will go till last element and during this process we will access value
of each element exactly once as below:
A [1] = 10 A [2] = 20 A [3] = 30 A [4] = 40 A [5] = 50
2. Searching: It is used to find out the location of the data item if it exists in the given collection of
data items.
Example:

We have linear array A as below:


1 2 3 4 5
15 50 35 20 25

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

Suppose item to be searched is 20. We will start from beginning and will compare 20 with each element.
This process will continue until element is found or array is finished. Here:
1. Compare 20 with 15
20 # 15, go to next element.
2. Compare 20 with 50
20 # 50, go to next element.
3. Compare 20 with 35
20 #35, go to next element.
4. Compare 20 with 20
20 = 20, so 20 is found and its location is 4.

3. Insertion: It is used to add a new data item in the given collection of data items.
Example:
We have linear array A as below:
1 2 3 4 5
10 20 50 30 15

New element to be inserted is 100 and location for insertion is 3. So shift the elements from 5th location to 3rd
location downwards by 1 place. And then insert 100 at 3rd location. It is shown below:

4. Deletion: It is used to delete an existing data item from the given collection of data items.
Example:

We have linear array A as below:

1 2 3 4 5
10 20 50 40 25 60

The element to be deleted is 50 which is at 3rd location. So shift the elements from 4th to 6th location upwards by
1 place. It is shown below:

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

After deletion the array will be:


1 2 3 4 5 6
10 20 40 25 60
5. Sorting: It is used to arrange the data items in some order i.e. in ascending or descending
order in case of numerical data and in dictionary order in case of alphanumeric data.
Example:

We have linear array A as below:

1 2 3 4 5
10 50 40 20 30
After arranging the elements in increasing order by using a sorting technique, the array will be:
1 2 3 4 5
10 20 30 40 50

6. Merging: It is used to combine the data items of two sorted files into single file in the sorted

form We have sorted linear array A as below:


1 2 3 4 5 6
10 40 50 80 95 100
And sorted linear array B as below:
1 2 3 4
20 35 45 90
After merging merged array C is as below:
1 2 3 4 5 6 7 8 9 10
10 20 35 40 45 50 80 90 95 100

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
2. By string literal
Declaring Strings in C Language:

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

Example of declaring string by char array in C language.


char ch[10]={‘y’,'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 10
j a G a d e e s 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 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

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

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
Address stored in a variable: bffd8b3c

Value of *a variable: 20 ]

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])
{
…..

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

…..
…..
}
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];
}
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. An array is a single, pre allocated chunk of


1. A pointer is a place in memory that keeps
contiguous elements (all of the same type),
address of another place inside
fixed in size and location.
2. Array can be initialized at definition. Example
2. Pointer can’t be initialized at definition.
int num[] = { 2, 4, 5}
3. Pointer is dynamic in nature. The memory 3. They are static in nature. Once memory is
allocation can be resized or freed later. allocated , it cannot be resized or freed

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

dynamically.
4. The assembly code of Pointer is different 4. The assembly code of Array is different than
than Array Pointer.

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;
floatc;
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.

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

]
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.
1st way:

Let's see the example to declare structure variable by struct keyword. It should be declared within the
main function. struct employee
{
int id;
char name[50];
float salary;
};
Now write given code inside the main() function. struct employee e1, e2;
2nd 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

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

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 : Radhika
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<conio.h>
#include<string.h>
struct student
{
int rollno;
char name[10];
};
void main()
{
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 2 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

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

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:

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];

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

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;
} ]

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:

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2


YRL COLLEGE OF ARTS, SCIENCE & TECHNOLOGY, SAMALKOT 2019-2020

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;
}
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.]

Sem-4, Programming in ‘ c ‘ By Jagadeesh Software Solutions Kakinada, 924 66 666 46 2

You might also like