0% found this document useful (0 votes)
57 views72 pages

EdisoftIndia C Tutorials

Uploaded by

anujkarn0218
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views72 pages

EdisoftIndia C Tutorials

Uploaded by

anujkarn0218
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

AN INTRODUCTION TO

C LANGUAGE A Key to Success

Designed BY: EduSoftIndia


Prepared BY: Brijesh Kumar Singh

Website: edusoftindia.com
AN INTRODUCTION TO C LANGUAGE

Introduction
C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the
UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in
1972.
In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now
known as the K&R standard.
The UNIX operating system, the C compiler, and essentially all UNIX application programs have been written
in C. C has now become a widely used professional language for various reasons −

• Easy to learn
• Structured language
• It produces efficient programs
• It can handle low-level activities
• It can be compiled on a variety of computer platforms
Facts about C

• C was invented to write an operating system called UNIX.


• C is a successor of B language which was introduced around the early 1970s.
• The language was formalized in 1988 by the American National Standard Institute (ANSI).
• The UNIX OS was totally written in C.
• Today C is the most widely used and popular System Programming Language.
• Most of the state-of-the-art software have been implemented using C.
• Today's most popular Linux OS and RDBMS MySQL have been written in C.
Why use C?
C was initially used for system development work, particularly the programs that make-up the operating
system. C was adopted as a system development language because it produces code that runs nearly as fast as
the code written in assembly language. Some examples of the use of C might be −

• Operating Systems
• Language Compilers
• Assemblers
• Text Editors
• Print Spoolers
• Network Drivers
• Modern Programs
• Databases
• Language Interpreters
• Utilities
C Programs
A C program can vary from 3 lines to millions of lines and it should be written into one or more text files with
extension ".c"; for example, hello.c. You can use "vi", "vim" or any other text editor to write your C program
into a file.
Local Environment Setup
If you want to set up your environment for C programming language, you need the following two software
tools available on your computer, (a) Text Editor and (b) The C Compiler.
Text Editor
This will be used to type your program. Examples of few a editors include Windows Notepad, OS Edit
command, Brief, Epsilon, EMACS, and vim or vi.
The name and version of text editors can vary on different operating systems. For example, Notepad will be
used on Windows, and vim or vi can be used on windows as well as on Linux or UNIX.
The files you create with your editor are called the source files and they contain the program source codes. The
source files for C programs are typically named with the extension ".c".
Before starting your programming, make sure you have one text editor in place and you have enough
experience to write a computer program, save it in a file, compile it and finally execute it.
The C Compiler

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 1


AN INTRODUCTION TO C LANGUAGE

The source code written in source file is the human readable source for your program. It needs to be
"compiled", into machine language so that your CPU can actually execute the program as per the instructions
given.
The compiler compiles the source codes into final executable programs. The most frequently used and free
available compiler is the GNU C/C++ compiler, otherwise you can have compilers either from HP or Solaris if
you have the respective operating systems.
The following section explains how to install GNU C/C++ compiler on various OS. We keep mentioning
C/C++ together because GNU gcc compiler works for both C and C++ programming languages.
Installation on UNIX/Linux
If you are using Linux or UNIX, then check whether GCC is installed on your system by entering the
following command from the command line −
$ gcc -v
If you have GNU compiler installed on your machine, then it should print a message as follows −
Using built-in specs.
Target: i386-redhat-linux
Configured with: ../configure --prefix=/usr .......
Thread model: posix
gcc version 4.1.2 20080704 (Red Hat 4.1.2-46)
If GCC is not installed, then you will have to install it yourself using the detailed instructions available
at http://gcc.gnu.org/install/
This tutorial has been written based on Linux and all the given examples have been compiled on the Cent OS
flavor of the Linux system.
Installation on Mac OS
If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode development environment from
Apple's web site and follow the simple installation instructions. Once you have Xcode setup, you will be able
to use GNU compiler for C/C++.
Xcode is currently available at developer.apple.com/technologies/tools/.
Installation on Windows
To install GCC on Windows, you need to install MinGW. To install MinGW, go to the MinGW
homepage, www.mingw.org, and follow the link to the MinGW download page. Download the latest version
of the MinGW installation program, which should be named MinGW-<version>.exe.
While installing Min GW, at a minimum, you must install gcc-core, gcc-g++, binutils, and the MinGW
runtime, but you may wish to install more.
Add the bin subdirectory of your MinGW installation to your PATH environment variable, so that you can
specify these tools on the command line by their simple names.
After the installation is complete, you will be able to run gcc, g++, ar, ranlib, dlltool, and several other GNU
tools from the Windows command line.
Hello World Example
A C program basically consists of the following parts −

• Preprocessor Commands
• Functions
• Variables
• Statements & Expressions
• Comments
Let us look at a simple code that would print the words "Hello World" −
#include <stdio.h>
int main()
{
/* my first program in C */
printf("Hello, World! \n");
return 0;
}
Let us take a look at the various parts of the above program −
• The first line of the program #include <stdio.h> is a preprocessor command, which tells a C compiler
to include stdio.h file before going to actual compilation.

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 2


AN INTRODUCTION TO C LANGUAGE

• The next line int main() is the main function where the program execution begins.
• The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments in
the program. So such lines are called comments in the program.
• The next line printf(...) is another function available in C which causes the message "Hello, World!" to
be displayed on the screen.
• The next line return 0; terminates the main() function and returns the value 0.

Compile and Execute C Program


Let us see how to save the source code in a file, and how to compile and run it. Following are the simple steps

• Open a text editor and add the above-mentioned code.
• Save the file as hello.c
• Open a command prompt and go to the directory where you have saved the file.
• Type gcc hello.c and press enter to compile your code.
• If there are no errors in your code, the command prompt will take you to the next line and would
generate a.out executable file.
• Now, type a.out to execute your program.
• You will see the output "Hello World" printed on the screen.
$ gcc hello.c
$ ./a.out
Hello, World!

Identifiers
A C identifier is a name used to identify a variable, function, or any other user-defined item. An identifier
starts with a letter A to Z, a to z, or an underscore '_' followed by zero or more letters, underscores, and digits
(0 to 9).
C does not allow punctuation characters such as @, $, and % within identifiers. C is a case-
sensitive programming language. Thus, Manpower and manpowerare two different identifiers in C. Here are
some examples of acceptable identifiers −
mohd zara abc move_name a_123
myname50 _temp j a23b9 retVal

Keywords
The following list shows the reserved words in C. These reserved words may not be used as constants or
variables or any other identifier names.
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 _Packed
double

Data Types
Data types in c refer to an extensive system used for declaring variables or functions of different types. The
type of a variable determines how much space it occupies in storage and how the bit pattern stored is
interpreted.
The types in C can be classified as follows −
S.N. Types & Description
1 Basic Types
They are arithmetic types and are further classified into:
(a) integer types
(b) floating-point types.

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 3


AN INTRODUCTION TO C LANGUAGE

• (c) Character types


2 Enumerated types
They are again arithmetic types and they are used to define variables that can only assign certain
discrete integer values throughout the program.
3 The type void
The type specifier void indicates that no value is available.
4 Derived types
They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e) Function
types.
The array types and structure types are referred collectively as the aggregate types. The type of a function
specifies the type of the function's return value. We will see the basic types in the following section, where as
other types will be covered in the upcoming chapters.
Integer Types
The following table provides the details of standard integer types with their storage sizes and value ranges −
Type Storage size Value range
char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
To get the exact size of a type or a variable on a particular platform, you can use the sizeof operator. The
expressions sizeof(type) yields the storage size of the object or type in bytes. Given below is an example to get
the size of int type on any machine −
#include <stdio.h>
#include <limits.h>
int main()
{
printf("Storage size for int : %d \n", sizeof(int));
return 0;
}
When you compile and execute the above program, it produces the following result on Linux −
Storage size for int : 4
Floating-Point Types
The following table provide the details of standard floating-point types with storage sizes and value ranges and
their precision −
Type Storage size Value range Precision
float 4 byte 1.2E-38 to 3.4E+38 6 decimal places
double 8 byte 2.3E-308 to 1.7E+308 15 decimal places
long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places
The header file float.h defines macros that allow you to use these values and other details about the binary
representation of real numbers in your programs. The following example prints the storage space taken by a
float type and its range values −
#include <stdio.h>
#include <float.h>

int main() {

printf("Storage size for float : %d \n", sizeof(float));


printf("Minimum float positive value: %E\n", FLT_MIN );
printf("Maximum float positive value: %E\n", FLT_MAX );
printf("Precision value: %d\n", FLT_DIG );

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 4


AN INTRODUCTION TO C LANGUAGE

return 0;
}
When you compile and execute the above program, it produces the following result on Linux −
Storage size for float : 4
Minimum float positive value: 1.175494E-38
Maximum float positive value: 3.402823E+38
Precision value: 6

The void Type


The void type specifies that no value is available. It is used in three kinds of situations −
S.N. Types & Description
1 Function returns as void
There are various functions in C which do not return any value or you can say they return void. A
function with no return value has the return type as void. For example, void exit (int status);
2 Function arguments as void
There are various functions in C which do not accept any parameter. A function with no parameter
can accept a void. For example, int rand(void);
3 Pointers to void
A pointer of type void * represents the address of an object, but not its type. For example, a memory
allocation function void *malloc( size_t size ); returns a pointer to void which can be casted to any
data type.

Variable
A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C
has a specific type, which determines the size and layout of the variable's memory; the range of values that can
be stored within that memory; and the set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must begin with
either a letter or an underscore. Upper and lowercase letters are distinct because C is case-sensitive. Based on
the basic types explained in the previous chapter, there will be the following basic variable types −
Type Description
char Typically a single octet(one byte). This is an integer type.
int The most natural size of integer for the machine.
float A single-precision floating point value.
double A double-precision floating point value.
void Represents the absence of type.
Variable Definition in C
A variable definition tells the compiler where and how much storage to create for the variable. A variable
definition specifies a data type and contains a list of one or more variables of that type as follows −
type variable_list;
Here, type must be a valid C data type including char, char, int, float, double, bool, or any user-defined object;
and variable_list may consist of one or more identifier names separated by commas. Some valid declarations
are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to create variables
named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal
sign followed by a constant expression as follows −
type variable_name = value;
Some examples are −
extern int d = 3, f = 5; // declaration of d and f.
int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 5


AN INTRODUCTION TO C LANGUAGE

char x = 'x'; // the variable x has the value 'x'.


For definition without an initializer: variables with static storage duration are implicitly initialized with NULL
(all bytes have the value 0); the initial value of all other variables are undefined.
Variable Declaration in C
A variable declaration provides assurance to the compiler that there exists a variable with the given type and
name so that the compiler can proceed for further compilation without requiring the complete detail about the
variable. A variable declaration has its meaning at the time of compilation only, the compiler needs actual
variable declaration at the time of linking the program.
A variable declaration is useful when you are using multiple files and you define your variable in one of the
files which will be available at the time of linking of the program. You will use the keyword extern to declare
a variable at any place. Though you can declare a variable multiple times in your C program, it can be defined
only once in a file, a function, or a block of code.
Example
Try the following example, where variables have been declared at the top, but they have been defined and
initialized inside the main function −
#include <stdio.h>
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main ()
{
/* variable definition: */
int a, b;
int c;
float f;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf("value of c : %d \n", c);
f = 70.0/3.0;
printf("value of f : %f \n", f);
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of c : 30
value of f : 23.333334
The same concept applies on function declaration where you provide a function name at the time of its
declaration and its actual definition can be given anywhere else. For example −
// function declaration
int func();
int main()
{
// function call
int i = func();
}
// function definition
int func()
{
return 0;
}
Lvalues and Rvalues in C
There are two kinds of expressions in C −
• lvalue − Expressions that refer to a memory location are called "lvalue" expressions. An lvalue may
appear as either the left-hand or right-hand side of an assignment.

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 6


AN INTRODUCTION TO C LANGUAGE

•rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is
an expression that cannot have a value assigned to it which means an rvalue may appear on the right-
hand side but not on the left-hand side of an assignment.
Variables are lvalues and so they may appear on the left-hand side of an assignment. Numeric literals are
rvalues and so they may not be assigned and cannot appear on the left-hand side. Take a look at the following
valid and invalid statements −

Constants & Literals


Constants refer to fixed values that the program may not alter during its execution. These fixed values are also
called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a character
constant, or a string literal. There are enumeration constants as well.
Constants are treated just like regular variables except that their values cannot be modified after their
definition.
Integer Literals
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or
0X for hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively.
The suffix can be uppercase or lowercase and can be in any order.
Here are some examples of integer literals −
212 /* Legal */
215u /* Legal */
0xFeeL /* Legal */
078 /* Illegal: 8 is not an octal digit */
032UU /* Illegal: cannot repeat a suffix */
Following are other examples of various types of integer literals −
85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */
Floating-point Literals
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can
represent floating point literals either in decimal form or exponential form.
While representing decimal form, you must include the decimal point, the exponent, or both; and while
representing exponential form, you must include the integer part, the fractional part, or both. The signed
exponent is introduced by e or E.
Here are some examples of floating-point literals −
3.14159 /* Legal */
314159E-5L /* Legal */
510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent */
.e55 /* Illegal: missing integer or fraction */
Character Constants
Character literals are enclosed in single quotes, e.g., 'x' can be stored in a simple variable of char type.
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character
(e.g., '\u02C0').
There are certain characters in C that represent special meaning when preceded by a backslash for example,
newline (\n) or tab (\t).
Here, you have a list of such escape sequence codes −
Following is the example to show a few escape sequence characters −
#include <stdio.h>

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 7


AN INTRODUCTION TO C LANGUAGE

int main()
{
printf("Hello\tWorld\n\n");
return 0;
}
When the above code is compiled and executed, it produces the following result −
Hello World
String Literals
String literals or constants are enclosed in double quotes "". A string contains characters that are similar to
character literals: plain characters, escape sequences, and universal characters.
You can break a long line into multiple lines using string literals and separating them using white spaces.
Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"
"hello, \
dear"
"hello, " "d" "ear"
Defining Constants
There are two simple ways in C to define constants −
• Using #define preprocessor.
• Using const keyword.
The #define Preprocessor
Given below is the form to use #define preprocessor to define a constant −
#define identifier value
The following example explains it in detail −
#include <stdio.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main()
{
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of area : 50
The const Keyword
You can use const prefix to declare constants with a specific type as follows −
const type variable = value;
The following example explains it in detail −
#include <stdio.h>
int main()
{
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
When the above code is compiled and executed, it produces the following result −

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 8


AN INTRODUCTION TO C LANGUAGE

value of area : 50

C Programming Operators
Operators are the symbol which operates on value or a variable. For example: + is a operator to
perform addition.
C programming language has wide range of operators to perform various operations. For better
understanding of operators, these operators can be classified as:
Operators in C programming
Arithmetic Operators
Increment and Decrement Operators
Assignment Operators
Relational Operators
Logical Operators
Conditional Operators
Bitwise Operators
Special Operators
Arithmetic Operators
Operator Meaning of Operator
+ addition or unary plus
- subtraction or unary minus
* multiplication
/ division
% remainder after division( modulo division)
Example of working of arithmetic operators
/* Program to demonstrate the working of arithmetic operators in C. */
#include <stdio.h>
int main(){
int a=9,b=4,c;
c=a+b;
printf("a+b=%d\n",c);
c=a-b;
printf("a-b=%d\n",c);
c=a*b;
printf("a*b=%d\n",c);
c=a/b;
printf("a/b=%d\n",c);
c=a%b;
printf("Remainder when a divided by b=%d\n",c);
return 0;
}

a+b=13

a-b=5

a*b=36

a/b=2

Remainder when a divided by b=1


INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 9
AN INTRODUCTION TO C LANGUAGE

Increment and decrement operators


In C, ++ and -- are called increment and decrement operators respectively. Both of these operators
are unary operators, i.e, used on single operand. ++ adds 1 to operand and -- subtracts 1 to operand
respectively. For example:

Let a=5 and b=10

a++; //a becomes 6

a--; //a becomes 5

++a; //a becomes 6

--a; //a becomes 5


Difference between ++ and -- operator as postfix and prefix
When i++ is used as prefix(like: ++var), ++var will increment the value of var and then return it but,
if ++ is used as postfix(like: var++), operator will return the value of operand first and then only
increment it. This can be demonstrated by an example:
#include <stdio.h>
int main()
{
int c=2,d=2;
printf("%d\n",c++); //this statement displays 2 then, only c incremented by 1 to 3.
printf("%d",++c); //this statement increments 1 to c then, only c is displayed.
return 0;
}
Assignment Operators
The most common assignment operator is =. This operator assigns the value in right side to the left
side. For example:

var=5 //5 is assigned to var

a=c; //value of c is assigned to a

5=c; // Error! 5 is a constant.


Operator Example Same as
= a=b a=b
+= a+=b a=a+b
-= a-=b a=a-b
*= a*=b a=a*b
/= a/=b a=a/b
%= a%=b a=a%b

Relational Operator
Relational operators checks relationship between two operands. If the relation is true, it returns value
1 and if the relation is false, it returns value 0. For example:

a>b
Here, > is a relational operator. If a is greater than b, a>b returns 1 if not then, it returns 0.
Relational operators are used in decision making and loops in C programming.
Operator Meaning of Operator Example
== Equal to 5==3 returns false (0)
> Greater than 5>3 returns true (1)

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 10


AN INTRODUCTION TO C LANGUAGE

< Less than 5<3 returns false (0)


!= Not equal to 5!=3 returns true(1)
>= Greater than or equal to 5>=3 returns true (1)
<= Less than or equal to 5<=3 return false (0)

Logical Operators
Logical operators are used to combine expressions containing relation operators. In C, there are 3
logical operators:
Operator Meaning of Operator Example
&& Logial AND If c=5 and d=2 then,((c==5) && (d>5)) returns false.
|| Logical OR If c=5 and d=2 then, ((c==5) || (d>5)) returns true.
! Logical NOT If c=5 then, !(c==5) returns false.
Explanation
For expression, ((c==5) && (d>5)) to be true, both c==5 and d>5 should be true but, (d>5) is false
in the given example. So, the expression is false. For expression ((c==5) || (d>5)) to be true, either
the expression should be true. Since, (c==5) is true. So, the expression is true. Since,
expression (c==5) is true, !(c==5) is false.
Conditional Operator
Conditional operator takes three operands and consists of two symbols ? and : . Conditional
operators are used for decision making in C. For example:

c=(c>0)?10:-10;
If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10.
Bitwise Operators
A bitwise operator works on each bit of data. Bitwise operators are used in bit level programming.
Operators Meaning of operators
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
>> Shift right
Bitwise operator is advance topic in programming . Learn more about bitwise operator in C
programming.
Other Operators
Comma Operator
Comma operators are used to link related expressions together. For example:

int a,c=5,d;
The sizeof operator
It is a unary operator which is used in finding the size of data type, constant, arrays, structure etc.
For example:
#include <stdio.h>
int main(){
int a;
float b;
double c;
char d;
printf("Size of int=%d bytes\n",sizeof(a));
printf("Size of float=%d bytes\n",sizeof(b));
printf("Size of double=%d bytes\n",sizeof(c));
printf("Size of char=%d byte\n",sizeof(d));
return 0;
INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 11
AN INTRODUCTION TO C LANGUAGE

}
Output

Size of int=4 bytes

Size of float=4 bytes

Size of double=8 bytes

Size of char=1 byte


Conditional operators (?:)
Conditional operators are used in decision making in C programming, i.e, executes different
statements according to test condition whether it is either true or false.
Syntax of conditional operators

conditional_expression?expression1:expression2
If the test condition is true, expression1 is returned and if false expression2 is returned.
Example of conditional operator
#include <stdio.h>
int main(){
char feb;
int days;
printf("Enter l if the year is leap year otherwise enter 0: ");
scanf("%c",&feb);
days=(feb=='l')?29:28;
/*If test condition (feb=='l') is true, days will be equal to 29. */
/*If test condition (feb=='l') is false, days will be equal to 28. */
printf("Number of days in February = %d",days);
return 0;
}
Output

Enter l if the year is leap year otherwise enter n: l

Number of days in February = 29


Programming Introduction Examples
This page contains example and source code on very basic features of C programming language. To
understand the examples on this page, you should have knowledge of following topics:
1. Variables and Constants
2. Data Types
3. Input and Output in C programming
4. Operators

Check your progress


1. C Program to Print a Sentence
2. C Program to Print a Integer Entered by a User
3. C Program to Add Two Integers Entered by User
4. C Program to Multiply two Floating Point Numbers
5. C Program to Find ASCII Value of Character Entered by User
6. C Program to Find Quotient and Remainder of Two Integers Entered by User
7. C Program to Find Size of int, float, double and char of Your System
8. C Program to Demonstrate the Working of Keyword long
9. C Program to Swap Two numbers Entered by User

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 12


AN INTRODUCTION TO C LANGUAGE

C Programming if, if..else and Nested if...else Statement


The if, if...else and nested if...else statement are used to make one-time decisions in C Programming,
that is, to execute some code/s and ignore some code/s depending upon the test expression.

C if Statement
if (test expression)
{
statement/s to be executed if test expression is true;
}
The if statement checks whether the text expression inside parenthesis () is true or not. If the test
expression is true, statement/s inside the body of if statement is executed but if test is false,
statement/s inside body of if is ignored.
Flowchart of if statement

Example 1: C if statement
Write a C program to print the number entered by user only if the number entered is negative.
#include <stdio.h>
int main(){
int num;
printf("Enter a number to check.\n");
scanf("%d",&num);
if(num<0) { /* checking whether number is less than 0 or not. */
printf("Number = %d\n",num);
}
/*If test condition is true, statement above will be executed, otherwise it will not be executed */
printf("The if statement in C programming is easy.");

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 13


AN INTRODUCTION TO C LANGUAGE

return 0;
}
Output 1
Enter a number to check.
-2
Number = -2
The if statement in C programming is easy.
When user enters -2 then, the test expression (num<0) becomes true. Hence, Number = -2 is
displayed in the screen.
Output 2
Enter a number to check.
5
The if statement in C programming is easy.
When the user enters 5 then, the test expression (num<0) becomes false. So, the statement/s inside
body of if is skipped and only the statement below it is executed.

C if...else statement
The if...else statement is used if the programmer wants to execute some statement/s when the test
expression is true and execute some other statement/s if the test expression is false.
Syntax of if...else
if (test expression) {
statements to be executed if test expression is true;
}
else {
statements to be executed if test expression is false;
}

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 14


AN INTRODUCTION TO C LANGUAGE

Flowchart of if...else statement

Example 2: C if...else statement


Write a C program to check whether a number entered by user is even or odd
#include <stdio.h>
int main(){
int num;
printf("Enter a number you want to check.\n");
scanf("%d",&num);
if((num%2)==0) //checking whether remainder is 0 or not.
printf("%d is even.",num);
else
printf("%d is odd.",num);
return 0;
}
Output 1
Enter a number you want to check.
25
25 is odd.
Output 2
Enter a number you want to check.
2
2 is even.

Nested if...else statement (if...elseif....else Statement)


The nested if...else statement is used when program requires more than one test expression.
Syntax of nested if...else statement.
if (test expression1){

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 15


AN INTRODUCTION TO C LANGUAGE

statement/s to be executed if test expression1 is true;


}
else if(test expression2) {
statement/s to be executed if test expression1 is false and 2 is true;
}
else if (test expression 3) {
statement/s to be executed if text expression1 and 2 are false and 3 is true;
}
else {
statements to be executed if all test expressions are false;
}
How nested if...else works?
The nested if...else statement has more than one test expression. If the first test expression is true, it
executes the code inside the braces{ } just below it. But if the first test expression is false, it checks
the second test expression. If the second test expression is true, it executes the statement/s inside the
braces{ } just below it. This process continues. If all the test expression are false, code/s
inside else is executed and the control of program jumps below the nested if...else
The ANSI standard specifies that 15 levels of nesting may be continued.
Example 3: C nested if else statement
Write a C program to relate two integers entered by user using = or > or < sign.
#include <stdio.h>
int main(){
int numb1, numb2;
printf("Enter two integers to check\n");
scanf("%d %d",&numb1,&numb2);
if(numb1==numb2) //checking whether two integers are equal.
printf("Result: %d = %d",numb1,numb2);
else
if(numb1>numb2) //checking whether numb1 is greater than numb2.
printf("Result: %d > %d",numb1,numb2);
else
printf("Result: %d > %d",numb2,numb1);
return 0;
}

C Programming for Loops


Looping means doing a work again and again. In our program, we may want to repeat a set of instructions many
times like entering many numbers or printing some values more than once. This repetition of instructions is
called looping.
Loops cause program to execute the certain block of code repeatedly until test condition is false.
Loops are used in performing repetitive task in programming. Consider these scenarios:
• You want to execute some code/s 100 times.
• You want to execute some code/s certain number of times depending upon input from user.
These types of task can be solved in programming using loops.
There are 3 types of loops in C programming:
1. while loop
2. do...while loop
3. for loop

while loop
while loop is a control flow statement that allows code to be executed repeatedly based on a given
boolean condition. The while loop can be thought of as a repeating if statement.

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 16


AN INTRODUCTION TO C LANGUAGE

while(condition_to_continue)
{
……………………;
……Statements…..;
……………………;
}
// Write a program to print numbers between 1 to 20.
#include<stdio.h>
void main()
{
int i=1;
while(i<=20)
{
printf(“\n%d”,i);
i++;
}
}

// Write a program to print all even numbers between 10 to 30.


#include<stdio.h>
void main()
{
int i=10;
while(i<=30)
{
if(i%2==0)
printf(“%d\n”,i);
i++;
}
}

// Write a program to enter numbers and calculate their sum.

#include<stdio.h>
void main()
{
int n, num, i =1, sum=0;
INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 17
AN INTRODUCTION TO C LANGUAGE

printf(“How many numbers you want to enter?”);


scanf(“%d”,&n);
printf(“Enter %d numbers now\n”,n);
while(i<=n)
{
scanf(“%d”,&num);
sum=sum+num;
i++;
}
printf(“\nThe sum of entered numbers is %d”, sum);
}

Break & Continue: “Break” and “Continue” are ‘C’ keywords that work with a loop. The work of
“break” is to stop the execution of the loop whereas the work of “continue” is to continue the
execution of the loop. Consider the following example:

#include<stdio.h>
void main()
{
int a=0;
while(a<20)
{
a++;
if(a%7==0)
break;
printf(“%d”,a);
}
}

#include<stdio.h>
void main()
{
int a=0;
while(a<20)
{
a++;
if(a%3==0)
continue;
printf(“%d”,a);
}
}

Nested While: Nesting of while means using “while” loop within another “while” loop. For example:

int i=1,j=1;
while(i<=3)
while(j<=3)
printf(“\n%d%d”,i,j);
DO-WHILE: It works exactly like “while” but the main difference between the two is that
“while” loop first checks the condition and then executes the statements within it. If the condition
evaluates to False on the very first time, loop will terminate.
INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 18
AN INTRODUCTION TO C LANGUAGE

On the other hand, a “do-while loop first executes the statements at least once and then
checks the condition.

do
{
……………………;
……Statements…..;
……………………;
}while(condition);

int a=5;
do
{
printf(“%d”,a);
a++;
}while(a>5&&a<10);

int a=5;
while(a>5&&a<10)
{
printf(“%d”,a);
a++;
}

// Write a program to print numbers between 1 to 100.

#include<stdio.h>
void main()
{
int n;
n=1;
while(n<=100)
{
printf(“%d”,n);
n++;
}

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 19


AN INTRODUCTION TO C LANGUAGE

// Write a program to print digit of a number in reverse order.

#include<stdio.h>
void main()
{
long int n, num;
printf(“Enter a number:”);
scanf(“%ld”,&n);
printf(“The reverse order of %ld is”,n);
while(n>0)
{
num=n%10;
printf(“%d”,num);
n=n/10;
}
}

FOR LOOP: for loop is another looping structure with some extra facilities over “while” loop.

for ( initialization; condition; increment / decrement )

for(expr1; condition; expr2)


{
……………………;
……Statements…..;
……………………;
}

// WAP to print numbers between 1 to 100.

#include<stdio.h>
void main()
{
INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 20
AN INTRODUCTION TO C LANGUAGE

int n;
for(n=1;n<=100;n++ )
{
Printf(“%d”,n);
}
}

// WAP to reverse the digit of a number.

#include<stdio.h>
void main()
{
long int n, sum;
printf(“Enter a number: ”);
scanf(“%ld”,&n);
printf(“The reverse number is “);
for( sum = 0 ; n ; )
{
sum=sum*10+n%10;
n=n/10;
}
printf(“%ld”,sum);
}

Nested for: Nesting of for means using “for” loop within another “for” loop. For example:

int i=1,j=1;
for(a=1;a<=3;a++)
for(j=1;j<=3;j++)
printf(“\n%d%d”,a,j);

// WAP to calculate the sum of the series: 1+3/2!+5/3!+7?4!+…………………………

#include<stdio.h>
void main()
{
float sum=0,f;
int a,j;
printf(“Enter the length of the series: ”);
scanf(“%d”,&n);
for(a=1;a<=n;a++)
{
for(j=1, f=1;j<=a;j++)
{
f=f*j;
sum=sum+(2*a-1)/f;
}
printf(“\nThe sum of the series of %d elements is %f”,n,sum);
}

GOTO: Goto transfers the control of the program to any marked line or label in the program.
INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 21
AN INTRODUCTION TO C LANGUAGE

// WAP to calculate the sum of n numbers entered by the user using goto.

#include<stdio.h>
void main()
{
int n,sum=0;
char more;
again:
printf(“Enter a number:”);
scanf(“%d”,&n);
fflush(stdin);
sum+=n;
printf(“Do you want to enter number(y / n)?”);
scanf(“%c”,&more);
if(more==’y’||more==’Y’)
goto again;
printf(“The sum of numbers is %d”, sum);
}

Q. What can one do if a loop is accidentally executed infinitely?


Ans. During program execution, press Ctrl + Break in Turbo compiler and then
Press any character key on the keyboard. This will return the control to the program
code.

// Program to print the prime no's.

#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j,prime;
clrscr();
printf("\n Prime no upto what?");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
prime=1;
for(j=2;j<i;j++)
if(i%j==0)
{
prime=0;
break;
}
if(prime)
printf("\n%d",i);
}
getch();
}

// Program to print the Fibonacci no's.

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 22


AN INTRODUCTION TO C LANGUAGE

#include<stdio.h>
#include<conio.h>
void main()
{
int f1,f2,f3,n,i;
printf("Enter how many terms");
scanf("%d",&n);
if(n<2)
{
printf("\n Invalid Input");
// exit(0);
}
f1=1;
f2=1;
i=0;
do
{
f3=f1+f2;
printf("\n%d",f3);
i++;
f1=f2;
f2=f3;
}
while(i<n);
getch();
}

// WAP to find H.C.F of two no’s.

#include<stdio.h>
void main()
{
int dividend,divisor,n,m,remainder,a;
printf("enter two numbers:");
scanf("%d%d",&n,&m);
if(n>m)
{
dividend=n;
divisor=m;
}
else
{
dividend=m;
divisor=n;
}
for(a=0;;a++)
{
remainder=dividend%divisor;
if(!remainder)
{

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 23


AN INTRODUCTION TO C LANGUAGE

printf("\nh.c.f.is %d",divisor);
break;
}
else
{
dividend=divisor;
divisor=remainder;
}
}

WAP to print like this


1
#include<stdio.h> 12
void main() 123
{ 1234
int i,j,n; 123 45
printf("Enter the numbers:"); 123456
scanf("%d",&n); 1234567
for(i=1;i<=n;i++) 12345678
{
for(j=1;j<=i;j++)
{
printf("%d",j);
}
printf("\n");
}
}

WAP to print like this


1
#include<stdio.h> 22
void main() 333
{ 4444
int i,j,n; 55555
printf("Enter the numbers:"); 666666
scanf("%d",&n); 7777777
for(i=1;i<=n;i++) 8 8 8 8 8 8….n
{
for(j=1;j<=i;j++)
{
printf("%d",j);
}
printf("\n");
}
}
WAP to print like this *
* *
#include<stdio.h> * * *
* * * *

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 24


AN INTRODUCTION TO C LANGUAGE

void main() * * * * *
{ * * * * * *
int n,a,j; * * * * * * *
printf("Enter the length :"); * * * * * * * *
scanf("%d",&n);
for(a=1;a<=n;++a)
{
for(j=1;j<=5-a;j++)
printf("A");
for(j=1;j<=a;j++)
printf("* ");
printf("\n");
}
}

WAP to print like this series: *


**
#include<stdio.h> ***
void main() ****
{ *****
int n,i,j; ******
printf("Enter the length :"); *******
scanf("%d",&n); ********
for(i=1;i<=n;++i)
{
for(j=1;j<=i;j++)
{
printf("*");
}
printf("\n");
}
}

WAP to print like this series: ********


*******
#include<stdio.h> ******
void main() *****
{ ****
int n,i,j; ***
printf("Enter the length :"); **
scanf("%d",&n); *
for(i=1;i<=n;++i)
{
for(j=5;j>=i;j--)
{
printf("*");
}
printf("\n");
}
}

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 25


AN INTRODUCTION TO C LANGUAGE

WAP to print like this

#include<stdio.h>

void main()
{ * * * * * *
int n,a,j; * * * * *
printf("Enter the length:"); * * * *
scanf("%d",&n); * * *
for(a=1;a<=n-1;a++) * *
{ *
for(j=15-n+a;j>=1;j--)
printf(" ");
for(j=1;j<=n-a;j++)
printf("* ");
printf("\n");
}
}

WAP to print like this *


* *
#include<stdio.h> * * *
* * * *
void main() * * * * *
{ * * * * * *
int n,a,j; * * * * *
printf("Enter the length:"); * * * *
scanf("%d",&n); * * *
for(a=1;a<=n;++a) * *
{ *
for(j=1;j<=15-a;j++)
printf(" ");
for(j=1;j<=a;j++)
printf("* ");
printf("\n");
}
for(a=1;a<=n-1;a++)
{
for(j=15-n+a;j>=1;j--)
printf(" ");
for(j=1;j<=n-a;j++)
printf("* ");
printf("\n");
}

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 26


AN INTRODUCTION TO C LANGUAGE

WAP to print table 1 to10 using do-while loop.

#include<stdio.h>
void main()
{
int COL,ROW,row,column,y;
printf("Enter the Column and Row :");
scanf("%d%d",&COL,&ROW);
row=1;
do {
column=1;
do {
y=row*column;
printf("%4d",y);
column++;
}
while(column<=COL);
printf("\n");
row++;
}while(row<=ROW);
}

WAP to print table 1 to10 using for loop.

#include<stdio.h>
void main()
{
int row,column,y;
for(row=1;row<=10;row++)
{
for(column=1;column<=10;column++)
{
y=row*column;
printf(“%4d”,y);
}
printf(“\n”);
}
}

WAP to find the equation y=xn when n is non-negative integer.

#include<stdio.h>
void main()
{
int count,n;
float x,y;
printf(“Enter the value of x and n: “);
scanf(“%f%d”,&x,&n);

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 27


AN INTRODUCTION TO C LANGUAGE

y=1.0;
count=1;
while(count<=n)
{
y=y*x;
count++;
}
printf(“\nx=%f; n=%d; x to power n=%f\n”,x,n,y);
}

Write a program to find the sum of first n natural numbers where n is entered by user. Note:
1,2,3... are called natural numbers.

#include <stdio.h>
int main(){
int n, count, sum=0;
printf("Enter the value of n.\n");
scanf("%d",&n);
for(count=1;count<=n;++count) //for loop terminates if count>n
{
sum+=count; /* this statement is equivalent to sum=sum+count */
}
printf("Sum=%d",sum);
return 0;
}

Example of while loop


Write a C program to find the factorial of a number, where the number is entered by user.
(Hints: factorial of n = 1*2*3*...*n

/*C program to demonstrate the working of while loop*/


#include <stdio.h>
int main(){
int number,factorial;
printf("Enter a number.\n");
scanf("%d",&number);
factorial=1;
while (number>0){ /* while loop continues util test condition number>0 is true */
factorial=factorial*number;
--number;
}
printf("Factorial=%d",factorial);
return 0;
}
Output

Enter a number.

Factorial=120
do...while loop

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 28


AN INTRODUCTION TO C LANGUAGE

In C, do...while loop is very similar to while loop. Only difference between these two loops is that,
in while loops, test expression is checked at first but, in do...while loop code is executed at first then
the condition is checked. So, the code are executed at least once in do...while loops.

Syntax of do...while loops

do {

some code/s;

while (test expression);


At first codes inside body of do is executed. Then, the test expression is checked. If it is true, code/s
inside body of do are executed again and the process continues until test expression becomes
false(zero).
Notice, there is semicolon in the end of while (); in do...while loop.

Example of do...while loop


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

/*C program to demonstrate the working of do...while statement*/


#include <stdio.h>
int main(){
int sum=0,num;
do /* Codes inside the body of do...while loops are at least executed once. */
{
printf("Enter a number\n");
scanf("%d",&num);
sum+=num;
}
while(num!=0);
printf("sum=%d",sum);
return 0;
}

Syntax of break statement

break;
The break statement can be used in terminating all three loops for, while and do...while loops.

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 29


AN INTRODUCTION TO C LANGUAGE

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

Example of break statement


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.

/* C program to demonstrate the working of break statement by terminating a loop, if user inputs
negative number*/
# include <stdio.h>
int main(){
float num,average,sum;
int i,n;
printf("Maximum no. of inputs\n");
scanf("%d",&n);
for(i=1;i<=n;++i){
printf("Enter n%d: ",i);
scanf("%f",&num);
if(num<0.0)
break; //for loop breaks if num<0.0
sum=sum+num;
}
average=sum/(i-1);
printf("Average=%.2f",average);
return 0;
}
Output
Syntax of continue Statement

continue;
Just like break, continue is also used with conditional if statement.

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 30


AN INTRODUCTION TO C LANGUAGE

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.

Example of continue statement


Write a C program to find the product of 4 integers entered by a user. If user enters 0 skip it.

//program to demonstrate the working of continue statement in C programming


# include <stdio.h>
int main(){
int i,num,product;
for(i=1,product=1;i<=4;++i){
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. */

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 31


AN INTRODUCTION TO C LANGUAGE

product*=num;
}
printf("product=%d",product);
return 0;
}

C Programming switch Statement


Decision making are needed when, the program encounters the situation to choose a particular
statement among many statements. If a programmer has to choose one block of statement among
many alternatives, nested if...else can be used but, this makes programming logic complex. This type
of problem can be handled in C programming using switch statement.

The switch statements evaluate the expression and then look for its value among the case constants. If the value
is found among a constraints listed, then the statements in that statements area executed. Otherwise if there is a
default then the program branches to that statement list. The syntax of the

Syntax of switch...case

switch (n) {

case constant1:

code/s to be executed if n equals to constant1;

break;

case constant2:
code/s to be executed if n equals to constant2;
break;
.
.
.
default:
code/s to be executed if n doesn't match to any cases;
}
The value of n is either an integer or a character in above syntax. If the value of n matches constant
in case, the relevant codes are executed and control moves out of the switch statement. If
the ndoesn't matches any of the constant in case, then the default codes are executed and control
moves out of switch statement.

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 32


AN INTRODUCTION TO C LANGUAGE

Example of switch...case statement


1. Write a program to input an integer between 1 to 4 and display the values in words.
#include<stdio.h>
#include<conio.h>
main()
{
Int i;
printf("Give an integer:");
scanf("%d",&i);
switch(ch)
{
case 1: printf(" one");
break;
case 2: printf("Two");
break;
case 3: printf("Three");
break;
case 4: printf("Four");
break;
default : printf("invalid input");
}
getch();
}
2. Write a program using switch case to print the comments according to the following
gradation scheme

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 33


AN INTRODUCTION TO C LANGUAGE

A, a=Very good
B, a= Good
C, c= Satisfactory
F, f= Fail
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
printf("give the charector");
scanf("%c",&ch);
switch(ch)
{
case 'a':
case 'A': printf("very good");
break;
case 'b':
case 'B': printf("good");
break;
case 'c':
case 'C': printf("satisfactory");
break;
case 'F':
case 'f': printf("fail");
break;
default :printf("invalid input");
}
getch();
}
3. Write a program to check that the inputted value is vowel or not.
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
printf("\n Give a charector:");
scanf("%c",&ch);
switch(ch)
{
case 'a':
case 'A':printf("you have typed the vowel A");
break;
case 'e':
case 'E':printf("you have typed the vowel E");
break;
case 'i':
case 'I':printf("you have typed the vowel I");
break;
INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 34
AN INTRODUCTION TO C LANGUAGE

case 'o':
case 'O':printf("you have typed the vowel O");
break;
case 'u':
case 'U':printf("you have typed the vowel U");
break;
case 0: printf("\n the end");
default :printf("\n You have typed a consonants:");
}
getch();
}
4. Write a program to make the computer work like a pocket calculator that is it should
input the two number and perform all the arithmetic operation on the given number’s.
#include<stdio.h>
#include<conio.h>
main()
{
int a,b,c,op;
printf("\n 1. To add");
printf("\n 2. To subtract");
printf("\n 3. To multiply");
printf("\n 4. To Divide");
printf("\n 5. To exit");
printf("\n Enter your choice:");
scanf("%d",&op);
switch(op)
{
case 1: printf("Give the value of a and b");
scanf("%d %d",&a,&b);
c=a+b;
printf("the addition of two no's are=%d",c);
break;
case 2: printf("Give the value of a and b");
scanf("%d %d",&a,&b);
c=a-b;
printf("the subtraction of two no's are=%d",c);
break;
case 3: printf("Give the value of a and b");
scanf("%d %d",&a,&b);
c=a*b;
printf("the multiplication of two no's are=%d",c);
break;

case 4: printf("Give the value of a and b");


scanf("%d %d",&a,&b);
c=a/b;
printf("the divide of two no's are=%d",c);

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 35


AN INTRODUCTION TO C LANGUAGE

break;
case 0: printf("\n the end");
default :printf("\n invalid choice");
}
getch();
}

5. Write a program that asks user an arithmetic operator('+','-','*' or '/') and two
operands and perform the corresponding calculation on the operands.

/* C program to demonstrate the working of switch...case statement */


/* C Program to create a simple calculator for addition, subtraction,
multiplication and division */

# include <stdio.h>
int main() {
char o;
float num1,num2;
printf("Select an operator either + or - or * or / \n");
scanf("%c",&o);
printf("Enter two operands: ");
scanf("%f%f",&num1,&num2);
switch(o) {
case '+':
printf("%.1f + %.1f = %.1f",num1, num2, num1+num2);
break;
case '-':
printf("%.1f - %.1f = %.1f",num1, num2, num1-num2);
break;
case '*':
printf("%.1f * %.1f = %.1f",num1, num2, num1*num2);
break;
case '/':
printf("%.1f / %.1f = %.1f",num1, num2, num1/num2);
break;
default:
/* If operator is other than +, -, * or /, error message is shown */
printf("Error! operator is not correct");
break;
}
return 0;
}

C Programming goto Statement


In C programming, goto statement is used for altering the normal sequence of program execution by
transferring control to some other part of the program.
Syntax of goto statement

goto label;

.............

.............

.............

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 36


AN INTRODUCTION TO C LANGUAGE

label:

statement;
In this syntax, label is an identifier. When, the control of program reaches to goto statement, the
control of the program will jump to the label: and executes the code below it.

Example of goto statement

/* C program to demonstrate the working of goto statement. */


/* This program calculates the average of numbers entered by user. */
/* If user enters negative number, it ignores that number and
calculates the average of number entered before it.*/
# include <stdio.h>
int main()
{
float num,average,sum;
int i,n;
printf("Maximum no. of inputs: ");
scanf("%d",&n);
for(i=1;i<=n;++i){
printf("Enter n%d: ",i);
scanf("%f",&num);
if(num<0.0)
goto jump; /* control of the program moves to label jump */
sum=sum+num;
}
jump:
average=sum/(i-1);
printf("Average: %.2f",average);
return 0;
}
Though goto statement is included in ANSI standard of C, use of goto statement should be reduced
as much as possible in a program.
Reasons to avoid goto statement
Though, using goto statement give power to jump to any part of program, using goto statement
makes the logic of the program complex and tangled. In modern programming, goto statement is
considered a harmful construct and a bad programming practice.
The goto statement can be replaced in most of C program with the use of break and continue
statements. In fact, any program in C programming can be perfectly written without the use of goto
statement. All programmer should try to avoid goto statement as possible as they can.

Check your Progress


C Programming Examples and Source Code

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 37


AN INTRODUCTION TO C LANGUAGE

C Program to Check Whether a Number is Even or Odd


C Program to Check Whether a Character is Vowel or consonant
C Program to Find the Largest Number Among Three Numbers Entered by User
C program to Find all Roots of a Quadratic equation
C Program to Check Whether the Entered Year is Leap Year or not
C Program to Check Whether a Number is Positive or Negative or Zero.
C Program to Checker Whether a Character is an Alphabet or not
C Program to Find Sum of Natural Numbers
C Program to Find Factorial of a Number
C program to Generate Multiplication Table
C Program to Display Fibonacci Series
C Program to Find HCF of two Numbers
C Program to Find LCM of two numbers entered by user
C Program to Count Number of Digits of an Integer
C Program to Reverse a Number
C program to Calculate the Power of a Number
C Program to Check Whether a Number is Palindrome or Not
C Program to Check Whether a Number is Prime or Not
C Program to Display Prime Numbers Between Two Intervals
C program to Check Armstrong Number
C Program to Display Armstrong Number Between Two Intervals
C program to Display Factors of a Number
C program to Print Pyramids and Triangles in C programming using Loops
C program to Make a Simple Calculator to Add, Subtract, Multiply or Divide Using switch...case

C Programming Functions
In programming, a function is a segment that groups code to perform a specific task.
A C program has at least one function main( ). Without main() function, there is technically no C
program.

Types of C functions
There are two types of functions in C programming:
• Library function
• User defined function
Library function
Library functions are the in-built function in C programming system. For example:

main()
- The execution of every C program starts from this main() function.

printf()
- prinf() is used for displaying output in C.

scanf()
- scanf() is used for taking input in C.
Visit this page to learn more about library functions in C programming language.
User defined function
C allows programmer to define their own function according to their requirement. These types of
functions are known as user-defined functions. Suppose, a programmer wants to find factorial of a
number and check whether it is prime or not in same program. Then, he/she can create two separate
user-defined functions in that program: one for finding factorial and other for checking whether it is
prime or not.

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 38


AN INTRODUCTION TO C LANGUAGE

How user-defined function works in C Programming?

#include <stdio.h>

void function_name(){

................

................

int main(){

...........

...........

function_name();

...........

...........

}
As mentioned earlier, every C program begins from main() and program starts executing the codes
inside main() function. When the control of program reaches
to function_name() inside main()function. The control of program jumps to void
function_name() and executes the codes inside it. When all the codes inside that user -defined
function are executed, control of the program jumps to the statement just after function_name() from
where it is called. Analyze the figure below for understanding the concept of function in C
programming. Visit this page to learn in detail about user-defined functions.

Remember, the function name is an identifier and should be unique.


Advantages of user defined functions
1. User defined functions helps to decompose the large program into small segments which makes
programmer easy to understand, maintain and debug.
2. If repeated code occurs in a program. Function can be used to include those codes and execute when
needed by calling that function.
3. Programmer working on large project can divide the workload by making different functions.

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 39


AN INTRODUCTION TO C LANGUAGE

C Programming User-defined functions


This chapter is the continuation to the function Introduction chapter.

Example of user-defined function


Write a C program to add two integers. Make a function add to add integers and display sum
inmain() function.
/*Program to demonstrate the working of user defined function*/
#include <stdio.h>
int add(int a, int b); //function prototype(declaration)
int main(){
int num1,num2,sum;
printf("Enters two number to add\n");
scanf("%d %d",&num1,&num2);
sum=add(num1,num2); //function call
printf("sum=%d",sum);
return 0;
}
int add(int a,int b) //function declarator
{
/* Start of function definition. */
int add;
add=a+b;
return add; //return statement of function
/* End of function definition. */
}

Function prototype(declaration):
Every function in C programming should be declared before they are used. These type of declaration
are also called function prototype. Function prototype gives compiler information about function
name, type of arguments to be passed and return type.
Syntax of function prototype

return_type function_name(type(1) argument(1),....,type(n) argument(n));


In the above example,int add(int a, int b); is a function prototype which provides following
information to the compiler:
1. name of the function is add()
2. return type of the function is int.
3. two arguments of type int are passed to function.
Function prototype are not needed if user-definition function is written before main() function.

Function call
Control of the program cannot be transferred to user -defined function unless it is called invoked.
Syntax of function call

function_name(argument(1),....argument(n));
In the above example, function call is made using statement add(num1,num2); from main(). This
make the control of program jump from that statement to function definition and executes the codes
inside that function.

Function definition
Function definition contains programming codes to perform specific task.
Syntax of function definition

return_type function_name(type(1) argument(1),..,type(n) argument(n))


INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 40
AN INTRODUCTION TO C LANGUAGE

//body of function

}
Function definition has two major components:
1. Function declarator
Function declarator is the first line of function definition. When a function is called, control of the
program is transferred to function declarator.
Syntax of function declarator

return_type function_name(type(1) argument(1),....,type(n) argument(n))


Syntax of function declaration and declarator are almost same except, there is no semicolon at the
end of declarator and function declarator is followed by function body.
In above example, int add(int a,int b) in line 12 is a function declarator.
2. Function body
Function declarator is followed by body of function inside braces.

Passing arguments to functions


In programming, argument(parameter) refers to data this is passed to function(function definition)
while calling function.
In above example two variable, num1 and num2 are passed to function during function call and these
arguments are accepted by arguments a and b in function definition.

Arguments that are passed in function call and arguments that are accepted in function definition
should have same data type. For example:
If argument num1 was of int type and num2 was of float type then, argument variable a should be of
type int and b should be of type float,i.e ., type of argument during function call and function
definition should be same.
A function can be called with or without an argument.

Return Statement
Return statement is used for returning a value from function definition to calling function.
Syntax of return statement

return (expression);
For example:

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 41


AN INTRODUCTION TO C LANGUAGE

return a;

return (a+b);
In above example, value of variable add in add() function is returned and that value is stored in
variable sum in main() function. The data type of expression in return statement should also match
the return type of function.

Types of User-defined Functions in C Programming


For better understanding of arguments and return type in functions, user -defined functions can be
categorised as:
1. Function with no arguments and no return value
2. Function with no arguments and return value
3. Function with arguments but no return value
4. Function with arguments and return value.
Let's take an example to find whether a number is prime or not using above 4 categories of user
defined functions.

Function with no arguments and no return value.

/*C program to check whether a number entered by user is prime or not using function with no
arguments and no return value*/
#include <stdio.h>
void prime();
int main(){
prime(); //No argument is passed to prime().
return 0;
}
void prime(){
/* There is no return value to calling function main(). Hence, return type of prime() is void */
int num,i,flag=0;
printf("Enter positive integer enter to check:\n");
scanf("%d",&num);
for(i=2;i<=num/2;++i){
if(num%i==0){
flag=1;
}
}
if (flag==1)
printf("%d is not prime",num);
else
printf("%d is prime",num);
}
Function prime() is used for asking user a input, check for whether it is prime of not and display it
accordingly. No argument is passed and returned form prime() function.

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 42


AN INTRODUCTION TO C LANGUAGE

Function with no arguments but return value

/*C program to check whether a number entered by user is prime or not using function with no
arguments but having return value */
#include <stdio.h>
int input();
int main(){
int num,i,flag = 0;
num=input(); /* No argument is passed to input() */
for(i=2; i<=num/2; ++i){
if(num%i==0){
flag = 1;
break;
}
}
if(flag == 1)
printf("%d is not prime",num);
else
printf("%d is prime", num);
return 0;
}
int input(){ /* Integer value is returned from input() to calling function */
int n;
printf("Enter positive integer to check:\n");
scanf("%d",&n);
return n;
}
There is no argument passed to input() function But, the value of n is returned
from input() tomain() function.

Function with arguments and no return value

/*Program to check whether a number entered by user is prime or not using function with
arguments and no return value */
#include <stdio.h>
void check_display(int n);
int main(){
int num;
printf("Enter positive enter to check:\n");
scanf("%d",&num);
check_display(num); /* Argument num is passed to function. */
return 0;
}
void check_display(int n){
/* There is no return value to calling function. Hence, return type of function is void. */
int i, flag = 0;
for(i=2; i<=n/2; ++i){
if(n%i==0){
flag = 1;
break;
}
}
if(flag == 1)
printf("%d is not prime",n);
else
printf("%d is prime", n);
}

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 43


AN INTRODUCTION TO C LANGUAGE

Here, check_display() function is used for check whether it is prime or not and display it
accordingly. Here, argument is passed to user-defined function but, value is not returned from it to
calling function.

Function with argument and a return value

/* Program to check whether a number entered by user is prime or not using function with
argument and return value */
#include <stdio.h>
int check(int n);
int main(){
int num,num_check=0;
printf("Enter positive enter to check:\n");
scanf("%d",&num);
num_check=check(num); /* Argument num is passed to check() function. */
if(num_check==1)
printf("%d is not prime",num);
else
printf("%d is prime",num);
return 0;
}
int check(int n){
/* Integer value is returned from function check() */
int i;
for(i=2;i<=n/2;++i){
if(n%i==0)
return 1;
}
return 0;
}

Here, check() function is used for checking whether a number is prime or not. In this program, input
from user is passed to function check() and integer value is returned from it. If input the number is
prime, 0 is returned and if number is not prime, 1 is returned.
C Programming Recursion
A function that calls itself is known as recursive function and this technique is known as recursion in
C programming.
Example of recursion in C programming
Write a C program to find sum of first n natural numbers using recursion. Note: Positive
integers are known as natural number i.e. 1, 2, 3....n

#include <stdio.h>
int sum(int n);
int main(){
int num,add;
printf("Enter a positive integer:\n");
scanf("%d",&num);
add=sum(num);
printf("sum=%d",add);
}
int sum(int n){
if(n==0)
return n;
else
return n+sum(n-1); /*self call to function sum() */
}
Output

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 44


AN INTRODUCTION TO C LANGUAGE

Enter a positive integer:

15
In, this simple C program, sum() function is invoked from the same function. If n is not equal to 0
then, the function calls itself passing argument 1 less than the previous argument it was called with.
Suppose, n is 5 initially. Then, during next function calls, 4 is passed to function and the value of
argument decreases by 1 in each recursive call. When, n becomes equal to 0, the value of n is
returned which is the sum numbers from 5 to 1.
For better visualization of recursion in this example:

sum(5)

=5+sum(4)

=5+4+sum(3)

=5+4+3+sum(2)

=5+4+3+2+sum(1)

=5+4+3+2+1+sum(0)

=5+4+3+2+1+0

=5+4+3+2+1

=5+4+3+3

=5+4+6

=5+10

=15
Every recursive function must be provided with a way to end the recursion. In this example
when, n is equal to 0, there is no recursive call and recursion ends.
Advantages and Disadvantages of Recursion
Recursion is more elegant and requires few variables which make program clean. Recursion can be
used to replace complex nesting code by dividing the problem into same problem of its sub -type.
In other hand, it is hard to think the logic of a recursive function. It is also difficult to debug the
code containing recursion.
C Programming Storage Class
Every variable in C programming has two properties: type and storage class. Type refers to the data
type of variable whether it is character or integer or floating -point value etc. And storage class
determines how long it stays in existence.
There are 4 types of storage class:
1. automatic
2. external
3. static
4. register

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 45


AN INTRODUCTION TO C LANGUAGE

Automatic storage class


Keyword for automatic variable

auto
Variables declared inside the function body are automatic by default. These variable are also known
as local variables as they are local to the function and doesn't have meaning outside that function
Since, variable inside a function is automatic by default, keyword auto are rarely used.

External storage class


External variable can be accessed by any function. They are also known as global variables.
Variables declared outside every function are external variables.
In case of large program, containing more than one file, if the global variable is declared in file 1
and that variable is used in file 2 then, compiler will show error. To solve this problem,
keyword extern is used in file 2 to indicate that, the variable specified is global variable and declared
in another file.
Example to demonstrate working of external variable

#include
void Check();
int a=5;
/* a is global variable because it is outside every function */
int main(){
a+=4;
Check();
return 0;
}

void Check(){
++a;
/* ----- Variable a is not declared in this function but, works in any function as they are global
variable ------- */
printf("a=%d\n",a);
}
Output

a=10

Register Storage Class


Keyword to declare register variable

register
Example of register variable

register int a;
Register variables are similar to automatic variable and exists inside that particular function only.
If the compiler encounters register variable, it tries to store variable in microprocessor's register
rather than memory. Value stored in register are much faster than that of memory.
In case of larger program, variables that are used in loops and function parameters are declared
register variables.
Since, there are limited number of register in processor and if it couldn't store the variable in
register, it will automatically store it in memory.

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 46


AN INTRODUCTION TO C LANGUAGE

Static Storage Class


The value of static variable persists until the end of the program. A variable can be declared static
using keyword: static. For example:

static int i;
Here, i is a static variable.
Example to demonstrate the static variable
#include <stdio.h>
void Check();
int main(){
Check();
Check();
Check();
}
void Check(){
static int c=0;
printf("%d\t",c);
c+=5;
}
Output

0 5 10
During first function call, it will display 0. Then, during second function call, variable c will not be
initialized to 0 again, as it is static variable. So, 5 is displayed in second function call and 10 in third
call.
If variable c had been automatic variable, the output would have been:

0 0 0
C Programming Function Example
This page contains examples and source code on how to work with user -defined function. To
understand all the program on this page, you should have knowledge of following function topics:
1. User-Defined Function
2. User-Defined Function Types
3. Storage class( Specially, local variables )
4. Recursion

C Function Examples

C Programming Examples and Source Code

C Program to Display Prime Numbers Between Intervals by Making Function


C Program to Check Prime and Armstrong Number by Making Function
C program to Check Whether a Number can be Express as Sum of Two Prime Numbers
C program to Find Sum of Natural Numbers using Recursion.
C program to Calculate Factorial of a Number Using Recursion
C Program to Find H.C.F Using Recursion
C program to Reverse a Sentence Using Recursion
C program to Calculate the Power of a Number Using Recursion
C Program to Convert Binary Number to Decimal and Decimal to Binary

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 47


AN INTRODUCTION TO C LANGUAGE

C Programming Examples and Source Code

C Program to Convert Octal Number to Decimal and Decimal to Octal


C Program to Convert Binary Number to Octal and Octal to Binary
C Programming Arrays
In C programming, one of the frequently arising problem is to handle similar types of data. For
example: If the user want to store marks of 100 students. This can be done by creating 100 variable
individually but, this process is rather tedious and impracticable. These type of problem can be
handled in C programming using arrays.
An array is a sequence of data item of homogeneous value(same type).
Arrays are of two types:
1. One-dimensional arrays
2. Multidimensional arrays( will be discussed in next chapter )
Declaration of one-dimensional array

data_type array_name[array_size];

For example:
int age[5];
Here, the name of array is age. The size of array is 5,i.e., there are 5 items(elements) of array age.
All element in an array are of the same type (int, in this case).
Array elements
Size of array defines the number of elements in an array. Each element of array can be accessed and
used by user according to the need of program. For example:

int age[5];

Note that, the first element is numbered 0 and so on.


Here, the size of array age is 5 times the size of int because there are 5 elements.
Suppose, the starting address of age[0] is 2120d and the size of int be 4 bytes. Then, the next address
(address of a[1]) will be 2124d, address of a[2] will be 2128d and so on.
Initialization of one-dimensional array:
Arrays can be initialized at declaration time in this source code as:

int age[5]={2,4,34,3,4};
It is not necessary to define the size of arrays during initialization.

int age[]={2,4,34,3,4};
In this case, the compiler determines the size of array by calculating the number of elements of an
array.

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 48


AN INTRODUCTION TO C LANGUAGE

Accessing array elements


In C programming, arrays can be accessed and treated like variables in C.
For example:

scanf("%d",&age[2]);

/* statement to insert value in the third element of array age[]. */

scanf("%d",&age[i]);

/* Statement to insert value in (i+1)th element of array age[]. */

/* Because, the first element of array is age[0], second is age[1], ith is age[i -1] and (i+1)th is
age[i]. */

printf("%d",age[0]);

/* statement to print first element of an array. */

printf("%d",age[i]);

/* statement to print (i+1)th element of an array. */


Example of array in C programming

/* C program to find the sum marks of n students using arrays */

#include <stdio.h>
int main(){
int marks[10],i,n,sum=0;
printf("Enter number of students: ");
scanf("%d",&n);
for(i=0;i<n;++i){
printf("Enter marks of student%d: ",i+1);
scanf("%d",&marks[i]);
sum+=marks[i];
}
printf("Sum= %d",sum);
return 0;
}

Output

Enter number of students: 3

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 49


AN INTRODUCTION TO C LANGUAGE

Enter marks of student1: 12

Enter marks of student2: 31

Enter marks of student3: 2

sum=45
Important thing to remember in C arrays
Suppose, you declared the array of 10 students. For example: arr[10]. You can use array members
from arr[0] to arr[9]. But, what if you want to use element arr[10], arr[13] etc. Compiler may not
show error using these elements but, may cause fatal error during program execution.
C Programming Multidimensional Arrays
C programming language allows programmer to create arrays of arrays known as multidimensional
arrays. For example:

float a[2][6];
Here, a is an array of two dimension, which is an example of multidimensional array.
For better understanding of multidimensional arrays, array elements of above example can be thinked
of as below:

Initialization of Multidimensional Arrays


In C, multidimensional arrays can be initialized in different number of ways.

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

OR

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

OR

int c[2][3]={1,3,0,-1,5,9};
Initialization Of three-dimensional Array

double cprogram[3][2][4]={

{{-0.1, 0.22, 0.3, 4.3}, {2.3, 4.7, -0.9, 2}},

{{0.9, 3.6, 4.5, 4}, {1.2, 2.4, 0.22, -1}},

{{8.2, 3.12, 34.2, 0.1}, {2.1, 3.2, 4.3, -2.0}}

};

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 50


AN INTRODUCTION TO C LANGUAGE

Suppose there is a multidimensional array arr[i][j][k][m]. Then this array can hold i*j*k*m numbers
of data.
Similarly, the array of any dimension can be initialized in C programming.
Example of Multidimensional Array In C
Write a C program to find sum of two matrix of order 2*2 using multidimensional arrays
where, elements of matrix are entered by user.

#include <stdio.h>
int main(){
float a[2][2], b[2][2], c[2][2];
int i,j;
printf("Enter the elements of 1st matrix\n");
/* Reading two dimensional Array with the help of two for loop. If there was an array of 'n'
dimension, 'n' numbers of loops are needed for inserting data to array.*/
for(i=0;i<2;++i)
for(j=0;j<2;++j){
printf("Enter a%d%d: ",i+1,j+1);
scanf("%f",&a[i][j]);
}
printf("Enter the elements of 2nd matrix\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j){
printf("Enter b%d%d: ",i+1,j+1);
scanf("%f",&b[i][j]);
}
for(i=0;i<2;++i)
for(j=0;j<2;++j){
/* Writing the elements of multidimensional array using loop. */
c[i][j]=a[i][j]+b[i][j]; /* Sum of corresponding elements of two arrays. */
}
printf("\nSum Of Matrix:");
for(i=0;i<2;++i)
for(j=0;j<2;++j){
printf("%.1f\t",c[i][j]);
if(j==1) /* To display matrix sum in order. */
printf("\n");
}
return 0;
}

Ouput

Enter the elements of 1st matrix

Enter a11: 2;

Enter a12: 0.5;

Enter a21: -1.1;

Enter a22: 2;

Enter the elements of 2nd matrix

Enter b11: 0.2;

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 51


AN INTRODUCTION TO C LANGUAGE

Enter b12: 0;

Enter b21: 0.23;

Enter b22: 23;

Sum Of Matrix:

2.2 0.5

-0.9 25.0
C Programming Arrays and Functions

In C programming, a single array element or an entire array can be passed to a function. Also, both
one-dimensional and multi-dimensional array can be passed to function as argument.

Passing One-dimensional Array In Function


C program to pass a single element of an array to function

#include <stdio.h>
void display(int a)
{
printf("%d",a);
}
int main(){
int c[]={2,3,4};
display(c[2]); //Passing array element c[2] only.
return 0;
}
Output

4
Single element of an array can be passed in similar manner as passing variable to a function.
Passing entire one-dimensional array to a function
While passing arrays to the argument, the name of the array is passed as an argument(,i.e, starting
address of memory area is passed as argument).
Write a C program to pass an array containing age of person to a function. This function
should find average age and display the average age in main function.

#include <stdio.h>
float average(float a[]);
int main(){
float avg, c[]={23.4, 55, 22.6, 3, 40.5, 18};
avg=average(c); /* Only name of array is passed as argument. */
printf("Average age=%.2f",avg);
return 0;
}
float average(float a[]){
int i;
float avg, sum=0.0;
for(i=0;i<6;++i){
sum+=a[i];
}
avg =(sum/6);

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 52


AN INTRODUCTION TO C LANGUAGE

return avg;
}
Output

Average age=27.08

Passing Multi-dimensional Arrays to Function


To pass two-dimensional array to a function as an argument, starting address of memory area
reserved is passed as in one dimensional array
Example to pass two-dimensional arrays to function

#include
void Function(int c[2][2]);
int main(){
int c[2][2],i,j;
printf("Enter 4 numbers:\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j){
scanf("%d",&c[i][j]);
}
Function(c); /* passing multi-dimensional array to function */
return 0;
}
void Function(int c[2][2]){
/* Instead to above line, void Function(int c[][2]){ is also valid */
int i,j;
printf("Displaying:\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j)
printf("%d\n",c[i][j]);
}
Output

Enter 4 numbers:

Displaying:

5
C Programming Array and Pointer Examples
This page contains examples and source code on arrays and pointers. To understand all program on
this page, you should have knowledge of following array and pointer topics:

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 53


AN INTRODUCTION TO C LANGUAGE

1. Arrays
2. Multi-dimensional Arrays
3. Pointers
4. Array and Pointer Relation
5. Call by Reference
6. Dynamic Memory Allocation

Array and Pointer Examples

C Programming Examples and Source Code

C Program to Calculate Average Using Arrays


C Program to Find Largest Element of an Array
C Program to Calculate Standard Deviation
C Program to Add Two Matrix Using Multi-dimensional Arryas
C Program to Multiply to Matrix Using Multi-dimensional Arrays
C Program to Find Transpose of a Matrix
C Program to Multiply two Matrices by Passing Matrix to Function
C Program to Sort Elements of an Array
C Program to Access Elements of an Array Using Pointer
C Program Swap Numbers in Cyclic Order Using Call by Reference
C Program to Find Largest Number Using Dynamic Memory Allocation

C Programming Structure
Structure is the collection of variables of different types under a single name for better handling. For
example: You want to store the information about person about his/her name, citizenship number and
salary. You can create these information separately but, better approach will be collection of these
information under single name because all these information are related to person.

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

};
INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 54
AN INTRODUCTION TO C LANGUAGE

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

struct person

char name[50];

int cit_no;

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 is allocated. For the above
structure of person, variable can be declared as:

struct person

char name[50];

int cit_no;

float salary;

};

Inside main function:


struct person p1, p2, p[20];
Another way of creating sturcture variable is:

struct person

char name[50];

int cit_no;

float salary;

}p1 ,p2 ,p[20];


In both cases, 2 variables p1, p2 and array p 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.
1. Member operator(.)
INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 55
AN INTRODUCTION TO C LANGUAGE

2. Structure pointer operator(->) (will be discussed in structure and pointers chapter)


Any member of a structure can be accessed as: structure_variable_name.member_name
Suppose, we want to access salary for variable p2. Then, it can be accessed as:

p2.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;
}d1,d2,sum;
int main(){
printf("1st distance\n");
printf("Enter feet: ");
scanf("%d",&d1.feet); /* input of feet for structure variable d1 */
printf("Enter inch: ");
scanf("%f",&d1.inch); /* input of inch for structure variable d1 */
printf("2nd distance\n");
printf("Enter feet: ");
scanf("%d",&d2.feet); /* input of feet for structure variable d2 */
printf("Enter inch: ");
scanf("%f",&d2.inch); /* input of inch for structure variable d2 */
sum.feet=d1.feet+d2.feet;
sum.inch=d1.inch+d2.inch;
if (sum.inch>12){ //If inch is greater than 12, changing it to feet.
++sum.feet;
sum.inch=sum.inch-12;
}
printf("Sum of distances=%d\'-%.1f\"",sum.feet,sum.inch);
/* printing sum of distance d1 and d2 */
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
Programmer generally use typedef while using structure in C language. For example:

typedef struct complex{

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 56


AN INTRODUCTION TO C LANGUAGE

int imag;

float real;

}comp;

Inside main:

comp c1,c2;
Here, typedef keyword is used in creating a type comp(which is of type as struct complex). Then,
two structure variables c1 and c2 are created by this comp type.

Structures within structures


Structures can be nested within other structures in C programming.

struct complex

int imag_value;

float real_value;

};

struct number{

struct complex c1;

int real;

}n1,n2;
Suppose you want to access imag_value for n2 structure variable then, structure
membern1.c1.imag_value is used.
Programming Structure and Pointer
Pointers can be accessed along with structures. A pointer variable of structure can be created as
below:

struct name {

member1;

member2;

};

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 57


AN INTRODUCTION TO C LANGUAGE

-------- Inside function -------

struct name *ptr;


Here, the pointer variable of type struct name is created.
Structure's member through pointer can be used in two ways:
1. Referencing pointer to another address to access memory
2. Using dynamic memory allocation
Consider an example to access structure's member through pointer.
#include <stdio.h>
struct name{
int a;
float b;
};
int main(){
struct name *ptr,p;
ptr=&p; /* Referencing pointer to memory address of p */
printf("Enter integer: ");
scanf("%d",&(*ptr).a);
printf("Enter number: ");
scanf("%f",&(*ptr).b);
printf("Displaying: ");
printf("%d%f",(*ptr).a,(*ptr).b);
return 0;
}
In this example, the pointer variable of type struct name is referenced to the address of p. Then,
only the structure member through pointer can can accessed.
Structure pointer member can also be accessed using -> operator.

(*ptr).a is same as ptr->a

(*ptr).b is same as ptr->b


Accessing structure member through pointer using dynamic memory allocation
To access structure member using pointers, memory can be allocated dynamically using malloc()
function defined under "stdlib.h" header file.
Syntax to use malloc()

ptr=(cast-type*)malloc(byte-size)
Example to use structure's member through pointer using malloc() function.
#include <stdio.h>
#include<stdlib.h>
struct name {
int a;
float b;
char c[30];
};
int main(){
struct name *ptr;
int i,n;
printf("Enter n: ");
scanf("%d",&n);
ptr=(struct name*)malloc(n*sizeof(struct name));
/* Above statement allocates the memory for n structures with pointer ptr pointing to base address
*/
for(i=0;i<n;++i){
printf("Enter string, integer and floating number respectively:\n");
scanf("%s%d%f",&(ptr+i)->c,&(ptr+i)->a,&(ptr+i)->b);

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 58


AN INTRODUCTION TO C LANGUAGE

}
printf("Displaying Infromation:\n");
for(i=0;i<n;++i)
printf("%s\t%d\t%.2f\n",(ptr+i)->c,(ptr+i)->a,(ptr+i)->b);
return 0;
}
Output

Enter n: 2

Enter string, integer and floating number respectively:

Programming

3.2

Enter string, integer and floating number respectively:

Structure

2.3

Displaying Information

Programming 2 3.20

Structure 6 2.30
C Programming Structure and Function
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 normal variable. If structure is
passed by value, change made in structure variable in function definition does not reflect in original
structure variable in calling function.
Write a C program to create a structure student, containing name and roll. Ask user the name and roll
of a student in main function. Pass this structure to a function and display the information in that
function.
#include <stdio.h>
struct student{
char name[50];
int roll;
};
void Display(struct student stu);
/* function prototype should be below to the structure declaration otherwise compiler shows error
*/
int main(){
struct student s1;
printf("Enter student's name: ");
scanf("%s",&s1.name);

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 59


AN INTRODUCTION TO C LANGUAGE

printf("Enter roll number:");


scanf("%d",&s1.roll);
Display(s1); // passing structure variable s1 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 address location of structure variable is passed to function while passing it by reference. If
structure is passed by reference, change made in structure variable in function definition reflects in
original structure variable in the calling function.
Write a C program to add two distances(feet-inch system) entered by user. To solve this
program, make a structure. Pass two structure variable (containing distance in feet and inch) to
add function by reference and display the result in main function without returning it.
#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;

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 60


AN INTRODUCTION TO C LANGUAGE

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"


Explaination
In this program, structure variables dist1 and dist2 are passed by value (because value
of dist1and dist2 does not need to be displayed in main function) and dist3 is passed by reference
,i.e, address of dist3 (&dist3) is passed as an argument. Thus, the structure pointer variable d3 points
to the address of dist3. If any change is made in d3 variable, effect of it is seed in dist3 variable in
main function.
C Programming Unions
Unions are quite similar to the structures in C. Union is also a derived type as structure. Union can be defined in
same manner as structures just the keyword used in defining union in union where keyword used in defining
structure was struct.

union car{

char name[50];

int price;

};
Union variables can be created in similar manner as structure variable.

union car{

char name[50];

int price;

}c1, c2, *c3;

OR;
INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 61
AN INTRODUCTION TO C LANGUAGE

union car{

char name[50];

int price;

};

-------Inside Function-----------

union car c1, c2, *c3;


In both cases, union variables c1, c2 and union pointer variable c3 of type union car is created.
Accessing members of an union
The member of unions can be accessed in similar manner as that structure. Suppose, we you want to access price
for union variable c1 in above example, it can be accessed as c1.price. If you want to access price for union
pointer variable c3, it can be accessed as (*c3).price or as c3->price.

Difference between union and structure


Though unions are similar to structure in so many ways, the difference between them is crucial to understand.
This can be demonstrated by this example:
#include <stdio.h>
union job { //defining a union
char name[32];
float salary;
int worker_no;
}u;
struct job1 {
char name[32];
float salary;
int worker_no;
}s;
int main(){
printf("size of union = %d",sizeof(u));
printf("\nsize of structure = %d", sizeof(s));
return 0;
}
Output

size of union = 32

size of structure = 40
There is difference in memory allocation between union and structure as suggested in above example. The
amount of memory required to store a structure variables is the sum of memory size of all members.

But, the memory required to store a union variable is the memory required for largest element of an union.

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 62


AN INTRODUCTION TO C LANGUAGE

What difference does it make between structure and union?


As you know, all members of structure can be accessed at any time. But, only one member of union can be
accessed at a time in case of union and other members will contain garbage value.

#include <stdio.h>

union job {

char name[32];

float salary;

int worker_no;

}u;

int main(){

printf("Enter name:\n");

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

printf("Enter salary: \n");

scanf("%f",&u.salary);

printf("Displaying\nName :%s\n",u.name);

printf("Salary: %.1f",u.salary);

return 0;

}
Output

Enter name

Hillary

Enter salary

1234.23

Displaying

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 63


AN INTRODUCTION TO C LANGUAGE

Name: f%Bary

Salary: 1234.2
Note: You may get different garbage value of name.
Why this output?
Initially, Hillary will be stored in u.name and other members of union will contain garbage value. But when
user enters value of salary, 1234.23 will be stored in u.salary and other members will contain garbage value.
Thus in output, salary is printed accurately but, name displays some random string.
Passing Union To a Function
Union can be passed in similar manner as structures in C programming. Visit this page to learn more
about: How structure can be passed to function in C programming?
◄ Previous Page
C Programming Structure Examples
This page contains examples and source code on structures in C programming language. To
understand all examples in this page, you should have knowledge of following structure topics.
1. Structure Introduction
2. Structure and Pointers
3. Passing Structure to Function

Example of Structures in C Programming

C Programming Examples and Source Code

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


C Program to Add Two Distances (in inch-feet) System Using Structures
C Program to Add Two Complex Numbers by Passing Structure to a Function
C Program to Calculate Difference Between Two Time Period
C Program to Store Information of 10 Students Using Structure
C Program to Store Information Using Structures for n Elements Dynamically
C Programming Files I/O
In C programming, file is a place on disk where a group of related data is stored.

Why files are needed?


When the program is terminated, the entire data is lost in C programming. If you want to keep large
volume of data, it is time consuming to enter the entire data. But, if file is created, these information
can be accessed using few commands.
There are large numbers of functions to handle file I/O in C language. In this tutorial, you will learn
to handle standard I/O(High level file I/O functions) in C.
High level file I/O functions can be categorized as:
1. Text file
2. Binary file

File Operations
1. Creating a new file
2. Opening an existing file
3. Reading from and writing information to a file
4. Closing a file
Working with file
While working with file, you need to declare a pointer of type file. This declaration is needed for
communication between file and program.

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 64


AN INTRODUCTION TO C LANGUAGE

FILE *ptr;
Opening a file
Opening a file is performed using library function fopen(). The syntax for opening a file in standard
I/O is:

ptr=fopen("fileopen","mode")

For Example:

fopen("E:\\cprogram\program.txt","w");

/* --------------------------------------------------------- */

E:\\cprogram\program.txt is the location to create file.

"w" represents the mode for writing.

/* --------------------------------------------------------- */
Here, the program.txt file is opened for writing mode.

Opening Modes in Standard I/O

File Mode Meaning of Mode During Inexistence of file

If the file does not exist, fopen() returns


r Open for reading. NULL.
If the file exists, its contents are overwritten.
w Open for writing. If the file does not exist, it will be created.
Open for append. i.e, Data
a is added to end of file. If the file does not exists, it will be created.
Open for both reading and If the file does not exist, fopen() returns
r+ writing. NULL.
Open for both reading and If the file exists, its contents are overwritten.
w+ writing. If the file does not exist, it will be created.
Open for both reading and
a+ appending. If the file does not exists, it will be created.

Closing a File
The file should be closed after reading/writing of a file. Closing a file is performed using library
function fclose().

fclose(ptr); //ptr is the file pointer associated with file to be closed.

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 65


AN INTRODUCTION TO C LANGUAGE

The Functions fprintf() and fscanf() functions.


The functions fprintf() and fscanf() are the file version of printf() and fscanf(). The only difference
while using fprintf() and fscanf() is that, the first argument is a pointer to the structure FILE
Writing to a file

#include <stdio.h>
int main()
{
int n;
FILE *fptr;
fptr=fopen("C:\\program.txt","w");
if(fptr==NULL){
printf("Error!");
exit(1);
}
printf("Enter n: ");
scanf("%d",&n);
fprintf(fptr,"%d",n);
fclose(fptr);
return 0;
}
This program takes the number from user and stores in file. After you compile and run this program,
you can see a text file program.txt created in C drive of your computer. When you open that file, you
can see the integer you entered.
Similarly, fscanf() can be used to read data from file.
Reading from file

#include <stdio.h>
int main()
{
int n;
FILE *fptr;
if ((fptr=fopen("C:\\program.txt","r"))==NULL){
printf("Error! opening file");
exit(1); /* Program exits if file pointer returns NULL. */
}
fscanf(fptr,"%d",&n);
printf("Value of n=%d",n);
fclose(fptr);
return 0;
}
If you have run program above to write in file successfully, you can get the integer back entered in
that program using this program.
Other functions like fgetchar(), fputc() etc. can be used in similar way.

Binary Files
Depending upon the way file is opened for processing, a file is classified into text file and binary
file.
If a large amount of numerical data it to be stored, text mode will be insufficient. In such case binary
file is used.
Working of binary files is similar to text files with few differences in opening modes, reading from
file and writing to file.

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 66


AN INTRODUCTION TO C LANGUAGE

Opening modes of binary files


Opening modes of binary files are rb, rb+, wb, wb+,ab and ab+. The only difference between opening
modes of text and binary files is that, b is appended to indicate that, it is binary file.
Reading and writing of a binary file.
Functions fread() and fwrite() are used for reading from and writing to a file on the disk respectively
in case of binary files.
Function fwrite() takes four arguments, address of data to be written in disk, size of data to be
written in disk, number of such type of data and pointer to the file where you want to write.

fwrite(address_data,size_data,numbers_data,pointer_to_file);
Function fread() also take 4 arguments similar to fwrite() function as above.
C Programming File Examples

Examples of files in C Programming

C Program to read name and marks of students and store it in file


C Program to read name and marks of students and store it in file. If file already exists, add
information to it.
C Program to write members of arrays to a file using fwrite()
Write a C program to read name and marks of n number of students from user and store them
in a file

#include <stdio.h>
int main(){
char name[50];
int marks,i,n;
printf("Enter number of students: ");
scanf("%d",&n);
FILE *fptr;
fptr=(fopen("C:\\student.txt","w"));
if(fptr==NULL){
printf("Error!");
exit(1);
}
for(i=0;i<n;++i)
{
printf("For student%d\nEnter name: ",i+1);
scanf("%s",name);
printf("Enter marks: ");
scanf("%d",&marks);
fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);
}
fclose(fptr);
return 0;
}
Write a C program to read name and marks of n number of students from user and store them
in a file. If the file previously exits, add the information of n students.

#include <stdio.h>
int main(){
char name[50];
int marks,i,n;
printf("Enter number of students: ");
scanf("%d",&n);
FILE *fptr;

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 67


AN INTRODUCTION TO C LANGUAGE

fptr=(fopen("C:\\student.txt","a"));
if(fptr==NULL){
printf("Error!");
exit(1);
}
for(i=0;i<n;++i)
{
printf("For student%d\nEnter name: ",i+1);
scanf("%s",name);
printf("Enter marks: ");
scanf("%d",&marks);
fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);
}
fclose(fptr);
return 0;
}
Write a C program to write all the members of an array of strcures to a file using fwrite().
Read the array from the file and display on the screen.

#include <stdio.h>
struct s
{
char name[50];
int height;
};
int main(){
struct s a[5],b[5];
FILE *fptr;
int i;
fptr=fopen("file.txt","wb");
for(i=0;i<5;++i)
{
fflush(stdin);
printf("Enter name: ");
gets(a[i].name);
printf("Enter height: ");
scanf("%d",&a[i].height);
}
fwrite(a,sizeof(a),1,fptr);
fclose(fptr);
fptr=fopen("file.txt","rb");
fread(b,sizeof(b),1,fptr);
for(i=0;i<5;++i)
{
printf("Name: %s\nHeight: %d",b[i].name,b[i].height);
}
fclose(fptr);
C Programming Enumeration
An enumeration is a user-defined data type consists of integral constants and each integral constant
is give a name. Keyword enum is used to defined enumerated data type.

enum type_name{ value1, value2,...,valueN };


Here, type_name is the name of enumerated data type or tag. And value1, value2,....,valueN are
values of type type_name.
By default, value1 will be equal to 0, value2 will be 1 and so on but, the programmer can change the
default value.

// Changing the default value of enum elements

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 68


AN INTRODUCTION TO C LANGUAGE

enum suit{

club=0;

diamonds=10;

hearts=20;

spades=3;

};

Declaration of enumerated variable


Above code defines the type of the data but, no any variable is created. Variable of type enum can be
created as:

enum boolean{

false;

true;

};

enum boolean check;


Here, a variable check is declared which is of type enum boolean.
Example of enumerated type
#include <stdio.h>
enum week{ sunday, monday, tuesday, wednesday, thursday, friday, saturday};
int main(){
enum week today;
today=wednesday;
printf("%d day",today+1);
return 0;
}
Output

4 day
You can write any program in C language without the help of enumerations but, enumerations helps
in writing clear codes and simplify programming.
C Programming Preprocessor and Macros
Preprocessor extends the power of C programming language. Line that begin with # are called
preprocessing directives.

Use of #include
Let us consider very common preprocessing directive as below:

#include <stdio.h>
Here, "stdio.h" is a header file and the preprocessor replace the above line with the contents of
header file.

Use of #define
Preprocessing directive #define has two forms. The first form is:
INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 69
AN INTRODUCTION TO C LANGUAGE

#define identifier token_string


token_string part is optional but, are used almost every time in program.
Example of #define

#define c 299792458 /*speed of light in m/s */


The token string in above line 2299792458 is replaced in every occurance of symbolic constant c.
C Program to find area of a cricle. [Area of circle=πr 2]
#include <stdio.h>
#define PI 3.1415
int main(){
int radius;
float area;
printf("Enter the radius: ");
scanf("%d",&radius);
area=PI*radius*radius;
printf("Area=%.2f",area);
return 0;
}
Output

Enter the radius: 3

Area=28.27

Syntactic Sugar
Syntactic sugar is the alteration of programming syntax according to the will of programmer. For
example:

#define LT <
Every time the program encounters LT, it will be replaced by <.
Second form of preprocessing directive with #define is:

Macros with argument


Preprocessing directive #define can be used to write macro definitions with parameters as well in the
form below:

#define identifier(identifier 1,.....identifier n) token_string


Again, the token string is optional but, are used in almost every case. Let us consider an example of
macro definition with argument.

#define area(r) (3.1415*(r)*(r))


Here, the argument passed is r. Every time the program encounters area(argument), it will be
replace by (3.1415*(argument)*(argument)). Suppose, we passed (r1+5) as argument then, it
expands as below:

area(r1+5) expands to (3.1415*(r1+5)*(r1+5))


C Program to find area of a circle, passing arguments to macros. [Area of circle=πr 2 ]
#include <stdio.h>
#define PI 3.1415
#define area(r) (PI*(r)*(r))
int main(){
int radius;
float area;
INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 70
AN INTRODUCTION TO C LANGUAGE

printf("Enter the radius: ");


scanf("%d",&radius);
area=area(radius);
printf("Area=%.2f",area);
return 0;
}

Predefined Macros in C language

Predefined macro Value

__DATE__ String containing the current date


__FILE__ String containing the file name
__LINE__ Integer representing the current line number
__STDC__ If follows ANSI standard C, then value is a nonzero integer
__TIME__ String containing the current date.

How to use predefined Macros?


C Program to find the current time
#include <stdio.h>
int main(){
printf("Current time: %s",__TIME__); //calculate the current time
}
Output

Current time: 19:54:39

INTRODUCTION TO C LANGUAGE BRIJESH KUMAR SINGH (MOB: -9891428723) 71

You might also like