You are on page 1of 228

‘C’ Programming Language

Introduction
The C language is the most frequently used language for writing system software
such as operating systems, programming languages and compilers.

It is also widely used for developing applications

The BCPL (Basic Combined Programming Language) is a computer


programming language designed by Martin Richards, of Cambridge University in
1966

Later, ‘B’ was developed by Bell Labs

‘B’ It is a programming language which has some complexities

Then, Dennis Ritchie and Ken Thomson was improved B language at AT &
T[telephone] Bell Laboratories in 1972

They called the new language C and it can be used on various types of
computers

What is C?
‘C’ language is a structured and procedural programming language

It is a powerful and flexible language which can be used for a variety of


applications, from business programs to engineering
‘C’ language is particular a popular language for programmers of PCs (Personal
Computer) because it is relatively

small; and it requires less memory than other languages

Many versions of the Unix-based operating systems are written in ‘C’

It is a high-level language

‘C’ language is much closer to the assembly language then the majority of the
other high-level languages.

An assembly language is a program written for a type of operating system


which we cannot run on other operating systems

Sr. High level Middle level Low level


No.
1 High level languages Middle level languages Low level
provide almost don’t provide all the built- languages provides
everything that the in functions found in high nothing other than
programmer might need level languages, but access to the
to do as already built provides all building machines basic
into the language blocks that we need to instruction set
produce the result we
want

2 Examples: Java, Python C,C++ Assembler

It is easier to learn C if you can compare it to a language you already know.


Because the C language has many features and advantages.

Features of the ‘C’ Language


 Operating system portability

We can write a C program in an operating system and this program can be carried
out in another Operating System.

 Highly efficient object code

This is a computer code which helps to execute our program quickly.

 Support of structured programming

The C language has a standard programming format. Each program must have the
main function and other attributes.

 Standard function libraries

The C language is entirely integrated with the functions which are stored in the
library.

 Ease of access to hardware features

C language supports writing programs to affect the hardware such as memory


management, process scheduling etc.

How ‘C’ Program Works?


 Firstly, the program is written in the form of number of text files using a
screen editor.
— This form of the program is called the source program.
— It is not possible to execute this file directly.
 Secondly, the completed source file is passed to a compiler
— (Compiler is a program which generates a new file containing a
machine code translation of the source text).
— This file is called an object file

Basic structure of C program


Structure of C program is defined by set of rules called protocol, to be followed by
programmer while writing C program.

All C programs are having sections/parts which are mentioned below.

 Documentation section
 Link Section
 Definition Section
 Global declaration section
 Function prototype declaration section
 Main function
 User defined function definition section
1. Documentation section: The documentation section consists of a
set of comment lines giving the name of the program, the author
and other details, which the programmer would like to use later.
2. Link section: The link section provides instructions to the
compiler to link functions from the system library such as using
the #include directive.
3. Definition section: The definition section defines all symbolic
constants .
4. Global declaration section: There are some variables that are
used in more than one function. Such variables are called global
variables and are declared in the global declaration section that is
outside of all the functions. This section also declares all the user-
defined functions.
5. main () function section: Every C program must have one main
function section. This section contains two parts; declaration part
and executable part
1. Declaration part: The declaration part declares all
the variables used in the executable part.
2. Executable part: There is at least one statement in the
executable part. These two parts must appear between the
opening and closing braces. The program execution begins at
the opening brace and ends at the closing brace. The closing
brace of the main function is the logical end of the program.
All statements in the declaration and executable part end with
a semicolon.
6. Subprogram section: If the program is a multi-function
program then the subprogram section contains all the user-defined
functions that are called in the main () function. User-defined
functions are generally placed immediately after the main ()
function, although they may appear in any order.
All section, except the main () function section may be absent when they
are not required.

Following is a sample C Program that contains all of the above


mentioned sections

?
1 /*
2 * Name: Sample Program
3 * Author: OnlineClassNotes.COM
* Create Date: 26/11/2016
4
* Last Modified: 27/11/2016
5 */
6
7 //Linking required library
8 #include <stdio.h>
9
10 //defining a constant
#define MAX_ARRAY_LENGTH 20
11
12
//defining a global variable
13 intmax_input_length = 15;
14
15 //declaring an user defined function which has been defined later
16 floataddNumbers(floata, floatb);
17
18 intmain(){
19 //declaring a local variable for main()
intlocalVariable = 50;
20
21 //Accessing a defined constant
22 printf("Max array length is %d\n", MAX_ARRAY_LENGTH);
23
24 //Accessing a global variable
25 printf("Max input length is %d\n", max_input_length);
26
27 //Accessing an user defined function, declared in gloabl declaration section
printf("Summation of 5.5 and 8.3 = %f\n",addNumbers(5.5,8.3));
28
29 return0;
30 }
31
32 //defining an user defined function which has been declared earlier.
33 floataddNumbers(floata, floatb){
34 return(a+b);
35 }
36
37
38
39

In this above sample C Program

 Line 1-6: These are comments, these lines will not be executed.
This is the Documentation Section.
 Line 9: This is the Link Section. Here we are linking our program
to a header file or library called stdio.h, this library provides
methods for sending output to screen or taking input from user
using standard output and input devices.
 Line 12: This is the Definition Section. Here we are defining a
constant.
 Line 15 & 18: This is Global Declaration Section. In line 15 we
are declaring a global variable and in line 18 we are declaring an
user defined function
 Line 20-34: This is the Main Function Section. Every C Program
must have this section. This section can have to sub-sections.
Declaration Part and Executable Part. However, this two part can
be mixed. In line 22 we are declaring local variable. Line 25, 28,
31 and 33 are executable statements.
 Line 37-39: This is the Sub-Program Section. Here we have
defined an user defined function that we have previously declared
in the Global Declaration Section.
Compiler & Interpreter

Each program is written in human language. But it will not be understood by the
computer. So for this, we use compilers and interpreters.

Compiler:

A compiler is a special program which takes processes written in a certain


particular programming language and transforms them into machine language.
When we compile our program, the compiler checks the whole program, whether
there are errors or not. If there is no error, the source code will be converted into
machine code. C language is compiler based program.

That means the program can be executed if there is no error.

Interpreter:

An interpreter is similar to the compiler which checks the whole program


simultaneously. But an interpreter performs check line by the line. If any error
occurs in the particular line, the execution will stop at this particular line. This
property makes the interpreters slower than a compiler.

The Structure of C Programs

Many programming languages such as Java, C++, Pascal, COBOL etc., have a
certain standard format which should be followed of the programmer. In the same
way, the C language also has the standard structure which resembles this.

Structure of C Program

<include Header Files>

[Global Declaration]
main() { <Local Declarations>; <Statements>; }

In the syntax, we mentioned include header files, which means we have to


include the header files

In the second line, you can see global declarations. It indicates that a function or
the variable can be declared here and accessed anywhere in the program.

The main function, this is necessary in each C program, because the execution
starts in the main function

Each C program must be started with the main function.

Following main function, we used the curly braces which are the parts to start
and of closing of the program

The statements are nothing but, the goal of the function

Understanding Header Files


We need to declare all functions in C language before you can use them. Because it
would be helpful to group related function declarations and manage them in a
single place. This is the function of header files.

Header files are vital in large projects because they give you an overview of source
code without having to look through every line of code.

The header files are the collection of pre-defined functions necessary for the
operation of a program if it is in a section written by the user of code, or as an
element of the standard libraries of C language by convention, the names of the
header files finish with dot H.
The suffix of dot H is used by the header files which are equipped with operating
system. We can also make our own header files if we need.

The header files define the following functions:

 Structures of certain files and subroutines


 Type the synonyms of definition (type def) for data types
 System parameters or implementation characteristics
 Constants and macros which are substituted during the phase of
pretreatment of language C.

Header Files

string.h - This file contains the functions which are related to string
manipulations

alloc.h - It has the functions which are related with memory allocation

time.h - This header file consists of the time related functions

conio.h - The conio.h has console (i.e. monitor) input output functions

ctype.h - It includes the functions which are related to conversion

Stdlib.h - It has standard library functions and also memory allocation

graphics.h - It has many built-in functions that support graphics

dos.h - It defines many functions that are related to date and delay which is
used to set interval

process.h - It contains system supporting functions.


Note : Several of the header files provided with the operating system end with .inc
(include file). Additional header files are provided with the operating system. Most
of these can be found in either the /usr/include directory or the /usr/include/sys
directory.

The Main Function


A C program is composed of one or more functions.

A function is a group of one or more statements which are joined in curly brackets
carry out a certain operation and return a simple value to the program in which
they reside; it also could be looked like subroutine.

All the C programs must have a main() function. The execution of the program
starts with the first statement of the main function.

The main function will call usually other functions coming from the same program,
and others of the libraries to carry out its work. The fact that the main function is
surrounded by curly brackets means that it is the definition of the main function.

Mainly, the function has two parts. One is the declaratory part. It handles the
declaration of the variables. And the next part is the achievable part which contains
the code which carries out the detail charge.

Like other functions, the main function lets pass the parameters. If we pass the
parameters by the main function, it is called as command line arguments

Remember! Without having the main function, we cannot execute any C program.
First ‘C’ Program
Program No. 1

Hello World Program

/* Printing a Text message */

#include<stdio.h>

#include<conio.h>

void main()

clrscr();

printf(“Hello World”);

getch();

/* Printing a Text message */

It is a comment line which denotes the purpose of the program

#include<stdio.h>

It is a preprocessor directive which is used to include stdio.h which contains


standard input and output functions

void main ()

‘main’ is a function, every programs execution starts from the main function
which should be enclosed with the
pair of curly braces. A void is a keyword which indicates the main function should
not return any value

printf(“HelloWorld”);

printf() is a function which is used to print the given information inside the
brackets

Essentials for C Programming Data Type Variables, Constants,


Keywords Operators Operator Precedence Format Strings and Escape
Sequences

Program No. 2

Variable Declaration Demo1

/* Program No. 2 Variable Declaration Demo 1 */

#include<conio.h>

#include<stdio.h>

void main()

int age; //variable declaration

clrscr();

age = 23;

printf("\n\t Value of variable age = %d", age);

getch();

}
Program No. 3

Variable Declaration Demo2

/* Program No. 3 Variable Declaration Demo 2*/

#include<stdio.h>

#include<conio.h>

void main()

float avg;

char ch;

clrscr();

avg = 3.78;

ch = 'A';

printf("\n\t Value of Variable avg = %.1f", avg); printf("\n\t Value of


Variable ch = %c", ch);

getch();

Program No. 4

Input data using Scanf() Function Demo 1

/* Program No. 4 Input age from keyboard */

#include<conio.h>

#include<stdio.h>
void main()

{
int age;
clrscr();

printf("\n\t Enter Age :");

scanf("%d", &age); // &: Address of

printf("\n\t Value of Age = %d", age);

getch()

Program No. 5

Input data using Scanf() Function Demo2


/* Program No.5 Input a character and one float value using scanf() function
*/
#include<conio.h>
#include<stdio.h>
void main()
{
char ch;
float avg;
clrscr();
printf("\n\t Enter any Character :");
scanf("%c", &ch);
printf("\n\t Enter Average Marks :");
scanf("%f", &avg);
printf("\n\t ch = %c", ch);
printf("\n\t Average value = %.2f", avg);
getch(); }
Data Type
All the programming languages have data types which can be changed language
with the language. The data types are essential for any computer programming
language. Without them, it becomes very difficult to maintain information in a
computer program.

The data is a group of information which is not classified by category. It means


that information will not be arranged in a suitable way. This is called raw data.
Data can be numerical data or a character or date and so forth. These are called
data types.

The C programming language provides two types of data


1. Primary Data Types / Fundamental types

I. Integer Data Type


 The Integer Data Type allows only the values of integer without
decimals but not characters.
In this case, when you assign a character with a variable of integer,
it will be regarded as value of ASCII
 C has 3 classes of integer storage namely short int, int and long int
 All of these data types have signed and unsigned forms.
 A short int requires half the space than normal integer values.
 Unsigned numbers are always positive and consume all the bits for
the magnitude of the number. Therefore, the range of an unsigned
integer will be from 0 to 65535.
 The long integers are used to declare a longer range of values and
it occupies 4 bytes of storage space.
Type Storage Value range Format
size Specifier
int / signed int 2 or 4 bytes -32,768 to 32,767 or - %d or %i
2,147,483,648 to
2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to %u
4,294,967,295
Short 2 bytes -128 to 127 or %hi
short int -32,768 to 32,767
signed short
signed short int
unsigned short 2 bytes 0 to 65,535 %hu
long 4 bytes -2,147,483,648 to %li
long int 2,147,483,647
signed long
signed long int

Program No. 6

Print the size, Min value, Max value for Integer Data types

/* Program No. 6 Print the size, min , max value of int data type */

#include<conio.h>

#include<stdio.h>

#include<limits.h>

void main()

{ int a, b, c;

clrscr();
printf("\n\t size required for int data type = %d bytes", sizeof(int));
printf("\n\n\t Min value for int = %d", INT_MIN);
printf("\n\t MAx value for int = %d", INT_MAX);
getch();

2. Floating Point Data Types

The float allows numbers with the floating decimal points

The float data type is used to store fractional numbers (real numbers) with 6
digits of precision

When the accuracy of the floating point number is insufficient, we can use the
double to define the number

The double is same as float but with longer precision and takes double space (8
bytes) than float

To extend the precision further we can use long double which occupies 10 bytes
of memory space.

Type Storage size Value range Precision Format


Specifier
float 4 byte 1.2E-38 to 6 decimal %f
3.4E+38 places
double 8 byte 2.3E-308 to 15 decimal %lf
1.7E+308 places
long double 10 byte 3.4E-4932 to 19 decimal %Lf
1.1E+4932 places

Program No. 7

Print the size, Min value, Max value for float Data types
/* Program No. 7 print size required for float, min value, max value of
float */

#include<conio.h>
#include<stdio.h>
#include<float.h>
void main()
{
float avg = 34.654;
clrscr();
printf("\n\t Size required for float data type = %d bytes", sizeof(float));
printf("\n\n\t Min value for float = %E", FLT_MIN);
printf("\n\t Max value for float = %E", FLT_MAX);
printf("\n\t No of precision for float = %d", FLT_DIG);
printf("\n\n\t value of float f = %f", avg);
getch();
}

3. Character Data Type

 The char type allows a character at the same time. A group of characters are
called string
 Each character is stored in a separate place
 Character type variable can hold a single character and are declared by using
the keyword char
 The Char Data type have Signed and unsigned forms; both occupy 1 byte
each, but having different ranges
Type Storage size Value range Format
Specifier
char 1 byte -128 to 127 or %c
0 to 255
unsigned char 1 byte 0 to 255 %c
signed char 1 byte -128 to 127 %c
Program No. 8

Print the size, Min value, Max value for char Data types

/* Program No. 8 print the size of char data type, min value and max value
of char */

#include<conio.h>
#include<stdio.h>
#include<limits.h>
void main()
{
clrscr();
printf("\n\t Size required for char data type = %d bytes", sizeof(char));
printf("\n\n\t Min value for char = %d", CHAR_MIN);
printf("\n\t Max value of char = %d", CHAR_MAX);
getch(); }
Variables
Variable is a data name that may be used to store a data value, in other words variable is a
named location in memory that is used to hold a value that can be modified by the
program.
A variable name can be chosen by the programmer in a meaningful way so as to reflect
its function or nature in the program. For ex. Average, sum, total, marks_sub1.
Variable names may consist of letters, digits, and the underscore character.
Generally, the variables are used to store the values. A variable is a container for
information which you want to store.

Its value can change during the script. It should be unique. Variables must be
declared before used.

Rules for Declaring Variables

The variable names are case sensitive. That means, small `a’ differs from capital
‘A’

The name of a variable is a combination of the alphabets, digits, or underscores


The first character of the variable name must be an alphabet or an underscore

No commas or white spaces are allowed in a variable name

No special symbol other than an underscore can be used in a variable name

Syntax to declaring variables

Datatype var_name [Size];

In the syntax, Data Type denotes what type of information you are going to store
in the variable. And, var_name refers to the name of the variable. Size is an
optional, which can be used as arrays.

Example : char name [10]; int x=100;


In this example, variable x is declared and initialized simultaneously. If you wish
to declare many variables with same type.

int regno, marks;

Constants
Constants are similar to the variables. But the values of the variable can be
changed during the execution of the program while, the constant cannot be
changed

In C language, constants are divided into two categories, numbers and characters

The number constant has two parts, they are, integer, real numbers

The character constant is also having two parts, they are single, string. When you
will use these constants in your C program, you should know the rules

Integer Constants

An integer constant must have at least a digit

It should not have a decimal point

It can be positive or negative

No comma or blanks are allowed within an integer constant

Constants
|
----------------------------------------------------------------------------------------
| |
Number Character
| |
Integer Float Single String
Real Constants

The real constants are often called the constants of floating point

The real constants could be written in the forms, fractional and the exponential
form

A real constant must have at least one digit

It could be positive or negative. By default, the sign is positive

Character constants

A character constant is a single letter, a single digit or a single special symbol


included in single inverted commas

The two inverted commas should move towards the left. For your better
understanding, look at the example

The maximum length of character constant can be 1 character

Keywords
The keywords are the reserved words whose significance is already defined by the
compiler of C.

We cannot use the key words as our own variable names. If we do so, it means that
we are trying to assign a new meaning to the keyword which is not allowed by the
compiler.

Keywords are the words their meaning has already been explained to the C
compiler.
The keywords cannot be used as variable names.

In C programming language, there are 32 keywords available

The keywords supported by C language are

auto Else long switch


break Enum register typedef
case extern return union
char float short unsigned
const for signed void
continue goto sizeof volatile
default if static while
Do int struct double

The key words can be used while declaring conditional variables or statements or
making a loop of the statements and so on

Comments
In C language, comments are used to explain the goal of the program. If you wish
to add a line of comment, you should start with a combination of a forward slash
and an asterisk and ends with the asterisk and a forward slash

//Single line Comment

The forward slash asterisk (i.e. /*) is called the opening of comment, and asterisk
forward (i.e. */) is the mark of comment of closing
/* Multiple

Line

Comments */

The compiler of C is unaware of all between the mark of comment of opening and
the mark of comment of closing. It is in good practices of programming to put a
comment before writing a program

And also you can put a comment inside the code. The comment line should not be
enclosed with the string literal that is, double quotes. If we do so, that line will be
treated as a normal line not a comment line.

Operators
With most programming languages, the operators play the important part. If we
want to perform a simple calculation, we need the operators. Without using
operators, we cannot do anything in the program.

The operators are symbols which take one or more operands or expressions and
carry out arithmetic or logical calculations.

The operands are variables or expressions which are used in the operators to
evaluate the expression. The combination of the operands and the operators form
an expression.

10 + 20 = 30 In above example, 10 and 20 are the operands which are combined


by the plus (+) operator. The operands are evaluated by the arithmetic plus
operator and produce the value of 30 as an output. Similarly, there are many
operators available in C language.
Simple assignment

This is the most commonly used operator. It assigns the value on its right to the
operand on its left. Here are some examples:

Assigning values:

int x = 10;

float y = 3.5;

int a = x+y-5;

int a = b;

Arithmetic Operators

The operators of arithmetic carry out the addition, subtraction, multiplication,


division and the modulus division

The following table shows all the arithmetic operators supported by the C
language. Assume variable A holds 10 and variable B holds 20, then:

Operator Description Example


+ Adds two operands. A + B = 30
- Subtracts second operand
from the first. A - B = -10
* Multiplies both operands. A * B = 200
/ Divides numerator by
Denominator. B/A=2
% Modulus Operator and
remainder of after an
integer division. B%A=0
++ Increment operator
increases the integer value
by one. A++ = 11
-- Decrement operator decreases
the integer value by one. A-- = 9

Relational operators

The relational operators are used to compare two operands or two expressions and
result is a true/false. The following table lists all relational operators in C.

| The following table shows all the relational operators supported by C.


Assume variable A holds 10 and variable B holds 20, then:
Operator Description Example
== Checks if the values of two operands are equal
or not. If yes, then the condition becomes
true. (A == B) is nottrue.
!= Checks if the values of two operands are equal
or not. If the values are not equal, then the
condition becomes true. (A != B) is true.
> Checks if the value of left operand is greater
than the value of right operand. If yes, then
the condition becomes true. (A > B) is not true.
< Checks if the value of left operand is less than
the value of right operand. If yes, then the
condition becomes true. (A < B) is true.
>= Checks if the value of left operand is greater
than or equal to the value of right operand. If
yes, then the condition becomes true. (A >= B) is not
true.

<= Checks if the value of left operand is less than


or equal to the value of right operand. If yes,
then the condition becomes true. (A <= B) is true

Logical Operators
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then:
Operator Description Example
&& Called Logical AND operator.
If both the operands are
non-zero, then the condition
becomes true. (A && B) is false.

|| Called Logical OR Operator.


If any of the twooperands is
non-zero, then the condition
becomes true. (A || B) is true.

! Called Logical NOT Operator.


It is used toreverse the logical
state of its operand. If a condition
is true, then Logical NOT operator
will make it false. !(A && B) is true? :
ternary operator in form of: A ? B : C
The conditional operators (&& and ||) are used to perform conditional-AND and
conditional-OR operations on two expressions and result in a true/false value. They
have “short-circuiting” behavior:

For the && operator: if the left expression is evaluated to false, then the right
expression is not evaluated. Final result is false

For the || operator: if the left expression is evaluated to true, then the right
expression is not evaluated. Final result is true

Escape Sequence Characters

A word consists of a backslash (\) followed of a letter or by a combination of the


digits are called the escape sequences.

They are similar to format strings. Both are used to format the output characters.
But the main difference between these two is, format strings can be used input and
output functions (i.e. print f, scan f) while the escape sequence characters are only
for the output

The escape sequence characters are also called the non-printable characters. It
produces only the results without printing slash (\) symbol

If we need any special character, we can use the escape sequence character. All the
escape sequence characters are started with the character of backslash (\)

Escape Sequences Character


Escape Sequences Character
\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\' Single quotation
mark
\" Double quotation
mark
\? Question mark
\0 Null character

Bitwise Operators
Bitwise operator works on bits and performs bit-by-bit operation. The truth tables
for &, |, and ^ is as follows −

p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1
Assume A = 60 and B = 13 in binary format, they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The following table lists the bitwise operators supported by C. Assume variable
'A' holds 60 and variable 'B' holds 13, then −
Show Examples

Operator Description Example

& Binary AND Operator copies a bit to the result if it (A & B) =


exists in both operands. 12, i.e.,
0000 1100

| Binary OR Operator copies a bit if it exists in either (A | B) =


operand. 61, i.e.,
0011 1101

^ Binary XOR Operator copies the bit if it is set in (A ^ B) =


one operand but not both. 49, i.e.,
0011 0001

~ (~A ) = -61,
Binary Ones Complement Operator is unary and
i.e,. 1100
has the effect of 'flipping' bits.
0011 in 2's
complement
form.

<< Binary Left Shift Operator. The left operands value A << 2 =
is moved left by the number of bits specified by the 240 i.e.,
right operand. 1111 0000

>> Binary Right Shift Operator. The left operands A >> 2 = 15


value is moved right by the number of bits i.e., 0000
specified by the right operand. 1111

Sizeof & ternary


Besides the operators discussed above, there are a few other important operators
including sizeof and ? : supported by the C Language.
Show Examples

Operator Description Example

sizeof() sizeof(a), where a is integer,


Returns the size of a variable.
will return 4.

& &a; returns the actual address


Returns the address of a variable.
of the variable.

* Pointer to a variable. *a;

?: If Condition is true ? then


Conditional Expression.
value X : otherwise value Y
Ternary Operator in C

If any operator is used on three operands or variable is known as Ternary


Operator. It can be represented with ? : . It is also called as conditional
operator

Advantage of Ternary Operator

Using ?: reduce the number of line codes and improve the performance of
application.
Syntax

expression-1 ? expression-2 : expression-3

In the above symbol expression-1 is condition and expression-2 and expression-


3 will be either value or variable or statement or any mathematical expression. If
condition will be true expression-2 will be execute otherwise expression-3 will
be executed.

Syntax

a<b ? printf("a is less") : printf("a is greater");

Find largest number among 3 numbers using ternary operator


Example

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

void main()
{
int a, b, c, large;
clrscr();
printf("Enter any three number: ");
scanf("%d%d%d",&a,&b,&c);
large = a>b ? (a>c?a:c) : (b>c?b:c);
printf("Largest Number is: %d",large);
getch();
}

Output

Enter any three number: 5 7 2


Largest number is 7

Module 4: Input and Output Functions

Standard I/O Functions

Character I/O Functions

String I/O Functions

Standard I/O Functions


A computer cannot make anything without giving any request. The user must give
the request, the answer will be sent by computer.

The functions printf() and scanf() are used to perform input and output
operations

The printf() function prints the information provided on the screen (i.e.
monitor)
The scanf() function receives the data from the user

By using printf() and scanf() functions, we can print and input with any format
with the assistance of the format strings. Since the format strings decide only
which type of data to enter or shown.

A limitation of using the scanf() function does not allow empty spaces between
the strings. For example, when we enter a name Mother Theresa, a scanf() function
allows only the string of “Mother”. The remainder of the word will not be stored in
the respective variable. To avoid this kind of difficulty, we have to use a special
function called gets() which will be discussed in the upcoming lessons.

Syntax:

printf(“<Format_String>”, <List_of_Variables>);

scanf(“<Format_String>”, <& List_of_Variables>);

In this syntax, both functions are taken as two arguments, format string, and list of
variables.

“<Format_String>”: The format strings are used to determine the input or


output data type.

<List_of_Variables>: The list of variables indicates variables which have


data.

The printf() is a name of the function which allows printing the output.

The scanf() uses an ampersand (&) symbol is placed in front of the list of
variables, which indicates the address of value. That means, when we give an
input, the value will be stored in the address because each variable has a separate
memory location.
Program No. 9

Input an integer, float value and display

/* Program No. 9 Input a number, and float value and display the same */

#include<conio.h>
#include<stdio.h>
void main()
{
int i;
float f;
clrscr();
printf("\n\t Enter any Integer No. :");
scanf("%d", &i);
printf("\n\t Enter a floating point value :");
scanf("%f", &f);
printf("\n\t Value of i = %d", i);
printf("\n\t Value of f = %.2f", f);
getch();
}

Operators Precedence in C
Operator precedence determines the grouping of terms in an expression and
decides how an expression is evaluated. Certain operators have higher precedence
than others; for example, the multiplication operator has a higher precedence than
the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a
higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those
with the lowest appear at the bottom. Within an expression, higher precedence
operators will be evaluated first.

The following table lists the precedence and associativity of C operators. Operators
are listed top to bottom, in descending precedence.

Precedence Operator Description Associativity

++ -- Suffix/postfix increment and decrement Left-to-right

() Function call

[] Array subscripting
1

. Structure and union member access

Structure and union member access through


->
pointer
(type){list} Compound literal(C99)

++ -- Prefix increment and decrement Right-to-left

+- Unary plus and minus

!~ Logical NOT and bitwise NOT

(type) Type cast


2
* Indirection (dereference)

& Address-of

sizeof Size-of[note 1]

_Alignof Alignment requirement(C11)

3 */% Multiplication, division, and remainder Left-to-right

4 +- Addition and subtraction

5 << >> Bitwise left shift and right shift

For relational operators < and ≤


< <=
respectively
6

> >= For relational operators > and ≥


respectively

7 == != For relational = and ≠ respectively

8 & Bitwise AND

9 ^ Bitwise XOR (exclusive or)

10 | Bitwise OR (inclusive or)

11 && Logical AND

12 || Logical OR

13[note 2] ?: Ternary conditional[note 3] Right-to-Left

= Simple assignment

+= -= Assignment by sum and difference

Assignment by product, quotient, and


*= /= %=
remainder
14

Assignment by bitwise left shift and right


<<= >>=
shift

Assignment by bitwise AND, XOR, and


&= ^= |=
OR
15 , Comma Left-to-right

1. ↑ The operand of sizeof can't be a type cast: the expression sizeof (int) * p is
unambiguously interpreted as (sizeof(int)) * p, but not sizeof((int)*p).
2. ↑ Fictional precedence level, see Notes below
3. ↑ The expression in the middle of the conditional operator (between ? and :)
is parsed as if parenthesized: its precedence relative to ?: is ignored.
When parsing an expression, an operator which is listed on some row will be
bound tighter (as if by parentheses) to its arguments than any operator that is listed
on a row further below it. For example, the expression *p++ is parsed as *(p++),
and not as (*p)++.
Operators that are in the same cell (there may be several rows of operators listed in
a cell) are evaluated with the same precedence, in the given direction. For example,
the expression a=b=c is parsed as a=(b=c), and not as (a=b)=c because of right-to-
left associativity.

Type Conversion in C
A type cast is basically a conversion from one type to another. There are two types
of type conversion:

1. Implicit Type Conversion


Also known as ‘automatic type conversion’.
 Done by the compiler on its own, without any external trigger from the
user.
 Generally takes place when in an expression more than one data type is
present. In such condition type conversion (type promotion) takes place
to avoid lose of data.
 All the data types of the variables are upgraded to the data type of the
variable with largest data type.
bool -> char -> short int -> int -> unsigned int -> long ->
unsigned -> long long -> float -> double -> long double
 It is possible for implicit conversions to lose information, signs can be
lost (when signed is implicitly converted to unsigned), and overflow can
occur (when long long is implicitly converted to float).

Example of Type Implicit Conversion:


// An example of implicit conversion

#include<stdio.h>
int main()
{
int x = 10; // integer x
char y = 'a'; // character c

// y implicitly converted to int. ASCII


// value of 'a' is 97
x = x + y;

// x is implicitly converted to float


float z = x + 1.0;
printf("x = %d, z = %f", x, z);
return 0;
}
Run on IDE

Output:
x = 107, z = 108.000000

2. Explicit Type Conversion–


This process is also called type casting and it is user defined. Here the user
can type cast the result to make it of a particular data type.
The syntax in C:

(type) expression

Type indicated the data type to which the final result is converted.
// C program to demonstrate explicit type casting

#include<stdio.h>

int main()

double x = 1.2;

// Explicit conversion from double to int

int sum = (int)x + 1;

printf("sum = %d", sum);

return 0;

Run on IDE

Output:

sum = 2

Advantages of Type Conversion


 This is done to take advantage of certain features of type hierarchies or
type representations.
 It helps us to compute expressions containing variables of different data
types.

Input Marks of 3 Subjects, Calculate Total Marks, Average marks


and display the same
/* Program no. 14:
Input marks of 3 subjects, calculate total marks, average marks and display
it
*/
#include<conio.h>
#include<stdio.h>
void main()
{
int sub1, sub2, sub3, total;
float avg;
clrscr();
printf("\n\t Enter Marks for sub1 :");
scanf("%d", &sub1);
printf("\n\t Enter Marks for sub2 :");
scanf("%d", &sub2);
printf("\n\t Enter Marks for sub3 :");
scanf("%d", &sub3);
total = sub1 + sub2 + sub3;
avg = (float)total/3;
printf("\n\t Total Marks = %d", total);
printf("\n\t Average Marks = %.2f", avg);
getch();
}

Input Radius of a circle and calculate area and circumference


/*
Program No. 15
Input Radius and calculate Area, Circumference of a Circle
*/
#include<conio.h>
#include<stdio.h>
void main()
{
float rad, area, cir;
clrscr();
printf("\n\t Enter Radius of Circle :");
scanf("%f", &rad);
area = 3.14 * rad * rad;
cir = 2 * 3.14 * rad;
printf("\n\t Area of Circle = %.2f", area);
printf("\n\t Circumference of Circle = %.2f", cir);
getch();
}

Program No. 16

Input Two Numbers and interchange their values (Swapping using third variable) /*

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

void main() { int a, b, temp; clrscr();

printf("\n\t Enter a : "); scanf("%d", &a);

printf("\n\t Enter b : "); scanf("%d", &b);

printf("\n\n\t Before Swap : a = %d \t b = %d", a, b);

temp = a; a = b; b = temp;

printf("\n\n\n\t After Swap : a = %d \t b = %d", a, b);

getch(); }
Program No. 17

WAP to input 3 digit integer number and display their addition /*

Program No. 17: Input a 3 Digit Integer Number and display sum of all the 3
digits */

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

void main() { int no, d1, d2, d3, sum; clrscr();

printf("\n\t Enter a 3 digit integer number :"); scanf("%d", &no);

d3 = no%10; no = no/10;

d2 = no%10; no = no/10;

d1 = no%10;

sum = d1 + d2 + d3;

printf("\n\t Sum of all the digits = %d", sum);

getch();

Program No. 18

WAP input three digit integer no and display its reverse /* Program No. 18:
Input a 3 digit integer number and display its Reverse */

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

void main() { int no, rem, rev=0; clrscr();

printf("\n\t Enter any 3 digit integer number :"); scanf("%d", &no);

rem = no%10; rev = (rev*10)+rem; no = no/10;

rem = no%10; rev = (rev*10)+rem; no = no/10;

rem = no%10; rev = (rev*10)+rem;


printf("\n\t Reverse = %d", rev);

getch();

Program No. 19

WAP to input distance between two cities in Kilometer and convert it into meter,
centimeter, inch and in float. [ 1 Km = 1000 m, 1 Meter = 100 Cm, 1 inch = 2.54 cm,
1 ft = 12 Inch] /* Program No. 19: Input Distance between two cities in KM
convert and display it into Meters, cm, inches, feet */

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

void main() { float km, m, cm, in, feet; clrscr();

printf("\n\t Enter distance between two cities in KM :"); scanf("%f", &km);

m = km * 1000; printf("\n\t Distance in Meters = %.2f", m);

cm = m * 100; printf("\n\t Distance in Centimeters = %.2f", cm);

in = cm/2.54; printf("\n\t Distance in Inches = %.2f", in);

feet = in / 12; printf("\n\t Distance in Feet = %.2f", feet);

getch();

Program No. 23

Input a 4 digit no, write a program that displays the number as follows

First Line : All digits

Second Line : All except first digit :

Third Line … … All except first two digits

Last Line : The last digit


Example: The number 5678 will be displayed as 5 6 7 8 6 7 8 7 8 8

Program No. 24

A certain town has population 80000, In which 35% are men and 55% are women.
The literacy of men is 45% and illiteracy of women is 15%, Then calculate the
literacy and illiteracy of the town.

Program No. 25

WAP to input Name and Basic salary of an employee in INR and calculate gross
salary if DA = 20% and HRA = 15% of Salary

Program No. 26

WAP to input Name and Basic salary of an employee in INR and calculate gross
salary if DA = 20% and HRA = 15% of Salary

Session 6: Decision and Control Flow Statements IF Statements, Nested IF


Statements The switch case and go to Statements The for Loop The while
Loop The do...while Loop Working with break and continue Keywords

Branching Statements
Branching decides what actions to take. Branching is so called because the program
chooses to follow one branch or another.

The C language programs follows a sequential form of execution of statements. Many times it is
required to alter the flow of sequence of instructions. C language provides statements that can
alter the flow of a sequence of instructions.

These statements are called as control statements. To jump from one part of the
program to another, these statements help. The control transfer may be unconditional
or conditional. Branching Statement are of following categories:

1. If Statement

2. The If Else Statement

4. Compound Relational tests

5. Nested if Statement

6. Switch Statement

Looping Statements
Loops provide a way to repeat commands and control how many times they are
repeated. C provides a number of looping ways.

1. While

2. Do-While

3. For

Jumping Statements

These statements transfer control to another part of the program. When we want to
break any loop condition or to continue any loop with skipping any values then we
use these statements. There are three types of jumps statements.

1. Goto

2. Break

3. Continue
Branching Statements
IF Statement
This is the simplest form of the branching statements.

It takes an expression in parenthesis and a statement or block of statements. if the


expression is true then the statement or block of statements gets executed otherwise
these statements are skipped.

Syntax: The syntax of an if...else statement in C programming language is:

if(Condition/Expression)

/* statement(s) will execute if the Condition/ Expression is true */


}

If the Condition/Expression evaluates to true, then the block of code inside the if
statement will be executed. If Condition/Expression evaluates to false, then the first
set of code after the end of the if statement (after the closing curly brace) will be
executed.

Note: C programming language assumes any non-zero and non-null values as true
and if it is either zero or null, then it is assumed as false value.

Program No. 27

Input two numbers and display the max /* Program No. 27 Input two numbers
and display the max */

void main() {

int a, b;

clrscr();

printf("\n\t Enter a and b :");

scanf("%d %d", &a, &b);

if(a>b)

{ printf("\n\t a = %d is max", a);

if(b>a)

printf("\n\t b = %d is max", b);

if(a==b)

{ printf("\n\t a and b both are same");

getch(); }
Program No. 28

WAP to input any number from the user and display whether the number is positive
or negative

/* Program No 28 WAP to input a number and display whether it is positive,


negative or zero */

void main()

{ int no; clrscr();

printf("\n\t Enter any number :"); scanf("%d", &no);

if(no>0) printf("\n\t %d is a positive no", no);

if(no==0) printf("\n\t %d is Zero", no);

if(no<0) printf("\n\t %d is a Negative No.", no);

getch();

Decision making using if-else :


When we have single condition is to be check then we can use if … else.

Syntax

if(condition)
{
........
statements
........
}
else
{
........
statements
........
}

In the above syntax whenever condition is true all the if block statement are executed
remaining statement of the program by neglecting else block statement. If the
condition is false else block statement remaining statement of the program are
executed by neglecting if block statements

e.g. find the number is even or odd


main( )

int no;

printf ( “enter any number :”);

scanf (“%d”,&no);

if (no%2 == 0)

printf ( “ number is even”);

else

printf ( “ number is odd”);

NOTE:- It is optional to give curly brackets after if but if you don’t give curly
brackets, only first statement after if is part of if.

If-Else if – Else Statement


An if statement can be followed by an optional else if...else statement, which is very
useful to test various conditions using single if...else if statement.
When using if , else if , else statements there are few points to keep in mind:

An if can have zero or one else's and it must come after any else if's.
An if can have zero to many else if's and they must come before the else.
Once an else if succeeds, none of the remaining else if's or else's will be tested.

Syntax:
The syntax of an if...else if...else statement in C programming language is:
if(boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3)
{
/* Executes when the boolean expression 3 is true */
}
else
{
/* executes when the none of the above condition is true */

Program No. 33

Input a number and display whether it is positive negative or zero

/* program No. 33 Input a number and display whether it is positive,


negative or zero */

#include<conio.h>

#include<stdio.h>

void main()

{ int no;

clrscr();

printf("\n\t Enter any no. :");

scanf("%d", &no);

if(no>0)

{ printf("\n\t %d is a Positive number", no);

}
else if(no==0)

{ printf("\n\t %d is a Zero", no);

else

{ printf("\n\t %d is a Negative Number", no);

} getch();

Program No. 34

Input Average Marks and display appropriate result

Avg >=75 Distinction


60 to 75 First Class
45 to 60 Second Class
35 to 45 Pass
Below 35 Fail

/* Program No. 34 Input Average Marks and Display appropriate Result */

#include<conio.h>

#include<stdio.h>

void main()

float avg;
clrscr();

printf("\n\t Enter Average Marks :");

scanf("%f", &avg); //68.34

if(avg>=75)

printf("\n\t Distinction");

else if(avg>=60)

printf("\n\t First Class");

else if(avg>=45)

printf("\n\t Second Class");

else if(avg>=35)

printf("\n\t Pass");

else

printf("\n\t Fail");

}
getch();

Program No. 35

WAP to input any character from the user and display whether it is vowel or
consonant. /* Program No. 35 Input any Alphabet and display whether it is
vowel or consonant */

#include<stdio.h>

#include<conio.h>

void main()

char alpha;

clrscr();

printf("\n\t Enter any Alphabet :");

scanf("%c", &alpha);

if(alpha == 'a')

printf("\n\t %c is a Vowel", alpha);

else if(alpha == 'e')

printf("\n\t %c is a Vowel", alpha);

else if(alpha == 'i')

printf("\n\t %c is a Vowel", alpha);

else if(alpha== 'o')

printf("\n\t %c is a Vowel", alpha);

else if(alpha == 'u')


printf("\n\t %c is a Vowel", alpha);

else

printf("\n\t %c is a Consonant", alpha);

getch();

Nested If-Else
It is always legal in C programming to nest if-else statements, which means you can use one if or
else if statement inside another if or else if statement(s).

Syntax: The syntax for a nested if statement is as follows:


if( boolean_expression 1)

{ /* Executes when the boolean expression 1 is true */ if(boolean_expression


2)

{ /* Executes when the boolean expression 2 is true */

You can nest else if...else in the similar way as you have nested if statement.

Program No. 36

Input three numbers and display the maximum number /* Program No. 36
Input three numbers and display the maximum number */

#include<conio.h>

#include<stdio.h>

void main()

{
int a, b, c;

clrscr();

printf("\n\t Enter three numbers :");

scanf("%d %d %d", &a, &b, &c); // 23 122 400

if(a>b)

if(a>c)

printf("\n\t a = %d is max", a);

else

printf("\n\t c = %d is max", c);

else {

if(b>c)

printf("\n\t b = %d is max", b);

else

printf("\n\t c = %d is max", c);


}

getch();

Program No. 37

WAP to input gender and age of an employee and check whether the employee is
eligible for the insurance or not using the following conditions.

a. If employee is male and age>=30

b. If employee is female and age>=25

#include<conio.h>

#include<stdio.h>

void main()

char gender; // m/f

int age;

clrscr();

printf("\n\t Enter Gender [m/f] :");

gender = getche();

printf("\n\t Enter Age :");

scanf("%d", &age);

if(gender == 'm')

if(age>=35)
{

printf("\n\t Employee is Elibible for Insurance");

else

printf("\n\t Employee is NOT Eligible for Insurance because


of Age Criteria");

else if(gender == 'f')

if(age>=25)

printf("\n\t Employee is Elibible for Insurance");

else

printf("\n\t Employee is NOT Elibible for Insurance


bcaz of Age Criteria");

else

{
printf("\n\t Wrong Input");

getch();

Program No. 38

Write a program to accept three numbers from user and print them in
ascending and descending order

/* Program No. 38 Input three numbers and display in order */

#include<conio.h>

#include<stdio.h>

void main()

int a, b, c;

clrscr();

printf("\n\t Enter three Numbers :");

scanf("%d %d %d", &a, &b, &c); // 2 6 1

if(a>b)

if(a>c && b>c)

printf("\n\t Descending Order %d %d %d", a, b, c);

printf("\n\t Ascending Order : %d %d %d", c, b, a);

}
else

printf("\n\t Descending Order %d %d %d", a, c, b);

printf("\n\t Ascending Order : %d %d %d", b, c, a);

else

if(b>c && a>c)

printf("\n\t Decending Order %d %d %d", b, a, c);

printf("\n\t Ascending Order : %d %d %d", c, a, b);

else

printf("\n\t Decending Order %d %d %d", b, c, a);

printf("\n\t Ascending Order : %d %d %d", a, c, b);

getch();

}
Switch Statement
The Switch Case Statement is used to make a decision from the number of choices

Syntax:
switch(expression)

case expr1:

statements;

break;

case expr2:

statements;

break;

case expr3:

statements;

break;

default:

statements;

The expression following the keyword switch is any C expression that evaluates
an integer or a char value.

First, the expression following the keyword switch is evaluated. The value is then
matched, one by one, against the constant values that follow the case statements.
When a match is found, the program executes the statements following that case, and
all subsequent case and default statements as well.
If no match is found with any of the case statements, only the statements following
the default are executed. A few examples will show how this control structure works.

We can check the value of any expression in a switch. Thus the following switch
statements are legal.

switch ( i + j * k ) switch ( 23 + 45 % 4 * k ) switch ( a < 4 && b > 7 )

Expressions can also be used in cases provided they are constant expressions. Thus
case 3 + 7 is correct, however, case a + b is incorrect.

The break statement when used in a switch takes the control outside the switch.
However, use of continue will not take the control to the beginning of switch as one
is likely to believe.

In principle, a switch may occur within another, but in practice it is rarely done. Such
statements would be called nested switch statements.

The switch statement is very useful while writing menu driven programs.
Program No. 44

Switch Demo /* Program No. 44 Switch Case Demo */

#include<conio.h>
#include<stdio.h>
void main()
{
int no;
clrscr();
printf("\n\t Enter any number between 0 to 9 :" );
scanf("%d", &no);
switch(no)
{
case 0:
printf("\n\t Zero");
break;
case 1:
printf("\n\t One");
break;
case 2:
printf("\n\t Two");
break;
case 3:
printf("\n\t Three");
break;
case 4:
printf("\n\t Four");
break;
case 5:
printf("\n\t Five");
break;
case 6:
printf("\n\t Six");
break;
case 7:
printf("\n\t Seven");
break;
case 8:
printf("\n\t Eight");
break;
case 9:
printf("\n\t Nine");
break;
default:
printf("\n\t Wrong Input");
}
getch();
}

Looping Statements
There may be a situation, when you need to execute a block of code several number
of times. In general, statements are executed sequentially: The first statement in a
function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple
times and following is the general form of a loop statement in most of the
programming languages
C programming language provides the following types of loop to handle looping
requirements. Click the following links to check their detail.

Loop type Description


while loop Repeats a statement or group of statements while a
given condition is true. It tests the condition before
executing the loop body.
for loop Execute a sequence of statements multiple times
and abbreviates the code that manages the loop
variable.
do...while loop Like a while statement, except that it tests the
condition at the end of the loop body
nested loops You can use one or more loop inside any another
while, for or do..while loop.

While Loop
A while loop statement in C programming language repeatedly executes a target
statement as long as a given condition is true.
Syntax:
The syntax of a while loop in C programming language is:

while(condition)

{ statement(s);

}
Here, statement(s) may be a single statement or a block of statements. The condition
may be any expression, and true is any nonzero value. The loop iterates while the
condition is true.
When the condition becomes false, program control passes to the line immediately
following the loop.

Flow Diagram:
Here, key point of the while loop is that the loop might not ever run. When the
condition is tested and the result is false, the loop body will be skipped and the
first statement after the while loop will be executed

1. The statements within the while loop would keep on getting executed till the
condition being tested remains true. When the condition becomes false the block is
terminated
2. In place of the condition there can be any other valid expression. So long as the
expression evaluates to a non-zero value the statements within the loop would get
executed
3. As a rule the while loop must test a condition that will eventually become false,
otherwise the loop would execute forever, indefinitely
4. Instead of incrementing the loop counter, we can even decrement it
5. It is not necessary that a loop counter must only be an int, it can even be a float or
a char
Print 1 to 10 using while loop

/* Print 1 to 10 using while loop */


#include<conio.h>
#include<stdio.h>
void main()
{
int i;
clrscr();
i = 1; //initiaze counter variable
while(i<=10) //condition
{
printf("\n\t %d", i);
i++; //update the counter
}
getch();
}

Q. Print 10 to 1 using while loop


Input any number and display sum of all digits
#include<stdio.h>
#include<conio.h>
void main()
{
int n,sum=0,r;
clrscr();
printf("Enter a number upto 5 digits\n");
scanf("%d",&n);
while(n!=0)
{
r=n%10;
sum=sum+r;
n=n/10;
}
printf("Sum of all digits is %d\n",sum);
getch(); }

Input any number and display Reverse of it


#include<stdio.h>
#include<conio.h>
void main()
{
int n,rev=0;
clrscr();
printf("Enter a number to reverse\n");
scanf("%d",&n);
while (n != 0)
{
rev=rev*10;
rev=rev+n%10; n=n/10;
}
printf("Reverse of entered number is = %d\n", rev);
getch(); }
Input a Number and display its Factorial Value In mathematics, the factorial of a non-
negative integer n, denoted by n!, is the product of all positive integers less than or
equal to n.

#include<stdio.h> #include<conio.h> void main() { long int fact =1; int i=1,n;
clrscr(); printf("Enter an integer number : "); scanf("%d",&n); while(i<=n) {
fact*=i; i++; } printf("Number is = %d \n",n); printf("factorial value is =
%ld \n",fact); getch(); }

Program No. 66

Calculate power of given number #include <stdio.h>

int main() { int base, exp; long long int value=1; printf("Enter base number and
exponent respectively: "); scanf("%d%d", &base, &exp); while (exp!=0) {
value*=base; /* value = value*base; */

--exp; } printf("Answer = %d", value); return 0; }

Write a Program to check whether the entered number is Armstrong or not A positive
integer is called Armstrong number if sum of cubes of individual digit is equal to that
number itself

For Example: 153 = 1*1*1 + 5*5*5 + 3*3*3 // 153 is an Armstrong number 12 is not
equal to 1*1*1 + 2*2*2 so it is not an Armstrong number

#include <stdio.h> int main() { int n, n1, rem, num=0; printf("Enter a positive
integer: "); scanf("%d", &n); n1=n; while(n1!=0) { rem=n1%10;
num+=rem*rem*rem; n1/=10; } if(num==n) printf("%d is an Armstrong
number.",n); else printf("%d is not an Armstrong number.",n);

return 0; }

Fibonacci Series without Recursion Numbers of Fibonacci sequence are known


as Fibonacci numbers. First few numbers of series are 0, 1, 1, 2, 3, 5, 8 etc.,
except first two terms in sequence every other term is the sum of two previous
terms, For example 8 = 3 + 5 (addition of 3, 5). This sequence has many
applications in mathematics and Computer Science.

Program No. 68

Input any number and display count of all digits

/* Fibonacci Series c language */

#include<stdio.h>
int main()
{
int n, first = 0, second = 1, next, c;
printf("Enter the number of terms\n");
scanf("%d",&n);
printf("First %d terms of Fibonacci series are :-\n",n);
c = 0;
while(c < n )
{
if ( c <= 1 )
next = c;
else
{
next = first + second;
first = second;
second = next;
}
printf("%d\n",next);
c++;
}
return 0;
}
Assignment

Program No. 69

C Program to print table of a number.

Program No. 70

C Program to check entered number is palindrome or not

Break and Continue Statement


There are two statements built in C programming, break; and continue; to alter the
normal flow of a program. Loops perform a set of repetitive task until text
expression becomes false but it is sometimes desirable to skip some statement/s
inside loop or terminate the loop immediately without checking the test expression.

In such cases, break and continue statements are used. The break; statement is also
used in switch statement to exit switch statement.

break Statement
In C programming, break is used in terminating the loop immediately after it is
encountered. The break statement is used with conditional if statement.
Syntax of break statement
break;
The break statement can be used in terminating all three loops for, while and
do...while loops.

The figure below explains the working of break statement in all three type of loops.
Program No. 71

Demonstration of break statements

#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* while loop execution */
while( a < 20 )
printf("value of a: %d\n", a);
a++;
if( a > 15)
{
/* terminate the loop using break statement */
break;
}
}
return 0;
}
Program No. 72

Write a C program to find average of maximum of n positive numbers entered


by user. But, if the input is negative, display the average(excluding the average
of negative input) and end the program.

# include <stdio.h>
int main()
{
float num,average,sum;
int i,n;
printf("Maximum no. of inputs\n");
scanf("%d",&n);
i = 1;
while(i<=n)
{
printf("Enter n%d: ",i);
scanf("%f",&num);
if(num<0.0)
{
break;
}
//for loop breaks if num<0.0
sum=sum+num;
i++; }
average=sum/(i-1);
printf("Average=%.2f",average);
return 0;
}

Continue Statement
It is sometimes desirable to skip some statements inside the loop. In such cases,
continue statements are used.

Syntax of continue Statement continue; Just like break, continue is also used with
conditional if statement.
For better understanding of how continue statements works in C programming.
Analyze the figure below which bypasses some code/s inside loops using continue
statement.
Program No. 73
Demonstration of continue statment #include <stdio.h> int main () {
/* local variable definition */ int a = 10;
/* do loop execution */ do { if( a == 15) { /* skip the iteration */
a = a + 1; continue; } printf("value of a: %d\n", a); a++; } while(
a < 20 ); return 0; }
Program No. 74
Write a C program to find the product of 4 integers entered by a user. If user enters 0
skip it. # include <stdio.h>
int main() { int i,num,product; i = 1; product = 1; while(i<=4) {
printf("Enter num%d:",i); scanf("%d",&num); if(num==0)
continue; / *In this program, when num equals to zero, it skips
the statement product*=num and continue the loop. */ product*=num; i++;
} printf("product=%d",product); return 0; }
Program No. 75

C Program to Check Whether a Number is Prime or Not A positive integer which is


only divisible by 1 and iself is known as prime number. For example: 13 is a prime
number because it is only divisible by 1 and 13 but, 15 is not prime number because
it is divisible by 1, 3, 5 and 15.

Nested While Loop


C programming allows to use one loop inside another loop. The following section
shows a few examples to illustrate the concept.

while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}

Do-While Loop

Unlike for and while loops, which test the loop condition at the top of the loop, the
do...while loop in C programming checks its condition at the bottom of the loop.

A do...while loop is similar to a while loop, except the fact that it is guaranteed to
execute at least one time.

Syntax The syntax of a do...while loop in C programming language is −

do {

statement(s);

} while(condition );

Notice that the conditional expression appears at the end of the loop, so the
statement(s) in the loop executes once before the condition is tested.

If the condition is true, the flow of control jumps back up to do, and the statement(s)
in the loop executes again. This process repeats until the given condition becomes
false
Program No. 84

Demonstrate do-while loop


#include <stdio.h>
#include<conio.h>
void main ()
{
int a = 10;
clrscr();
do
{
printf("value of a: %d\n", a);
a = a + 1;
}
while( a < 20 );
getch(); }
Program No. 85

Input roll no and name of students until user enters “y” for next records
#include <stdio.h>
#include<conio.h>
void main ()
{ int roll;
char sname[40],
choice;
clrscr();
do
{
printf("\n\t Enter Roll No. :”);
scanf(“%d”, &roll);
fflush(stdin);
printf(“\n\t Enter Student Name :”);
gets(sname);
fflush(stdin);
printf(“\n\t Enter another record ? [Y/N] :”);
scanf(“%c”, &choice);
}
while(choice==‘y’ || choice== ‘Y’);
getch(); }
Program No. 86

Write a C program to add all the numbers entered by a user until user enters 0

#include <stdio.h>
#include<conio.h>
void main ()
{
int sum=0,num;
clrscr();
do
{
printf("Enter a number\n");
scanf("%d",&num);
sum+=num;
}
while(num!=0);
printf("sum=%d",sum);
getch(); }

for loop
A for loop is a repetition control structure that allows you to efficiently write a loop
that needs to execute a specific number of times.

The syntax of a for loop in C programming language is −


for ( init; condition; increment )
{
statement(s); }
Here is the flow of control in a 'for' loop − The init step is executed first, and only
once. This step allows you to declare and initialize any loop control variables. You
are not required to put a statement here, as long as a semicolon appears.

 Next, the condition is evaluated. If it is true, the body of the loop is executed.
If it is false, the body of the loop does not execute and the flow of control
jumps to the next statement just after the 'for' loop.
 After the body of the 'for' loop executes, the flow of control jumps back up to
the increment statement. This statement allows you to update any loop
control variables. This statement can be left blank, as long as a semicolon
appears after the condition.
 The condition is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then increment step, and then again
condition). After the condition becomes false, the 'for' loop terminates.

Program No. 87
For loop example
#include <stdio.h>
#include<conio.h>
void main ()
{
int a;
clrscr();
for( a = 10; a < 20; a = a + 1 )
{
printf("value of a: %d\n", a);
}
getch();
}
Program No. 88
calculate the sum of the series 13 + 23 + 33 +. . . . . . . . + n3 and print the result
#include<stdio.h> #include<conio.h> #include<math.h> void main() { int n,i;
int sum=0; clrscr(); printf("Enter the value of n :\n"); scanf("%d",&n);
sum=pow(((n*(n+1))/2),2); printf("Sum of the series : "); for(i=1;i<=n;i++)
{ if (i != n) { printf("%d^3 + ",i); } else { printf("%d^3
= %d ",i,sum); } } getch(); }
C Unformatted Input Output Functions
In the unformatted Input/Output category, we have functions for
performing input/output of one character at a time, known as
character I/O functions and functions that perform input/output
of one string at a time, known as string I/O functions.

Now here we will discuss about unformatted i/o functions. There


are several standard library functions available in this category –
those that can deal with a single character and those that can
deal with a string of characters. The various unformatted
input/output functions in C are shown below

unformatted function types

1. CharacterInput/output functions

 Single Character Input – THE getchar FUNCTION


 Single Character Output – THE putchar FUNCTION

2.StringInput/output functions

 Single String Input – THE gets FUNCTION


 Single String Output – THE puts FUNCTION
:

Single Character Input – THE getchar() FUNCTION

 Single characters can be entered into the computer using


the C library function getchar() .
 The getchar function is a part of the standard C
Input/output functions library.
 It returns a single character from a standard input device
(typically a keyboard).
 The function does not require any arguments, though a pair
of empty parentheses must follow the word getchar.
 In general terms, a function reference would be written as:

CharacterVariable = getchar();
Where character variable refers to some previously declared
character variable.

“ch = getchar( )” will reads a character from the keyboard and


copy it into memory area which is identified by the variable ch.
No arguments are required for this macro. Once the character is
entered from the keyboard, the user has to press Enter key.

Single Character Output – THE putchar FUNCTION

 Single characters can be displayed (i.e., written out of the


computer) using the C library function putchar .
 The putchar function, like getchar function is a part of the
standard C Input/Output functions library .
 It transmits a single character to a standard output device
(typically a monitor). The character being transmitted will
normally be represented as a character-type variable.
 It must be expressed as an argument to the function,
enclosed in parentheses, following the word putchar.
 In general , a function reference would be written as:

putchar(character variable);
Where character variable refers to some previously declared
character variable.

“putchar(ch)” outputs a character stored in a variable on the


monitor. The variable should be passed as parameter as shown
in the above syntax.
Example1
main()
{
char ch;
clrscr();
ch = getchar();
putchar(ch);
getch();
}
getchar() and putchar() functions are part of the standard C
library header stdio.h
Example:2

#include <stdio.h>

int main()

charch;

printf("Input some character and finish by pressing the Enter


key.\n");

ch = getchar();

printf("The input character is ");

putchar(ch);

return 0;

If we run this program and enter the characters "apple" at the


prompt then the output will be as shown below
Input some character and finish by pressing the Enter key

apple

The input character is a

Please note that when you entered the word apple those
characters were echoed on the screen. You also terminated the
input by pressing the Enter key. However getchar() function
took only the first character, which is "a" from the input
and putchar() function printed it out.

getch(), getche() and putch()

These functions are similar to getchar() and putchar(), but


they come from the library header conio.h.

The functions getch() and getche() are used to read a character


from the keyboard, similar to getchar(). Both functions don’t
need a return key pressed to terminate the reading of a
character. A character entered will itself terminates reading.
getch() reads a single character from the standard input.
The input character is not displayed (echoed) on the screen.
Unlike the getchar() function, getch() returns when the first
character is entered and does not wait for the Enter key to be
pressed.
getche() is same as getch() except that it echoes the input
character.
putch() writes a character that is passed as an argument to the
console.

ch = getch(); /*Typed character will not be displayed on


the screen*/
ch = getche(); /*Typed character will be displayed on the
screen*/
Now, we have to display the inputted character on the screen,
putch() macro is introduced.
“putch(ch)” This function outputs a character stored in the
memory, on the monitor. The variable should be passed as
parameter to the functions. In the above syntax ‘ch’ is used as an
argument and its value is displayed on the screen.
Example1:
main()
{
char ch;
clrscr();
ch = getche();
putch(ch);
getch();
}
Example2

#include <conio.h>

#include <stdio.h>

int main()

charch;

printf("Press any key\n");

ch = getch();

printf("The key pressed is: ");


putch(ch);

return 0;

If we run this program and press any key, let's say "x", then the
output will be as shown below:

Press any key

The key pressed is x

Please note here that the character "x" was not echoed when you
entered it.

gets() and puts()


Multiple Characters Output – THE puts FUNCTION

 Multiple characters can be displayed (i.e., written out of the


computer) using the C library function puts.
 The puts function, like gets function is a part of the
standard C Input/Output functions library .
 It transmits a character array to a standard output device
(typically a monitor). The character array being transmitted
will normally be represented as a character-type array .
 It must be expressed as an argument to the function,
enclosed in parentheses, following the word puts.
 In general terms, a function reference would be written as:

puts(character array);

where character array refers to some previously declared


character array with length/size specified (e.g., char line[80])

These functions are used to read a set of characters (string) from


the keyboard and display a set of characters (string) on the
screen.
char str[5];
gets(str); /* Reads a set of characters into memory area str */
puts(str); /* Displays a set of characters from memory area str */
Example1
main()
{
char str[10];
clrscr();
gets(str);
puts(str);
getch();
}

String I/O in C

gets() in C

✍ The gets() function can read a full string even blank spaces
presents in a string. But, the scanf() function leave a string
after blank space is detected.
✍ The gets() function is used to get any string from the user.

Example C program - gets()

 #include <stdio.h>
 int main()
 {
 char c[25];
 printf("Enter a string : ");
 gets(c);
 printf("\n%s is awesome ",c);
 return 0;
 }

Output

 Enter a string : This book is


This book is awesome

Note:

The gets() function reads a string from through keyboard and


stores it in character array c[25].
The printf() function displays a string on the console.

puts() in C

✍ The puts() function prints the charater array or string on the


console.

✍ The puts() function is similar to printf() function, but we


cannot print other than characters using puts() function.

Example C program - puts()

 #include <stdio.h>
 int main()
 {
 char c[25];
 printf("Enter your Name : ");
 gets(c);
 puts(c);
 return 0;
 }
Output

 Enter your Name: pooja

pooja

Note:

puts() displays the name you entered to the console. The


C – Strings and String functions .
String is nothing but an array of characters (OR char data types).
While doing programming in C language, you may have faced
challenges wherein you might want to compare two strings,
concatenate strings, copy one string to another & perform various
string manipulation operations. All of such kind of operations plus
many more other functions are available in “string.h” header file. In
order to use these string functions you must include string.h file in
your C program.

In C programming, one dimensional array of characters is called a


string. A string is terminated by a null character /0. For example:

"c string tutorial"

Here, "c string tutorial" is a string. When, compiler encounter strings,


it appends a null character /0 at the end of string.
 String Declaration

Before we actually work with strings, we need to declare them first.

Strings are declared in a similar manner as arrays. Only difference is that,


strings are of char type.

Using arrays

char s[5];

Using pointers

Strings can also be declared using pointer.

char *p;

 Initialization of strings

In C, string can be initialized in a number of different ways.

For convenience and ease, both initialization and declaration are done in the
same step.
Using arrays

char c[] = "abcd";

OR,

char c[50] = "abcd";

OR,

char c[] = {'a', 'b', 'c', 'd', '\0'};

OR,

char c[5] = {'a', 'b', 'c', 'd', '\0'};

The given string is initialized and stored in the form of arrays as above.

Using pointers

String can also be initialized using pointers as:


char *c = "abcd";

 Reading Strings from user


String I/O

You can use the scanf() function to read a string like any other data types.

However, the scanf() function only takes the first entered word. The function
terminates when it encounters a white space (or just space).

Reading words from user

char c[20];
scanf("%s", c);

Example #1: Using scanf() to read a string

Write a C program to illustrate how to read string from terminal.

#include<stdio.h>

int main()

char name[20];

printf("Enter name: ");

scanf("%s", name);

printf("Your name is %s.", name);

return0;

Output

Enter name: Pooja Patil

Your name is Pooja


Here, program ignores Patil because, scanf() function takes only a single
string before the white space, i.e. Pooja.

Reading a line of text

An approach to reading a full line of text is to read and store each character
one by one.

Example #2: Using getchar() to read a line of text

1. C program to read line of text character by character.

#include<stdio.h>

int main()

char name[30],ch;

int i =0;

printf("Enter name: ");

while(ch!='\n')// terminates if user hit enter

ch=getchar();

name[i]=ch;

i++;
}

name[i]='\0';// inserting null character at end

printf("Name: %s", name);

return0;

In the program above, using the function getchar(), ch gets a single character
from the user each time.

This process is repeated until the user enters return (enter key). Finally, the
null character is inserted at the end to make it a string.

This process to take string is tedious.

Example #3: Using standard library function to read a line of text

2. C program to read line of text using gets() and puts()

To make life easier, there are predefined functions gets() and puts in C
language to read and display string respectively.

#include<stdio.h>

int main()

{
char name[30];

printf("Enter name: ");

gets(name);//Function to read string from user.

printf("Name: ");

puts(name);//Function to display string.

return0;

Both programs have the same output below:

Output

Enter name: Tom Hanks

Name: Tom Hanks

Passing Strings to Functions

Strings are just char arrays. So, they can be passed to a function in a similar
manner as arrays.

Learn more about passing array to a function.


#include<stdio.h>

voiddisplayString(charstr[]);

int main()

charstr[50];

printf("Enter string: ");

gets(str);

displayString(str);// Passing string c to function.

return0;

voiddisplayString(charstr[]){

printf("String Output: ");

puts(str);

Here, string c is passed from main() function to user-defined


function displayString(). In function declaration, str[] is the formal argument.
Read & Write Strings Using Printf and Scanf –

#include<stdio.h>
#include<string.h>
int main()
{
/* String Declaration*/
char nickname[20];

printf("Enter your Nick name:");

/*I am reading the input string and storing it in nickname*/


scanf("%s", &nickname);

/*Displaying String*/
printf("%s",nickname);

return0;
}
Note: %s is used for strings I/O

Read & Write Strings Using gets and puts –

#include<stdio.h>
#include<string.h>
int main()
{
/* String Declaration*/
char nickname[20];

/* Console display using puts */


puts("Enter your Nick name:");

/*Input using gets*/


gets(nickname);

puts(nickname);

return0;
}
 String functions

strlen function: size_t strlen(const char *str)

size_t represents unsigned short


It returns the length of the string without including end
character (terminating char ‘\0’).

Example:
#include<stdio.h>
#include<string.h>
int main()
{
char str1[20] = "BeginnersBook";
printf("Length of string str1: %d", strlen(str1));
return0;
}
Output:

Length of string str1: 13


Strlen vs sizeof
strlen returns you the length of the string stored in array, however sizeof
returns the total allocated size assigned to the array. So if I consider the above
example again then the following statements would return the below values.

strlen(str1) returned value 13.


sizeof(str1) would return value 20 as the array size is 20 (see the first
statement in main function).

strnlen function: size_t strnlen(const char *str, size_t maxlen)

size_t represents unsigned short


It returns length of the string if it is less than the value specified for maxlen
(maximum length) otherwise it returns maxlen value.
Example:

#include<stdio.h>
#include<string.h>
int main()
{
char str1[20] = "BeginnersBook";
printf("Length of string str1 when maxlen is 30: %d", strnlen(str1, 30));
printf("Length of string str1 when maxlen is 10: %d", strnlen(str1, 10));
return0;
}
Output:
Length of string str1 when maxlen is 30: 13
Length of string str1 when maxlen is 10: 10

Have you noticed the output of second printf statement, even though the string
length was 13 it returned only 10 because the maxlen was 10.

strcmp function: int strcmp(const char *str1, const char *str2)

It compares the two strings and returns an integer value. If both the strings are
same (equal) then this function would return 0 otherwise it may return a
negative or positive value based on the comparison.
If string1 < string2 OR string1 is a substring of string2 then it would result
in a negative value.

If string1 > string2 then it would return positive value.


If string1 == string2 then you would get 0(zero) when you use this function
for compare strings.

Example:

#include<stdio.h>
#include<string.h>
int main()
{
char s1[20] = "BeginnersBook";
char s2[20] = "BeginnersBook.COM";
if (strcmp(s1, s2) ==0)
{
printf("string 1 and string 2 are equal");
}else
{
printf("string 1 and 2 are different");
}
return0;
}
Output:

string1and2 are different


strncmp function: int strncmp(const char *str1, const char *str2, size_t n)

size_t is for unassigned short


It compares both the string till n characters or in other words it compares first
n characters of both the strings.

Example:

#include<stdio.h>
#include<string.h>
int main()
{
char s1[20] = "BeginnersBook";
char s2[20] = "BeginnersBook.COM";
/* below it is comparing first 8 characters of s1 and s2*/
if (strncmp(s1, s2, 8) ==0)
{
printf("string 1 and string 2 are equal");
}else
{
printf("string 1 and 2 are different");
}
return0;
}
Output:

string1 and string2 are equal


strcat function: char *strcat(char *str1, char *str2)

It concatenates two strings and returns the combined one string.

Example:

#include<stdio.h>
#include<string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
return0;
}
Output:

Outputstring after concatenation: HelloWorld


strncat function: char *strncat(char *str1, char *str2, int n)
It concatenates n characters of str2 to string str1. A terminator char (‘\0’) will
always be appended at the end of the concatenated string.

Example:

#include<stdio.h>
#include<string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strncat(s1,s2, 3);
printf("Concatenation using strncat: %s", s1);
return0;
}
Output:

Concatenationusingstrncat: HelloWor
strcpy function: char *strcpy( char *str1, char *str2)

It copies the string str2 into string str1, including the end character (terminator
char ‘\0’).

Example:
#include<stdio.h>
#include<string.h>
int main()
{
char s1[30] = "string 1";
char s2[30] = "string 2 : I’m gonna copied into s1";
/* this function has copied s2 into s1*/
strcpy(s1,s2);
printf("String s1 is: %s", s1);
return0;
}
Output:

String s1 is: string2: I’m gonna copied into s1


char *strncpy( char *str1, char *str2, size_t n)

size_t is unassigned short and n is a number.


Case1: If length of str2 > n then it just copies first n characters of str2 into
str1.
Case2: If length of str2 < n then it copies all the characters of str2 into str1
and appends several terminator chars(‘\0’) to accumulate the length of str1 to
make it n.

Example:
#include<stdio.h>
#include<string.h>
int main()
{
char first[30] = "string 1";
char second[30] = "string 2: I’m using strncpy now";
/* this function has copied first 10 chars of s2 into s1*/
strncpy(s1,s2, 12);
printf("String s1 is: %s", s1);
return0;
}
Output:

String s1 is: string2: I’m


strchr function: char *strchr(char *str, intch)

It searches string str for character ch. The thing is when we give any character
while using strchr then it internally gets converted into integer for better
searching.

Example:

#include<stdio.h>
#include<string.h>
int main()
{
charmystr[30] = "I’m an example of function strchr";
printf ("%s", strchr(mystr, 'f'));
return0;
}
Output:

ffunctionstrchr
Strrchr function: char *strrchr(char *str, intch)

It is similar to the function strchr, the only difference is that it searches the
string in reverse order, now you would have understood why we have extra r
in strrchr, yes you guessed it rite it is for reverse only.

Now let’s take the same above example:

#include<stdio.h>
#include<string.h>
int main()
{
charmystr[30] = "I’m an example of function strchr";
printf ("%s", strrchr(mystr, 'f'));
return0;
}
Output:
functionstrchr
Why output is different than strchr? It is because it started searching from
the end of the string and found the first ‘f’ in function instead of ‘of’.

strstr function: char *strstr(char *str, char *srch_term)

It is similar to strchr, except that it searches for string srch_term instead of a


single char.

Example:

#include<stdio.h>
#include<string.h>
int main()
{
charinputstr[70] = "String Function in C at BeginnersBook.COM";
printf ("Output string is: %s", strstr(inputstr, 'Begi'));
return0;
}
Output:

Outputstringis: BeginnersBook.COM
You can also use this function n place of strchr as you are allowed to give
single char also in place of search_term string.
Function
A function is a block of statements, which is
used to perform a specific task. Suppose you are
building an application in C language and in one
of your program, you need to perform a same task
more than once. So in such scenario you have two
options –
a) Use the same set of statements every time you
want to perform the task
b) Create a function, which would do the task,
and just call it every time you need to perform
the same task.
Using option (b) is a good practice and a good
programmer always uses functions while writing
codes.
Types of functions
1) Predefined standard library functions –
such as puts(), gets(), printf(), scanf() etc –
These are the functions which already have a
definition in header files (.h files
like stdio.h), so we just call them whenever
there is a need to use them.
2) User Defined functions –
The functions which we can create by ourselves.
Why we need functions
[Why write separate functions at all? Why not
squeeze the entire logic into one function, main(
)? Two reasons:
(a) Writing functions avoids rewriting the same
code over and over. Suppose you have a section
of code in your program that calculates area of
a triangle. If later in the program you want to
calculate the area of a different triangle, you
won’t like it if you are required to write the
same instructions all over again. Instead, you
would prefer to jump to a ‘section of code’
that calculates area and then jump back to the
place from where you left off. This section of
code is nothing but a function.
(b) Using functions it becomes easier to write
programs and keep track of what they are doing.
If the operation of a program can be divided
into separate activities, and each activity
placed in a different function, then each could
be written and checked more or less
independently. Separating the code into modular
functions also makes the program easier to
design and understand.

Advantages of Functions –
a) To improve the readability of code.
b) Improves the reusability of the code, same
function can be used in any program rather than
writing the same code from scratch.
c) Debugging of the code would be easier if you
use functions as errors are easy to be traced.
d) Reduces the size of the code, duplicate set of
statements are replaced by function calls.

 Defining a function
return_type function_name (argument list)
{
Set of statements – Block of code
}

return_type:
Return type can be of any data type such as int,
double, char, void, short etc.
function_name:
It can be anything, however it is advised to have
a meaningful name for the functions so that it
would be easy to understand the purpose of
function just by seeing it’s name.

argument list:
Argument list contains variables names along with
their data types. These arguments are kind of
inputs for the function. For example – A function
which is used to add two integer variables, will
be having two integer argument.
Block of code:
Set of C statements, which will be executed
whenever a call will be made to the function.
Suppose you want to create a function which would
add two integer variables.
Function will sum up two numbers so it’s name
should be sum, addition, etc…
return_type addition(argument list)

This function is going to add two integer


variables, which means we need two integer
variable as input
return_type addition(int num1, int num2)
The result of the sum of two integers would be
integer only. Hence function should return an
integer value – so return type – It should be
integer –
int addition(int num1, int num2);
So you got your function prototype or signature.
Now you can add logic to that in the below
example-
Example1:
Example1:
int addition(int num1, int num2)
{
int sum
/* Arguments are used here*/
sum = num1+num2;
/* function return type is integer so it should
return some integer value */
return sum;
}
int main()
{
int var1, var2, res;
printf("enter number 1: ");
scanf("%d",&var1);
printf("enter number 2: ");
scanf("%d",&var2);
/* calling function – function return type is integer so
define integer variable
* to store the returned value */
res = addition(var1, var2);
printf ("Output: %d", res);

return 0;
}
Example2:
Example2:
/* function return type is void and doesn't have
parameters*/
void introduction()
{
printf("Hi\n");
printf("My name is Pooja\n");
printf("How are you?");
/* there is no return statement inside this function,
since its return type is void */
}
int main()
{
/*calling function*/
introduction();
return 0;

Example:3
}
main( )
{
message( ) ;
printf ( "\nCry, and you stop the monotony!" ) ;
}
message( )
{
printf ( "\nSmile, and the world smiles with you..." ) ;
}
And here’s the output...
Smile, and the world smiles with you...
Cry, and you stop the monotony!
Here, main( ) itself is a function and through it we are
calling the function message( ). What do we mean when we say
that main( ) ‘calls’ the function message( )? We mean that the
control passes to the function message( ). The activity of
main( ) is temporarily suspended; it falls asleep while the
message( ) function wakes up and goes to work. When the
message( ) function runs out of statements to execute, the
control returns to main( ), which comes to life again and
begins executing its code at the exact point where it left off.
Thus, main( ) becomes the ‘calling’ function, whereas message(
) becomes the ‘called’ function.
If you have grasped the concept of ‘calling’ a function you are
prepared for a call to more than one function. Consider the
following example:
main( )
{
printf ( "\nI am in main" ) ;
italy( ) ;
brazil( ) ;
argentina( ) ;
}
italy( )
{
printf ( "\nI am in italy" ) ;
}
brazil( )
{
printf ( "\nI am in brazil" ) ;
}
argentina( )
{
printf ( "\nI am in argentina" ) ;
}
The output of the above program when executed
would be as under:
I am in main
I am in italy
I am in brazil
I am in argentina
From this program a number of conclusions can be
drawn:
− Any C program contains at least one function.
− If a program contains only one function, it
must be main( ).
− If a C program contains more than one function,
then one (and only one) of these functions must
be main( ), because program execution always
begins with main( ).
− There is no limit on the number of functions
that might be present in a C program.
− Each function in a program is called in the
sequence specified by the function calls in
main( ).
− After each function has done its thing, control
returns to main( ).When main( ) runs out of
function calls, the program ends.

As we have noted earlier the program execution


always begins with main( ).
main( )
{
printf ( "\nI am in main" ) ;
italy( ) ;
printf ( "\nI am finally back in main" ) ;
}
italy( )
{
printf ( "\nI am in italy" ) ;
brazil( ) ;
printf ( "\nI am back in italy" ) ;
}
brazil( )
{
printf ( "\nI am in brazil" ) ;
argentina( ) ;
}
argentina( )
{
printf ( "\nI am in argentina" ) ;
}
And the output would look like
I am in main
I am in italy
I am in brazil
I am in argentina
I am back in italy
I am finally back in main

 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.
A function declaration has the following parts:
return_type function_name( parameter list );
For ex.max(),the function declaration is as
follows:
int max(int num1, int num2);
Parameter names are not important in function
declaration, only their type is required, so the
following is also a valid declaration:
int max(int, int);
Function declaration is required when you define
a function in one source file
and you call that function in another file. In
such case, you should declare the
function at the top of the file calling the
function
Calling a Function
While creating a C function, you give a
definition of what the function has to do.To use
a function, you will have to call that function
to perform the defined task.
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.
For example:
#include <stdio.h>
/* function declaration */
int max(int num1, int num2);
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
/* calling a function to get max value */
ret = max(a, b);
printf( "Max value is : %d\n", ret );
return 0;
}
/* function returning the max between two numbers
*/
int max(int num1, int num2)
{
/* local variable declaration */
int result;

if (num1 > num2)


result = num1;
else
result = num2;
return result;
}
We have kept max()along with main() and compiled
the source code. While running the final
executable, it would produce the following
result:
Max value is : 200

Call by Value and Call by Reference


By now we are well familiar with how to call
functions. But, if you observe carefully,
whenever we called a function and passed
something to it we have always passed the
‘values’ of variables to the called function.
Such function calls are called ‘calls by
value’. By this what we mean is, on calling a
function we are passing values of variables to
it. The examples of call by value are shown
below:
sum = calsum ( a, b, c ) ;
f = factr( a ) ;
We have also learnt that variables are stored
somewhere in memory. So instead of passing the
value of a variable, can we not pass the location
number (also called address) of the variable to a
function? If we were able to do so it would
become a ‘call by reference’.

1. Call by Value
The call by value method of passing arguments to
a function copies the actual value of an argument
into the formal parameter of the function. In
this case,
changes made to the parameter inside the function
have no effect on the
argument.
By default, C programming 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. Consider the function swap() definition
as follows.
/* function definition to swap the values */
void swap(int x, int y)
{
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */
return;
}
Now, let us call the function swap() by passing
actual values as in the following
example:
#include <stdio.h>
/* function declaration */
void swap(int x, int y);
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values */
swap(a, b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}
Let us put the above code in a single C file,
compile and execute it, it will
produce the following result:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
It shows that there are no changes in the values,
though they had been changed inside the function.

2. Call by Reference
The call by reference method of passing arguments
to a function copies the address of an argument
into the formal parameter. Inside the function,
the address is used to access the actual argument
used in the call. It means the changes made to
the parameter affect the passed argument.
To pass a value by reference, argument pointers
are passed to the functions just like any other
value. So accordingly, you need to declare the
function parameters as pointer types as in the
following function swap(), which
exchanges the values of the two integer variables
pointed to, by their
arguments.
/* function definition to swap the values */
void swap(int *x, int *y)
{
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
return;
}
Let us now call the function swap() by passing
values by reference as in the
following example:
#include <stdio.h>
/* function declaration */
void swap(int *x, int *y);
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values.
* &a indicates pointer to a i.e. address of
variable a and
* &b indicates pointer to b i.e. address of
variable b.
*/
swap(&a, &b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}
Let us put the above code in a single C file,
compile and execute it, to produce
the following result:
Before swap, value of a :100
Before swap, value of b :200

After swap, value of a :200


After swap, value of b :100
It shows that the change has reflected outside
the function as well, unlike call
by value where the changes do not reflect outside
the function.
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.
There are five types of functions and they are:
1. Functions with no arguments and no return
values.
2. Functions with arguments and no return
values.
3. Functions with arguments and return values.
4. Functions that return multiple values.
5. Functions with no arguments and return
values.
1. Functions with no arguments and no return
value.
A C function without any arguments means you
cannot pass data (values like int, char etc) to
the called function. Similarly, function with no
return type does not pass back data to
the calling function. It is one of the simplest
types of function in C. This type of function
which does not return any value cannot be used in
an expression it can be used only as independent
statement.
1 #include<stdio.h>
2 #include<conio.h>
3
4 Void printline()
5 {
6 inti;
7 printf("\n");
8 for(i=0;i<30;i++)
9 {
10 printf("-");
11 }
12 printf("\n");
13 }
14
15 voidmain()
16 {
17 clrscr();
18 printf("Welcome to function in
19 C");
20 printline();
21 printf("Function easy to
22 learn.");
23 printline();
getch();
}

Logic of the functions with no arguments and no


return value.
Output

Output of above program.


Source Code Explanation:
The above C program example illustrates that how
to declare a function with no argument and no
return type.
Line 4-13: This C code block is a user defined
function (UDF) whose task is to print a
horizontal line. As you can see in line no. 8 we
have declared a “for loop” which loops 30 time
and prints “-” symbol continuously.
Line 15-23: These line are “main()” function code
block. Line no. 18 and 20 simply prints two
different messages. And line no. 19 and 21 calls
our user defined function “printline()”.
2. Functions with arguments and no return
value.
In our previous example what we have noticed that
“main()” function has no control over the UDF
“printfline()”, it cannot control its output.
Whenever “main()” calls “printline()”, it simply
prints line every time. So the result remains the
same.

A C function with arguments can perform much


better than previous function type. This type of
function can accept data from calling function.
In other words, you send data to the called
function from calling function but you cannot
send result data back to the calling function.
Rather, it displays the result on the terminal.
But we can control the output of function by
providing various values as arguments. Let’s have
an example to get it better.
?
1 #include<stdio.h>
2 #include<conio.h>
3
4 voidadd(intx, inty)
5 {
6 intresult;
7 result = x+y;
8 printf("Sum of %d and %d is
9 %d.\n\n",x,y,result);
10 }
11
12 voidmain()
13 {
14 clrscr();
15 add(30,15);
16 add(63,49);
17 add(952,321);
18 getch();
}

Logic of the function with arguments and no


return value.
Output

Output of above program.


Source Code Explanation:
This program simply sends two integer arguments
to the UDF “add()” which, further, calculates its
sum and stores in another variable and then
prints that value. So simple program to
understand.
Line 4-9: This C code block is “add()” which
accepts two integer type arguments. This UDF also
has an integer variable “result” which stores the
sum of values passed by calling function (in this
example “main()”). And line no. 8 simply prints
the result along with argument variable values.
Line 11-18: This code block is a “main()”
function but only line no. 14, 15, 16 is
important for us now. In these three lines we
have called same function “add()” three times but
with different values and each function call
gives different output. So, you can see, we can
control function’s output by providing different
integer parameters which was not possible in
function type 1. This is the difference between
“function with no argument” and “function with
argument”.
3. Functions with arguments and return value.
This type of function can send arguments (data)
from the calling function to the called function
and wait for the result to be returned back from
the called function back to the calling function.
And this type of function is mostly used in
programming world because it can do two way
communications; it can accept data as arguments
as well as can send back data as return value.
The data returned by the function can be used
later in our program for further calculations.
?
#include<stdio.h>
1
#include<conio.h>
2
3
intadd(intx, inty)
4
{
5
intresult;
6
result = x+y;
7
return(result);
8
}
9
10
voidmain()
11
{
12
intz;
13
clrscr();
14
15
z = add(952,321);
16
printf("Result
17
%d.\n\n",add(30,55));
18
printf("Result %d.\n\n",z);
19
20
getch();
21
}
Logic of the function with arguments and return
value.

Output of the above program.


Source Code Explanation:
This program sends two integer values (x and y)
to the UDF “add()”, “add()” function adds these
two values and sends back the result to the
calling function (in this program to “main()”
function). Later result is printed on the
terminal.
Line No. 4-9: Look line no. 4 carefully, it
starts with int. This int is the return type of
the function, means it can only return integer
type data to the calling function. If you want
any function to return character values then you
must change this to char type. In line no. 8 you
can see return statement, return is a keyword and
in bracket we can give values which we want to
return. You can assign any integer value to
experiment with this return which ultimately will
change its output. Do experiment with all you
program and don’t hesitate.
Line No. 11-21: In this code block only line no.
16, 17 and 18 is important. We have declared an
integer “z” which we used in line no. 16. Why we
are using integer variable “z” here? You know
that our UDF “add()” returns an integer value on
calling. To store that value we have declared an
integer value. We have passed 952, 321 to the
“add()” function, which finally return 1273 as
result. This value will be stored in “z” integer
variable. Now we can use “z” to print its value
or to other function.
You will also notice some strange statement in
line no. 17. Actually line no. 17 and 18 does the
same job, in line no. 18 we have used an extra
variable whereas on line no. 17 we directly
printed the value without using any extra
variable. This was simply to show you how we
can use function in different ways.
4. Functions with no arguments but returns value.
We may need a function which does not take any
argument but only returns values to the calling
function then this type of function is useful.
The best example of this type of function is
“getchar()” library function which is declared in
the header file “stdio.h”. We can declare a
similar library function of own. Take a look.
?
1 #include<stdio.h>
2 #include<conio.h>
3
4 int send()
5 {
6 int no1;
7 printf("Enter a no : ");
8 scanf("%d",&no1);
9 return(no1);
10 }
11
12 voidmain()
13 {
14 int z;
15 clrscr();
16 z = send();
17 printf("\nYou entered : %d.",
18 z);
19 getch();
}
Functions with no arguments and return values.

Output of the above program.


Source Code Explanation:
In this program we have a UDF which takes one
integer as input from keyboard and sends back to
the calling function.
5. Functions that return multiple values.
So far, we have learned and seen that in a
function, return statement was able to return
only single value. That is because; a return
statement can return only one value. But if we
want to send back more than one value then how we
could do this?
We have used arguments to send values to the
called function, in the same way we can also use
arguments to send back information to the calling
function. The arguments that are used to send
back data are called Output Parameters.
It is a bit difficult for novice because this
type of function uses pointer. Let’s see an
example:
?
1 #include<stdio.h>
2 #include<conio.h>
3
4 voidcalc(intx, inty, int*add,
5 int*sub)
6 {
7 *add = x+y;
8 *sub = x-y;
9 }
10
11 voidmain()
12 {
13 inta=20, b=11, p,q;
14 clrscr();
15 calc(a,b,&p,&q);
16 printf("Sum = %d, Sub =
17 %d",p,q);
getch();
}

Output of the above program.


Source Code Explanation:
Logic of this program is that we call UDF
“calc()” and sends argument then it adds and
subtract that two values and store that values in
their respective pointers. The “*” is known as
indirection operator whereas “&” known as address
operator. We can get memory address of any
variable by simply placing “&” before variable
name. In the same way we get value stored at
specific memory location by using “*” just before
memory address. These things are a bit confusing
but when you will understand pointer then these
thing will become clearer.
Line no. 4-8: This UDF function is different from
all above UDF because it implements pointer. In
line no. 4 “Calc()” function has four arguments,
first two arguments need no explanation. Last two
arguments are integer pointer which works as
output parameters (arguments). Pointer can only
store address of the value rather than value but
when we add * to pointer variable then we can
store value at that address.
Line no. 10-17: When we call function “calc()” in
the line no. 14 then following assignments
occurs. Value of variable “a” is assigned to “x”,
value of variable “b” is assigned to “y”, address
of “p” and “q” to “add” and “sub” respectively.
In line no. 6 and 7 we are adding and subtracting
values and storing the result at their respective
memory location. This is how the program works.

Recursion in C Programming
The process of calling a function by itself is
called recursion and the function which calls
itself is called recursive function. Recursion is
used to solve various mathematical problems by
dividing it into smaller problems.
How recursion works?

void recurse()
{
... .. ...
recurse();
... .. ...
}
int main()
{
... .. ...
recurse();
... .. ...

The recursion continues until some condition is


met to prevent it.

To prevent infinite recursion, if...else


statement (or similar approach) can be used where
one branch makes the recursive call and other
doesn't.
Example1: Sum of Natural Numbers Using Recursion
#include<stdio.h>
int sum(int n);

int main()
{
int number, result;

printf("Enter a positive integer: ");


scanf("%d",&number);

result= sum(number);
printf("sum=%d", result);
}

int sum(intnum)
{
if(num!=0)
return num+ sum(num-1);// sum() function calls itself
else
return num;
}

Output

Enter a positive integer:


3
6

Initially, the sum() is called from


the main() function with number passed as an
argument.

Suppose, the value of num is 3 initially. During


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

When num is equal to 0, the if condition fails


and the else part is executed returning the sum
of integers to the main() function.
Advantages and Disadvantages of Recursion

Recursion makes program elegant and cleaner. All


algorithms can be defined recursively which makes
it easier to visualize and prove.
If the speed of the program is vital then, you
should avoid using recursion. Recursions use more
memory and are generally slow. Instead, you can
use loop.

Example #2: C program to calculate factorial of a


number using recursion.
#include<stdio.h>
int factorial(int n)
{
if(n==0)
return 1;
else
return (factorial(n-1)*n);
}

int main()
{
intnum,f;
printf("Enter a number: ");
scanf("%d",&num);
f=factorial(num);
printf("Factorial of %d = %d",num,f);
return 0;
}

Example #3: C program print first n Fibonacci


numbers using recursion.
#include<stdio.h>

intfibo(intnum)
{
if(num==1||num==2)
return 1;
else
return (fibo(num-1)+fibo(num-2)); // recursive
call
}

int main()
{
inti,n;
printf("Enter the required term: ");
scanf("%d",&n);
printf("First %d fibonacci numbers are\n",n);
for (i=1; i<=n; i++)
printf("%d\n",fibo(i));
return 0;
}

int main()
{
intnum,f;
printf("Enter a number: ");
scanf("%d",&num);
f=factorial(num);
printf("Factorial of %d = %d",num,f);
return 0;
}

Example4: Program to calculate power using


recursion

#include<stdio.h>

int power(int n1,int n2);

int main()
{
intbase,powerRaised, result;

printf("Enter base number: ");


scanf("%d",&base);

printf("Enter power number(positive integer): ");


scanf("%d",&powerRaised);

result= power(base,powerRaised);

printf("%d^%d = %d",base,powerRaised, result);


return0;
}
int power(intbase,intpowerRaised)
{
if(powerRaised!=1)
return(base*power(base, powerRaised-1));
else
return1;
}
C Dynamic Memory Allocation
In this unit, you'll learn to dynamically allocate memory in your C program
using C standard library functions: malloc(), calloc(), free() and realloc()
C Dynamic Memory Allocation
In C, the exact size of array is unknown until compile time, i.e., the time
when a compiler compiles your code into a computer understandable
language. So, sometimes the size of the array can be insufficient or more
than required.
Dynamic memory allocation allows your program to obtain more memory
space while running, or to release it if it's not required.
In simple terms, Dynamic memory allocation allows you to manually handle
memory space for your program.
Although, C language inherently does not have any technique to allocate
memory dynamically, there are 4 library functions under "stdlib.h" for
dynamic memory allocation.
Function Use of Function

malloc() Allocates requested size of bytes and returns a pointer first


byte of allocated space

calloc() Allocates space for an array elements, initializes to zero


and then returns a pointer to memory
free() deallocate the previously allocated space
realloc() Change the size of previously allocated space

1. C malloc()
The name malloc stands for "memory allocation".
The malloc() function allocates single block of requested memory.
The function malloc() reserves a block of memory of specified size and
return a pointer of type void which can be casted into pointer of any form.
It doesn't initialize memory at execution time, so it has garbage value
initially.
It returns NULL if memory is not sufficient.
Syntax of malloc()
ptr = (cast-type*) malloc(byte-size)
Here, ptr is pointer of cast-type.
The malloc() function returns a pointer to an area of memory with size of
byte size. If the space is insufficient, allocation fails and returns NULL
pointer.

ptr = (int*) malloc(100 * sizeof(int));


This statement will allocate either 200 or 400 according to size of int 2 or 4
bytes respectively and the pointer points to the address of first byte of
memory.

Let's see the example of malloc() function.


1. #include<stdio.h>
2. #include<stdlib.h>
3. int main(){
4. int n,i,*ptr,sum=0;
5. printf("Enter number of elements: ");
6. scanf("%d",&n);
7. ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
8. if(ptr==NULL)
9. {
10. printf("Sorry! unable to allocate memory");
11. exit(0);
12. }
13. printf("Enter elements of array: ");
14. for(i=0;i<n;++i)
15. {
16. scanf("%d",ptr+i);
17. sum+=*(ptr+i);
18. }
19. printf("Sum=%d",sum);
20. free(ptr);
21. return 0;
22. }

Output:

Enter elements of array: 3


Enter elements of array: 10
10
10
Sum=30

2. C calloc()
The name calloc stands for "contiguous allocation".
The calloc() function allocates multiple block of requested memory.
The only difference between malloc() and calloc() is that, malloc() allocates
single block of memory whereas calloc() allocates multiple blocks of
memory each of same size and sets all bytes to zero.

Syntax of calloc()
ptr = (cast-type*)calloc(n, element-size);
This statement will allocate contiguous space in memory for an array of n
elements. For example:

ptr = (float*) calloc(25, sizeof(float));


This statement allocates contiguous space in memory for an array of 25
elements each of size of float, i.e, 4 bytes.

3. C free()
Dynamically allocated memory created with either calloc() or malloc()
doesn't get freed on its own. You must explicitly use free() to release the
space.

syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.

4. C realloc()
If memory is not sufficient for malloc() or calloc(), you can reallocate
the memory by realloc() function. In short, it changes the memory size.

Let's see the syntax of realloc() function.

ptr=realloc(ptr, new-size)

Example #1: Using C malloc() and free()


Write a C program to find sum of n elements entered by user. To perform this
program, allocate memory dynamically using malloc() function.

#include <stdio.h>
#include <stdlib.h>

int main()
{
intnum, i, *ptr, sum = 0;

printf("Enter number of elements: ");


scanf("%d", &num);

ptr = (int*) malloc(num * sizeof(int)); //memory allocated using malloc


if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}

printf("Enter elements of array: ");


for(i = 0; i <num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}

printf("Sum = %d", sum);


free(ptr);
return 0;
}
Example #2: Using C calloc() and free()
Write a C program to find sum of n elements entered by user. To perform this
program, allocate memory dynamically using calloc() function.

#include <stdio.h>
#include <stdlib.h>

int main()
{
intnum, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);

ptr = (int*) calloc(num, sizeof(int));


if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}

printf("Enter elements of array: ");


for(i = 0; i <num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}

printf("Sum = %d", sum);


free(ptr);
return 0;
}
1. C realloc()
If the previously allocated memory is insufficient or more than required, you
can change the previously allocated memory size using realloc().

Syntax of realloc()
ptr = realloc(ptr, newsize);
Here, ptr is reallocated with size of newsize.

Example #3: Using realloc()


#include <stdio.h>
#include <stdlib.h>

int main()
{
int *ptr, i , n1, n2;
printf("Enter size of array: ");
scanf("%d", &n1);

ptr = (int*) malloc(n1 * sizeof(int));

printf("Address of previously allocated memory: ");


for(i = 0; i < n1; ++i)
printf("%u\t",ptr + i);

printf("\nEnter new size of array: ");


scanf("%d", &n2);
ptr = realloc(ptr, n2);
for(i = 0; i < n2; ++i)
printf("%u\t", ptr + i);
return 0;
}
File Input/Output in C
A file represents a sequence of bytes on the disk where a group of related
data is stored. File is created for permanent storage of data. It is a ready
made structure.

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.

Functions for file handling


There are many functions in C library to open, read, write, search and close
file. A list of file functions are given below:

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

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


Opening File: fopen()
The fopen() function is used to open a file. The syntax of fopen() function is
given below:

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

You 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

Closing File: fclose()


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

int fclose( FILE *fp );


C fprintf() and fscanf()
Writing File : 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, ...])
Example:
1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. fp = fopen("file.txt", "w");//opening file
5. fprintf(fp, "Hello file by fprintf...\n");//writing data into file
6. fclose(fp);//closing file
7. }

Reading File : fscanf() function


The fscanf() function is used to read set of characters from file. It reads a
word from the file and returns EOF at the end of file.
Syntax:
1. int fscanf(FILE *stream, const char *format [, argument, ...])
Example:
1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. char buff[255];//creating char array to store data of file
5. fp = fopen("file.txt", "r");
6. while(fscanf(fp, "%s", buff)!=EOF){
7. printf("%s ", buff );
8. }
9. fclose(fp);
10. }
Output:
Hello file by fprintf...

C fputc() and fgetc()


Writing File : fputc() function
The fputc() function is used to write a single character into file. It outputs a
character to a stream.

Syntax:

1. int fputc(int c, FILE *stream)

Example:

1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. fp = fopen("file1.txt", "w");//opening file
5. fputc('a',fp);//writing single character into file
6. fclose(fp);//closing file
7. }

file1.txt

Reading File : fgetc() function


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

Syntax:
1. int fgetc(FILE *stream)

Example:

1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char c;
6. clrscr();
7. fp=fopen("myfile.txt","r");
8.
9. while((c=fgetc(fp))!=EOF){
10. printf("%c",c);
11. }
12. fclose(fp);
13. getch();
14. }

myfile.txt

this is simple text message

C fputs() and fgets()


The fputs() and fgets() in C programming are used to write and read string
from stream. Let's see examples of writing and reading file using fgets() and
fgets() functions.

Writing File : fputs() function


The fputs() function writes a line of characters into file. It outputs string to a
stream.

Syntax:

1. int fputs(const char *s, FILE *stream)

Example:
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. clrscr();
6.
7. fp=fopen("myfile2.txt","w");
8. fputs("hello c programming",fp);
9.
10. fclose(fp);
11. getch();
12. }

myfile2.txt

hello c programming

Reading File : fgets() function


The fgets() function reads a line of characters from file. It gets string from a
stream.

Syntax:

1. char* fgets(char *s, int n, FILE *stream)

Example:

1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char text[300];
6. clrscr();
7.
8. fp=fopen("myfile2.txt","r");
9. printf("%s",fgets(text,200,fp));
10.
11. fclose(fp);
12. getch();
13. }

Output:
hello c programming

C fseek()
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:

1. int fseek(FILE *stream, long int offset, int whence)

There are 3 constants used in the fseek() function for whence: SEEK_SET,
SEEK_CUR and SEEK_END.

Example:

1. #include <stdio.h>
2. void main(){
3. FILE *fp;
4.
5. fp = fopen("myfile.txt","w+");
6. fputs("This is javatpoint", fp);
7.
8. fseek( fp, 7, SEEK_SET );
9. fputs("sonoo jaiswal", fp);
10. fclose(fp);
11. }

myfile.txt

This is sonoo jaiswal


C rewind() function
The rewind() function sets the file pointer at the beginning of the stream. It
is useful if you have to use stream many times.

Syntax:

1. void rewind(FILE *stream)

Example:
File: file.txt

1. this is a simple text

File: rewind.c

1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char c;
6. clrscr();
7. fp=fopen("file.txt","r");
8.
9. while((c=fgetc(fp))!=EOF){
10. printf("%c",c);
11. }
12.
13. rewind(fp);//moves the file pointer at beginning of the file
14.
15. while((c=fgetc(fp))!=EOF){
16. printf("%c",c);
17. }
18.
19. fclose(fp);
20. getch();
21. }

Output:

this is a simple textthis is a simple text

As you can see, rewind() function moves the file pointer at beginning of the file that is why "this is simple text" is
printed 2 times. If you don't call rewind() function, "this is simple text" will be printed only once.
Introduction to Pointers
Pointers are variables that hold address of another variable of same
data type.
Pointers are one of the most distinct and exciting features of C language.
It provides power and flexibility to the language. Its a powerful tool and
handy to use once its mastered.

Benefit of using pointers

 Pointers are more efficient in handling Array and Structure.


 Pointer allows references to function and thereby helps in passing of
function as arguments to other function.
 It reduces length and the program execution time.
 It allows C to support dynamic memory management.

Concept of Pointer
Whenever a variable is declared, system will allocate a location to that
variable in the memory, to hold value. This location will have its own
address number.
Let us assume that system has allocated memory location 80F for a
variable a.
int a = 10 ;
We can access the value 10 by either using the variable name a or
the address 80F. Since the memory addresses are simply numbers they
can be assigned to some other variable. The variable that holds memory
address are called pointer variables. A pointer variable is therefore
nothing but a variable that contains an address, which is a location of
another variable. Value of pointer variable will be stored in another
memory location.
 Declaring a pointer variable
General syntax of pointer declaration is,
data-type *pointer_name;
Data type of

pointer must be same as the variable, which the pointer is


pointing. void type pointer works with all data types, but isn't used
oftenly.

 Initialization of Pointer variable


Pointer Initialization is the process of assigning address of a variable
to pointer variable. Pointer variable contains address of variable of same
data type. In C language address operator & is used to determine the
address of a variable. The & (immediately preceding a variable name)
returns the address of the variable associated with it.
int a = 10 ;
int *ptr ; //pointer declaration
ptr = &a ; //pointer initialization
or,
int *ptr = &a ; //initialization and declaration together
Pointer variable always points to same type of data.
float a;
int *ptr;
ptr = &a; //ERROR, type mismatch
 Dereferencing of Pointer
Once a pointer has been assigned the address of a variable. To access the
value of variable, pointer is dereferenced, using the indirection
operator *.
int a,*p;
a = 10;
p = &a;

printf("%d",*p); //this will print the value of a.

printf("%d",*&a); //this will also print the value of a.

printf("%u",&a); //this will print the address of a.

printf("%u",p); //this will also print the address of a.

printf("%u",&p); //this will also print the address of p.

Pointer and Arrays


When an array is declared, compiler allocates sufficient amount of
memory to contain all the elements of the array. Base address which
gives location of the first element is also allocated by the compiler.
Suppose we declare an array arr,
int arr[5]={ 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires
two byte, the five element will be stored as follows

Here variable arr will give the base address, which is a constant pointer
pointing to the element, arr[0]. Therefore arr is containing the address
of arr[0] i.e 1000.
arr is equal to &arr[0] // by default
We can declare a pointer of type int to point to the array arr.
int *p;
p = arr;
or p = &arr[0]; //both the statements are equivalent.
Now we can access every element of array arr using p++ to move from
one element to another.
NOTE : You cannot decrement a pointer once incremented. p-- won't
work.

Pointer to Array
As studied above, we can use a pointer to point to an Array, and then we
can use that pointer to access the array. Lets have an example,
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i=0; i<5; i++)
{
printf("%d", *p);
p++;
}
In the above program, the pointer *p will print all the values stored in
the array one by one. We can also use the Base address (a in above case)
to act as pointer and print all the values.

Pointer to Multidimensional Array


A multidimensional array is of form, a[i][j]. Lets see how we can make a
pointer point to such an array. As we know now, name of the array gives
its base address. In a[i][j], a will give the base address of this array,
even a+0+0 will also give the base address, that is the address
of a[0][0] element.
Here is the generalized form for using pointer with multidimensional
arrays.
*(*(ptr + i) + j)
is same as
a[i][j]

Pointer and Character strings


Pointer can also be used to create strings. Pointer variables of char type
are treated as string.
char *str = "Hello";
This creates a string and stores its address in the pointer variable str.
The pointer str now points to the first character of the string "Hello".
Another important thing to note that string created using char pointer
can be assigned a value at runtime.
char *str;
str = "hello"; //thi is Legal
The content of the string can be printed using printf() and puts().
printf("%s", str);
puts(str);
Notice that str is pointer to the string, it is also name of the string.
Therefore we do not need to use indirection operator *.
Array of Pointers
We can also have array of pointers. Pointers are very helpful in handling
character array with rows of varying length.
char *name[3]={
"Adam",
"chris",
"Deniel"
};
//Now see same array without using pointer
char name[3][20]= {
"Adam",
"chris",
"Deniel"
};
In the second approach memory wastage is more, hence it is prefered to
use pointer in such cases.

Pointer Arithmetic
Pointer arithmetic is very important to understand, if you want to have
complete knowledge of pointer. In this topic we will study how the
memory addresses change when you increment a pointer.

16 bit Machine ( Turbo C )


In a 16 bit machine, size of all types of pointer, be it int*, float*, char*
or double* is always 2 bytes. But when we perform any arithmetic
function like increment on a pointer, changes occur as per the size of
their primitive data type.
Size of datatypes on 16-bit Machine :

Type Size(bytes)

int or signed int 2

char 1

long 4

float 4

double 8

long double 10

Examples for Pointer Arithmetic


Now lets take a few examples and understand this more clearly.
int* i;
i++;
In the above case, pointer will be of 2 bytes. And when we increment it,
it will increment by 2 bytes because int is also of 2 bytes.

float* i;
i++;
In this case, size of pointer is still 2 bytes. But now, when we increment
it, it will increment by 4 bytes because float is of 4 bytes.

double* i;
i++;
Similarly, in this case, size of pointer is still 2 bytes. But now, when we
increment it, it will increment by 8 bytes because its data type is double.

32 bit Machine ( Visual Basic C++ )


The concept of pointer arithmetic remains exact same, but the size of
pointer and various datatypes is different in a 32 bit machine. Pointer in
32 bit machine is of 4 bytes.
And, following is a table for Size of datatypes on 32-bit Machine :

Type Size(bytes)

int or signed int 4

char 2

long 8

float 8
double 16

Pointer as Function parameter


Pointer in function parameter list is used to hold address of argument
passed during function call. This is also known as call by reference.
When a function is called by reference any change made to the reference
variable will effect the original variable.

Example: Sorting an array using Pointer


#include <stdio.h>
#include <conio.h>
void sorting(int *x, int y);
void main()
{
int a[5],b,c;
clrscr();
printf("enter 5 nos");
for(b=0; b<5; b++)
{
scanf("%d",&a[b]);
}
sorting(a, 5);
getch();
}

void sorting(int *x, int y)


{
inti,j,temp;
for(i=1; i<=y-1; i++)
{
for(j=0; j*(x+j+1))
{
temp=*(x+j);
*(x+j)=*(x+j+1);
*(x+j+1)=temp;
}
}
}
for(i=0; i<5; i++)
{
printf("\t%d",*(x+i));
}
}
Function returning Pointer
A function can also return a pointer to the calling function. In this case
you must be careful, because local variables of function doesn't live
outside the function, hence if you return a pointer connected to a local
variable, that pointer be will pointing to nothing when function ends.
#include <stdio.h>
#include <conio.h>
int* larger(int*, int*);
void main()
{
int a=15;
int b=92;
int *p;
p=larger(&a, &b);
printf("%d is larger",*p);
}

int* larger(int *x, int *y)


{
if(*x > *y)
return x;
else
return y;
}
Safe ways to return a valid Pointer.

1. Either use argument with functions. Because argument passed to the


functions are declared inside the calling function, hence they will live
outside the function called.

2. Or, use static local variables inside the function and return it. As
static variables have a lifetime until main() exits, they will be
available througout the program.

Pointer to functions
It is possible to declare a pointer pointing to a function which can then
be used as an argument in another function. A pointer to a function is
declared as follows,
type (*pointer-name)(parameter);

Example :
int (*sum)(); //legal declaraction of pointer to function
int *sum(); //This is not a declaraction of pointer to function
A function pointer can point to a specific function when it is assigned
the name of the function.
int sum(int, int);
int (*s)(int, int);
s = sum;
s is a pointer to a function sum. Now sum can be called using function
pointer s with the list of parameter.
s (10, 20);

Example of Pointer to Function


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

int sum(int x, int y)


{
returnx+y;
}

int main( )
{
int (*fp)(int, int);
fp = sum;
int s = fp(10, 15);
printf("Sum is %d",s);
getch();
return 0;
}
Output : 25
C Programming Structure

Structure is a collection of variables of different types under a single


name.

For example: You want to store some information about a person:


his/her name, citizenship number and salary. You can easily create
different variables :name, citNo, salary to store these information
separately.

However, in the future, you would want to store information about


multiple persons. Now, you'd need to create different variables for each
information per person: name1, citNo1, salary1, name2, citNo2, salary2

You can easily visualize how big and messy the code would look. Also,
since no relation between the variables (information) would exist, it's
going to be a daunting task.

A better approach will be to have a collection of all related information


under a single name Person, and use it for every person. Now, the code
looks much cleaner, readable and efficient as well.

This collection of all related information under a single name Person is a


structure.

Structure Definition in C
Keyword struct is used for creating a structure.
 Syntax of structure
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeber3;
};

Note: Don't forget the semicolon }; in the ending line.

We can create the structure for a person as mentioned above as:

struct person
{
char name[50];
int citNo;
float salary;
};
This declaration above creates the derived data type struct person.

 Structure variable declaration


When a structure is defined, it creates a user-defined type but, no storage
or memory is allocated.

For the above structure of a person, variable can be declared as:


struct person
{
char name[50];
intcitNo;
float salary;
};

int main()
{
struct person person1, person2, person3[20];
return 0;
}
Another way of creating a structure variable is:

struct person
{
char name[50];
intcitNo;
float salary;
} person1, person2, person3[20];

In both cases, two variables person1, person2 and an array person3


having 20 elements of type struct person are created.

 Accessing members of a structure


There are two types of operators used for accessing members of a
structure.

Member operator(.)
Structure pointer operator(->) (is discussed in structure and pointers )
Any member of a structure can be accessed as:
structure_variable_name.member_name
Suppose, we want to assign values for variable person1. Then, it can be
done as:
Strcpy(person1.name,”Yash”);
person1.citNo = 123;
person1.salary = 20000.500;
We can also use scanf to give the values through keyboard.
Scanf(“%s %d %f “,person1.name,&person1.citNo,&person1.salary);
Now to access these values we can use
Person1.name, person1.citNo,person1.salary.
Example of structure
Write a C program to add two distances entered by user. Measurement
of distance should be in inch and feet. (Note: 12 inches = 1 foot)

#include <stdio.h>
struct Distance
{
int feet;
float inch;
} dist1, dist2, sum;

int main()
{
printf("1st distance\n");

// Input of feet for structure variable dist1


printf("Enter feet: ");
scanf("%d", &dist1.feet);
// Input of inch for structure variable dist1
printf("Enter inch: ");
scanf("%f", &dist1.inch);

printf("2nd distance\n");

// Input of feet for structure variable dist2


printf("Enter feet: ");
scanf("%d", &dist2.feet);

// Input of feet for structure variable dist2


printf("Enter inch: ");
scanf("%f", &dist2.inch);

sum.feet = dist1.feet + dist2.feet;


sum.inch = dist1.inch + dist2.inch;

if (sum.inch> 12)
{
//If inch is greater than 12, changing it to feet.
++sum.feet;
sum.inch = sum.inch - 12;
}

// printing sum of distance dist1 and dist2


printf("Sum of distances = %d\'-%.1f\"", sum.feet, sum.inch);
return 0;
}
Output
1st distance
Enter feet: 12
Enter inch: 7.9
2nd distance
Enter feet: 2
Enter inch: 9.8
Sum of distances = 15'-5.7"
Keyword typedef while using structure
Writing structstructure_namevariable_name; to declare a structure
variable isn't intuitive as to what it signifies, and takes some
considerable amount of development time.

So, developers generally use typedef to name the structure as a whole.


For example:

typedefstruct complex
{
intimag;
float real;
} comp;

int main()
{
comp comp1, comp2;
}
Here, typedef keyword is used in creating a type comp (which is of type
as struct complex).
00Then, two structure variables comp1 and comp2 are created by this
comp type.

 Structures within structures(Nested structure)


Structures can be nested within other structures in C programming.

struct complex
{
intimag_value;
floatreal_value;
};

struct number
{
struct complex comp;
int real;
} num1, num2;
Suppose, you want to access imag_value for num2 structure variable
then, following structure member is used.

num2.comp.imag_value
 C Programming Structure and Pointer
Structures can be created and accessed using pointers. A pointer variable
of a structure can be created as below:
struct name {
member1;
member2;
.
.
};

int main()
{
struct name *ptr;
}
Here, the pointer variable of type struct name is created.For ex.
#include <stdio.h>
typedefstruct person
{
int age;
float weight;
};

int main()
{
struct person *personPtr, person1;
personPtr = &person1; // Referencing pointer to memory address of person1
printf("Enter age: ");
scanf("%d",&(*personPtr).age);

printf("Enter weight: ");


scanf("%f",&(*personPtr).weight);

printf("Displaying: ");
printf("%d%f",(*personPtr).age,(*personPtr).weight);

return 0;
}
In this example, the pointer variable of type struct person is referenced
to the address of person1. Then, only the structure member through
pointer can canaccessed.
Using -> operator to access structure pointer member
Structure pointer member can also be accessed using -> operator.
(*personPtr).age is same as personPtr->age
(*personPtr).weight is same as personPtr->weight

 How to pass structure to a function in C


programming?

In C, structure can be passed to functions by two methods:

1. Passing by value (passing actual value as argument)


2. Passing by reference (passing address of an argument)
 Passing structure by value
A structure variable can be passed to the function as an argument as a
normal variable.
If structure is passed by value, changes made to the structure variable
inside the function definition does not reflect in the originally passed
structure variable.

C program to create a structure student, containing name and roll and


display the information.

#include <stdio.h>
struct student
{
char name[50];
int roll;
};

void display(struct student stud);


// function prototype should be below to the structure declaration
otherwise compiler shows error

int main()
{
struct student stud;
printf("Enter student's name: ");
scanf("%s", &stud.name);
printf("Enter roll number:");
scanf("%d", &stud.roll);
display(stud); // passing structure variable stud as argument
return 0;
}
void display(struct student stu){
printf("Output\nName: %s",stu.name);
printf("\nRoll: %d",stu.roll);
}

Output

Enter student's name: Kevin Amla


Enter roll number: 149
Output
Name: Kevin Amla
Roll: 149
 Passing structure by reference
The memory address of a structure variable is passed to function while
passing it by reference.

If structure is passed by reference, changes made to the structure


variable inside function definition reflects in the originally passed
structure variable.

C program to add two distances (feet-inch system) and display the result
without the return statement.

#include <stdio.h>
struct distance
{
int feet;
float inch;
};
void add(struct distance d1,struct distance d2, struct distance *d3);

int main()
{
struct distance dist1, dist2, dist3;

printf("First distance\n");
printf("Enter feet: ");
scanf("%d", &dist1.feet);
printf("Enter inch: ");
scanf("%f", &dist1.inch);

printf("Second distance\n");
printf("Enter feet: ");
scanf("%d", &dist2.feet);
printf("Enter inch: ");
scanf("%f", &dist2.inch);

add(dist1, dist2, &dist3);

//passing structure variables dist1 and dist2 by value whereas passing


structure variable dist3 by reference
printf("\nSum of distances = %d\'-%.1f\"", dist3.feet, dist3.inch);

return 0;
}
void add(struct distance d1,struct distance d2, struct distance *d3)
{
//Adding distances d1 and d2 and storing it in d3
d3->feet = d1.feet + d2.feet;
d3->inch = d1.inch + d2.inch;

if (d3->inch >= 12) { /* if inch is greater or equal to 12, converting it


to feet. */
d3->inch -= 12;
++d3->feet;
}
}
Output

First distance
Enter feet: 12
Enter inch: 6.8
Second distance
Enter feet: 5
Enter inch: 7.5

Sum of distances = 18'-2.3"


In this program, structure variables dist1 and dist2 are passed by value to
the add function (because value of dist1 and dist2 does not need to be
displayed in main function).

But, dist3 is passed by reference ,i.e, address of dist3 (&dist3) is passed


as an argument.

Due to this, the structure pointer variable d3 inside the add function
points to the address of dist3 from the calling main function. So, any
change made to the d3 variable is seen in dist3 variable in main function.
As a result, the correct sum is displayed in the output.

Example of Structures in C Programming

C Programming Examples and Source Code

Store Information(name, roll and marks) of a Student Using Structure

Add Two Distances (in inch-feet) System Using Structures

Add Two Complex Numbers by Passing Structure to a Function

Calculate Difference Between Two Time Period

Store Information of 10 Students Using Structure

Store Information Using Structures for n Elements Dynamically

C Program to Store Information(name, roll and marks) of a Student Using


Structure
1)This program stores the information (name, roll and marks) of a
student and displays it on the screen using structures.
Example: Store Information and Display it Using Structure
#include <stdio.h>
struct student
{
char name[50];
int roll;
float marks;
} s;

int main()
{
printf("Enter information:\n");

printf("Enter name: ");


scanf("%s", s.name);

printf("Enter roll number: ");


scanf("%d", &s.roll);

printf("Enter marks: ");


scanf("%f", &s.marks);

printf("Displaying Information:\n");

printf("Name: ");
puts(s.name);

printf("Roll number: %d\n",s.roll);


printf("Marks: %.1f\n", s.marks);

return0;
}

Output

Enter information:

Enter name: Jack

Enter roll number: 23

Enter marks: 34.5

Displaying Information:

Name: Jack

Roll number: 23

Marks: 34.5

2)C Program to Add Two Distances (in inch-feet) System Using


Structures

Example: Program to add two distances in inch-feet system

#include<stdio.h>
structDistance
{
int feet;
float inch;
} d1, d2, sumOfDistances;

int main()
{
printf("Enter information for 1st distance\n");
printf("Enter feet: ");
scanf("%d", &d1.feet);
printf("Enter inch: ");
scanf("%f", &d1.inch);

printf("\nEnter information for 2nd distance\n");


printf("Enter feet: ");
scanf("%d", &d2.feet);
printf("Enter inch: ");
scanf("%f", &d2.inch);

sumOfDistances.feet = d1.feet+d2.feet;
sumOfDistances.inch = d1.inch+d2.inch;
// If inch is greater than 12, changing it to feet.

if (sumOfDistances.inch>12.0)
{
sumOfDistances.inch = sumOfDistances.inch-12.0;
++sumOfDistances.feet;
}

printf("\nSum of distances = %d\'-%.1f\"",sumOfDistances.feet,


sumOfDistances.inch);
return0;
}

Output

Enter information for 1st distance

Enter feet: 23

Enter inch: 8.6

Enter information for 2nd distance

Enter feet: 34

Enter inch: 2.4


Sum of distances = 57'-11.0"

3)C Program to Add Two Complex Numbers by Passing Structure to a


Function

Example: Add Two Complex Numbers


#include<stdio.h>
typedefstruct complex
{
float real;
floatimag;
} complex;
complex add(complex n1,complex n2);

int main()
{
complex n1, n2, temp;

printf("For 1st complex number \n");


printf("Enter real and imaginary part respectively:\n");
scanf("%f %f", &n1.real, &n1.imag);

printf("\nFor 2nd complex number \n");


printf("Enter real and imaginary part respectively:\n");
scanf("%f %f", &n2.real, &n2.imag);
temp = add(n1, n2);
printf("Sum = %.1f + %.1fi", temp.real, temp.imag);

return0;
}

complex add(complex n1, complex n2)


{
complex temp;

temp.real = n1.real + n2.real;


temp.imag = n1.imag + n2.imag;

return(temp);
}

Output

For 1st complex number

Enter real and imaginary part respectively: 2.3

4.5
For 2nd complex number

Enter real and imaginary part respectively: 3.4

Sum = 5.7 + 9.5i

In this program, structures n1 and n2 are passed as an argument of


function add().

This function computes the sum and returns the structure


variable temp to the main() function

4)C Program to Calculate Difference Between Two Time Periods

Example: Calculate Difference Between Two Time Periods


#include<stdio.h>
struct TIME
{
int seconds;
int minutes;
int hours;
};
voiddifferenceBetweenTimePeriod(struct TIME t1, struct TIME t2,
struct TIME *diff);

int main()
{
struct TIME startTime, stopTime, diff;

printf("Enter start time: \n");


printf("Enter hours, minutes and seconds respectively: ");
scanf("%d %d %d", &startTime.hours, &startTime.minutes,
&startTime.seconds);

printf("Enter stop time: \n");


printf("Enter hours, minutes and seconds respectively: ");
scanf("%d %d %d", &stopTime.hours, &stopTime.minutes,
&stopTime.seconds);

// Calculate the difference between the start and stop time period.
differenceBetweenTimePeriod(startTime, stopTime, &diff);

printf("\nTIME DIFFERENCE: %d:%d:%d - ", startTime.hours,


startTime.minutes, startTime.seconds);
printf("%d:%d:%d ", stopTime.hours, stopTime.minutes,
stopTime.seconds);
printf("= %d:%d:%d\n", diff.hours, diff.minutes, diff.seconds);

return0;
}
voiddifferenceBetweenTimePeriod(struct TIME start, struct TIME stop,
struct TIME *diff)
{
if(stop.seconds>start.seconds){
--start.minutes;
start.seconds += 60;
}

diff->seconds = start.seconds - stop.seconds;


if(stop.minutes>start.minutes){
--start.hours;
start.minutes += 60;
}

diff->minutes = start.minutes - stop.minutes;


diff->hours = start.hours - stop.hours;
}

Output

Enter start time:

Enter hours, minutes and seconds respectively: 12

34

55
Enter stop time:

Enter hours, minutes and seconds respectively:8

12

15

TIME DIFFERENCE: 12:34:55 - 8:12:15 = 4:22:40

In this program, user is asked to enter two time periods and these two
periods are stored in structure
variables startTime and stopTime respectively.

Then, the function differenceBetweenTimePeriod calculates the


difference between the time periods and the result is displayed
in main() function without returning it (Using call by reference
technique).

5)C Program to Store Information of Students Using Structure

Example: Store Information in Structure and Display it


#include<stdio.h>
struct student
{
char name[50];
int roll;
float marks;
} s[10];

int main()
{
int i;

printf("Enter information of students:\n");

// storing information
for(i=0; i<10; ++i)
{
s[i].roll = i+1;

printf("\nFor roll number%d,\n",s[i].roll);

printf("Enter name: ");


scanf("%s",s[i].name);

printf("Enter marks: ");


scanf("%f",&s[i].marks);

printf("\n");
}

printf("Displaying Information:\n\n");
// displaying information
for(i=0; i<10; ++i)
{
printf("\nRoll number: %d\n",i+1);
printf("Name: ");
puts(s[i].name);
printf("Marks: %.1f",s[i].marks);
printf("\n");
}
return0;
}

Output

Enter information of students:

For roll number1,

Enter name: Tom

Enter marks: 98

For roll number2,


Enter name: Jerry

Enter marks: 89

Displaying Information:

Roll number: 1

Name: Tom

Marks: 98

1)Write a program to define a structure which will store information


about a person such as name, DOB, qualification. Declare an array for
storing information about 5 persons and accept the data from the user.

2) Write a program to define a structure to store information about a


student having rollno, name, marks in three subjects and percentage.
Accept all the data except percentage and then update the structure
variable to contain the percentage.

You might also like