C Programming 2019 Soft Notes
C Programming 2019 Soft Notes
Introduction
The C language is the most frequently used language for writing system software
such as operating systems, programming languages and compilers.
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 high-level language
‘C’ language is much closer to the assembly language then the majority of the
other high-level languages.
We can write a C program in an operating system and this program can be carried
out in another Operating System.
The C language has a standard programming format. Each program must have the
main function and other attributes.
The C language is entirely integrated with the functions which are stored in the
library.
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.
?
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
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:
Interpreter:
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
[Global Declaration]
main() { <Local Declarations>; <Statements>; }
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
Following main function, we used the curly braces which are the parts to start
and of closing of the program
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.
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
conio.h - The conio.h has console (i.e. monitor) input output functions
dos.h - It defines many functions that are related to date and delay which is
used to set interval
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
#include<stdio.h>
#include<conio.h>
void main()
clrscr();
printf(“Hello World”);
getch();
#include<stdio.h>
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
Program No. 2
#include<conio.h>
#include<stdio.h>
void main()
clrscr();
age = 23;
getch();
}
Program No. 3
#include<stdio.h>
#include<conio.h>
void main()
float avg;
char ch;
clrscr();
avg = 3.78;
ch = 'A';
getch();
Program No. 4
#include<conio.h>
#include<stdio.h>
void main()
{
int age;
clrscr();
getch()
Program No. 5
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();
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.
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();
}
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.
The variable names are case sensitive. That means, small `a’ differs from capital
‘A’
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.
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
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
Character constants
The two inverted commas should move towards the left. For your better
understanding, look at the example
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.
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
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.
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 following table shows all the arithmetic operators supported by the C
language. Assume variable A holds 10 and variable B holds 20, then:
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.
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.
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
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 (\)
Bitwise Operators
Bitwise operator works on bits and performs bit-by-bit operation. The truth tables
for &, |, and ^ is as follows −
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
~ (~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
Using ?: reduce the number of line codes and improve the performance of
application.
Syntax
Syntax
#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
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>);
In this syntax, both functions are taken as two arguments, format string, and list of
variables.
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
/* 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.
() Function call
[] Array subscripting
1
& Address-of
sizeof Size-of[note 1]
12 || Logical OR
= Simple assignment
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:
#include<stdio.h>
int main()
{
int x = 10; // integer x
char y = 'a'; // character c
Output:
x = 107, z = 108.000000
(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;
return 0;
Run on IDE
Output:
sum = 2
Program No. 16
Input Two Numbers and interchange their values (Swapping using third variable) /*
#include<conio.h> #include<stdio.h>
temp = a; a = b; b = temp;
getch(); }
Program No. 17
Program No. 17: Input a 3 Digit Integer Number and display sum of all the 3
digits */
#include<conio.h> #include<stdio.h>
d3 = no%10; no = no/10;
d2 = no%10; no = no/10;
d1 = no%10;
sum = d1 + d2 + d3;
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>
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>
getch();
Program No. 23
Input a 4 digit no, write a program that displays the number as follows
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
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
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.
if(Condition/Expression)
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();
if(a>b)
if(b>a)
if(a==b)
getch(); }
Program No. 28
WAP to input any number from the user and display whether the number is positive
or negative
void main()
getch();
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
int no;
scanf (“%d”,&no);
if (no%2 == 0)
else
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.
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
#include<conio.h>
#include<stdio.h>
void main()
{ int no;
clrscr();
scanf("%d", &no);
if(no>0)
}
else if(no==0)
else
} getch();
Program No. 34
#include<conio.h>
#include<stdio.h>
void main()
float avg;
clrscr();
if(avg>=75)
printf("\n\t Distinction");
else if(avg>=60)
else if(avg>=45)
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();
scanf("%c", &alpha);
if(alpha == 'a')
else
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).
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();
if(a>b)
if(a>c)
else
else {
if(b>c)
else
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.
#include<conio.h>
#include<stdio.h>
void main()
int age;
clrscr();
gender = getche();
scanf("%d", &age);
if(gender == 'm')
if(age>=35)
{
else
if(age>=25)
else
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
#include<conio.h>
#include<stdio.h>
void main()
int a, b, c;
clrscr();
if(a>b)
}
else
else
else
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.
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
#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.
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
#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
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; */
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; }
Program No. 68
#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
Program No. 70
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
#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
# 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
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.
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
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.
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.
1. CharacterInput/output functions
2.StringInput/output functions
CharacterVariable = getchar();
Where character variable refers to some previously declared
character variable.
putchar(character variable);
Where character variable refers to some previously declared
character variable.
#include <stdio.h>
int main()
charch;
ch = getchar();
putchar(ch);
return 0;
apple
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.
#include <conio.h>
#include <stdio.h>
int main()
charch;
ch = getch();
return 0;
If we run this program and press any key, let's say "x", then the
output will be as shown below:
Please note here that the character "x" was not echoed when you
entered it.
puts(character array);
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.
#include <stdio.h>
int main()
{
char c[25];
printf("Enter a string : ");
gets(c);
printf("\n%s is awesome ",c);
return 0;
}
Output
Note:
puts() in C
#include <stdio.h>
int main()
{
char c[25];
printf("Enter your Name : ");
gets(c);
puts(c);
return 0;
}
Output
pooja
Note:
Using arrays
char s[5];
Using pointers
char *p;
Initialization of strings
For convenience and ease, both initialization and declaration are done in the
same step.
Using arrays
OR,
OR,
OR,
The given string is initialized and stored in the form of arrays as above.
Using pointers
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).
char c[20];
scanf("%s", c);
#include<stdio.h>
int main()
char name[20];
scanf("%s", name);
return0;
Output
An approach to reading a full line of text is to read and store each character
one by one.
#include<stdio.h>
int main()
char name[30],ch;
int i =0;
ch=getchar();
name[i]=ch;
i++;
}
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.
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("Name: ");
return0;
Output
Strings are just char arrays. So, they can be passed to a function in a similar
manner as arrays.
voiddisplayString(charstr[]);
int main()
charstr[50];
gets(str);
return0;
voiddisplayString(charstr[]){
puts(str);
#include<stdio.h>
#include<string.h>
int main()
{
/* String Declaration*/
char nickname[20];
/*Displaying String*/
printf("%s",nickname);
return0;
}
Note: %s is used for strings I/O
#include<stdio.h>
#include<string.h>
int main()
{
/* String Declaration*/
char nickname[20];
puts(nickname);
return0;
}
String functions
Example:
#include<stdio.h>
#include<string.h>
int main()
{
char str1[20] = "BeginnersBook";
printf("Length of string str1: %d", strlen(str1));
return0;
}
Output:
#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.
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.
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:
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:
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:
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:
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:
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.
#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’.
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)
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.
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;
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
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();
... .. ...
int main()
{
int number, result;
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
int main()
{
intnum,f;
printf("Enter a number: ");
scanf("%d",&num);
f=factorial(num);
printf("Factorial of %d = %d",num,f);
return 0;
}
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;
}
#include<stdio.h>
int main()
{
intbase,powerRaised, result;
result= power(base,powerRaised);
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.
Output:
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:
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.
ptr=realloc(ptr, new-size)
#include <stdio.h>
#include <stdlib.h>
int main()
{
intnum, i, *ptr, sum = 0;
#include <stdio.h>
#include <stdlib.h>
int main()
{
intnum, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
Syntax of realloc()
ptr = realloc(ptr, newsize);
Here, ptr is reallocated with size of newsize.
int main()
{
int *ptr, i , n1, n2;
printf("Enter size of array: ");
scanf("%d", &n1);
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.
You can use one of the following modes in the fopen() function.
Mode Description
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. }
Syntax:
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
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
Syntax:
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
Syntax:
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:
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
Syntax:
Example:
File: file.txt
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:
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.
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
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 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.
Type Size(bytes)
char 1
long 4
float 4
double 8
long double 10
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.
Type Size(bytes)
char 2
long 8
float 8
double 16
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);
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
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.
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;
};
struct person
{
char name[50];
int citNo;
float salary;
};
This declaration above creates the derived data type struct person.
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];
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");
printf("2nd distance\n");
if (sum.inch> 12)
{
//If inch is greater than 12, changing it to feet.
++sum.feet;
sum.inch = sum.inch - 12;
}
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.
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("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
#include <stdio.h>
struct student
{
char name[50];
int roll;
};
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
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);
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;
First distance
Enter feet: 12
Enter inch: 6.8
Second distance
Enter feet: 5
Enter inch: 7.5
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.
int main()
{
printf("Enter information:\n");
printf("Displaying Information:\n");
printf("Name: ");
puts(s.name);
return0;
}
Output
Enter information:
Displaying Information:
Name: Jack
Roll number: 23
Marks: 34.5
#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);
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;
}
Output
Enter feet: 23
Enter feet: 34
int main()
{
complex n1, n2, temp;
return0;
}
return(temp);
}
Output
4.5
For 2nd complex number
int main()
{
struct TIME startTime, stopTime, diff;
// Calculate the difference between the start and stop time period.
differenceBetweenTimePeriod(startTime, stopTime, &diff);
return0;
}
voiddifferenceBetweenTimePeriod(struct TIME start, struct TIME stop,
struct TIME *diff)
{
if(stop.seconds>start.seconds){
--start.minutes;
start.seconds += 60;
}
Output
34
55
Enter stop time:
12
15
In this program, user is asked to enter two time periods and these two
periods are stored in structure
variables startTime and stopTime respectively.
int main()
{
int i;
// storing information
for(i=0; i<10; ++i)
{
s[i].roll = i+1;
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 marks: 98
Enter marks: 89
Displaying Information:
Roll number: 1
Name: Tom
Marks: 98