Chapter One Overview of the Programming Languages A programming language is a special language which programmers use to develop software programs. The following is a list of major programming languages which are in use today. Choice of a programming language depends on your experience and the application which you want to address. Most of the time more than one programming languages are used for developing a single program/ software. What is C Language
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Chapter One
Overview of the Programming Languages
A programming language is a special language which programmers use to develop software
programs. The following is a list of major programming languages which are in use today.
Choice of a programming language depends on your experience and the application which you
want to address. Most of the time more than one programming languages are used for
developing a single program/ software.
What is C Language
C is most widely used general-purpose, powerful programming language which is very
procedural and imperative in nature. Dennis M. Ritchie of Bell Telephone Laboratories,
developed C in 1972 to produce the UNIX operating system.
Brian Kernighan and Dennis Ritchie in 1978 gave the first publicly available description of C
which is known as K&R standard.
C language has been used to write UNIX OS, UNIX applications and C language compiler. C is
now a most widely used professional language.Some of its core features are−
Easy to learn and understand
It is a structured language
It produces fast and efficient programs
It can handle low-level activities easily
It can be compiled on many types of computer platforms
Why C Language
C language was initially used for developing the operating systems because code of C language
can run as fast as an assembly language code. Some major uses of C language are –
Operating Systems
Text Editors
Language Compilers
Print Spoolers
Assemblers
Network Drivers
Databases
Modern Programs
Language Interpreters
Utilities
Future in C Language
C is a fundamental language which you need to understand to get a firm grip on any other
programming languages. C is still a better option for programming device drivers, utility
programs and embedded applications.
Prerequisite in C Language
To use this tutorial at full advantage user should have full command over Computer
Programming terminologies. A brief prior understanding of any programming language will
make your learning easier.
Audience
This tutorial is for beginners and those who have intermediate understanding of computer
programming. This tutorial will guide you to fully understand the C programming language
which is essential for developing higher level of expertise.
Setting up and Installing C Language
To setup C Programming language environment on you PC you need to have a Text Editor and
the compiler.
Text Editor
Text editor tool is used for typing programs. Windows Notepad, Brief, OS Edit command,
Epsilon, vim or vi and EMACS are some commonly used text editors. Notepadtext editor is
specific for windows while vim or vi is useable on windows, Linux and Unix.
C language code is initially written in text editor programs. This code is also called source code.
The source files for C programsgenerally have the extension ".c".
You can easily edit, review and revise your code in text editors. after finalizing your program in
the text editor you just need to compile and execute it to produce the desired results.
The Compiler
CPU only understands machine language. Compiler converts the human readable source code
into machine language.
The role of compiler is to produce final executable programs from the source code. The free
and most common compiler is the GNU C compiler, otherwise compilers made by HP or Solaris
are also available for their respective operating systems.
Steps to install GNU C compiler on various operating systems are described below.
Installation on UNIX/Linux
On most of the Linux or UNIX systems, GCC is already installed. If GCC is not installed on your
computer then you can install it by yourself using the detailed instructions from the following
link http://gcc.gnu.org/install/
Installation on Mac OS
Mac OS X users can download Xcode development environment from Apple's web site
at developer.apple.com/technologies/tools/. Follow the given installation instructions. After
getting the Xcode setup, GNU compiler for C/C++ can be used.
Installation on Windows
First of all install MinGW. Go to homepage of MinGW, www.mingw.org, and download MinGW
To specify these tools on the command line by their simple names just add the bin subdirectory
of MinGW setup to PATH environment variable.
After completing the installation, GNU tools can be easily run from the Windows command line.
Data Type, Constants & Variables
What is Data Types in C Language
Data types specify the characteristics of data which is used by variables and functions in a C
Language program. There are many data types in C language which are described below. Data
type of a variable describes how much space this variable takes and how its bit patterns are
interpreted by the computer.
Integers, long and short in C Language
Int data type is used to specify integers. Standard int data type has 2-4 byte size while short and long int
data types have sizes of 2 and 4 bytes respectively. Short int data type is used for storing small values
and long int data type is used for storing large values. Standard integer data types according to size are
stated below.
Data type Range of values Storage size on memory
int From -32,768 to 32,767 or from -2,147,483,648 to 2,147,483,647
2 or 4 bytes
short From -32,768 to 32,767 2 bytes
long From -2,147,483,648 to 2,147,483,647 4 bytes
Integers, signed and unsigned in C Language
Standard integer data types according to signs are stated below.
Data type Range of values Storage size on memory
signed int From -32,768 to 32,767 or from -2,147,483,648 to 2,147,483,647
2 or 4 bytes
unsigned int From 0 to 65,535 or from 0 to 4,294,967,295 2 or 4 bytes
signed short From -32,768 to 32,767 2 bytes
unsigned short From 0 to 65,535 2 bytes
signed long From -2,147,483,648 to 2,147,483,647 4 bytes
unsigned long From 0 to 4,294,967,295 4 bytes
Chars, signed and unsigned in C Language with practical
Standard character data types according to sign are stated below.
Data type Range of values Storage size on memory
char From -128 to 127 or 0 to 255 1 byte
unsigned char From 0 to 255 1 byte
signed char From -128 to 127 1 byte
Floats and Doubles in C Language with practical
Details of standard floating-point types with storage sizes and value ranges and their precision
are stated below.
Data type Range of values Storage size on memory Precision (decimal size)
Float From 1.2E-38 to 3.4E+38 4 byte 6
double From 2.3E-308 to 1.7E+308 8 byte 15
long double From 3.4E-4932 to 1.1E+4932 10 byte 19
The header file float.h is used to define macros which facilitate the use of float, long and
double values.
We can use the following program to check the storage space taken up by a float data type and
its range of values
#include <stdio.h> #include <float.h> int main() { printf("size of float data type : %d \n", sizeof(float)); printf("Minimum size of positive value of float: %E\n", FLT_MIN ); printf("Maximum size of positive value of float: %E\n", FLT_MAX ); printf("Precision of the value: %d\n", FLT_DIG ); return 0; }
After compiling and executing this program, it will produce the following results on Linux −
Size of float data type : 4
Minimum size of positive value of float: 1.175494E-38
Maximum size of positive value of float: 3.402823E+38
Precision of the value: 6
To check the exact memory size of a data type or any variable in C, sizeof operator can be
used. The standard syntax sizeof(type) is used to determine theexact memory storage size of a
data type or variable in bytes. Following program is used to get the size of int type.
#include <stdio.h> #include <limits.h> int main() { printf("size of int data type : %d \n", sizeof(int)); return 0; }
After compiling and executing this program, it will produce the following results on Linux −
size of int data type : 4
Constants in C
Fixed values which are mostly used un-changed in C programs are called constants or literals.
Constants can belong to any data type-
Integer constant
Floating constant
Character constant etc.
In C Language, Constants are used as variables. The only difference between variables and
constants is that once defined, value of constant cannot be changed.
Major categories of constants are stated below.
Integer constant
It is a number belonging to any of the decimal, hexadecimal and octal number systems. Prefix
is used to specify the base of the number; 0 is used for octal and 0x is used for hexadecimal.
The suffix of a constant can be a combination of unsigned (U) and long (L). Order of the
suffixes does not matter. The suffix can be uppercase or lowercase.
Here are some examples of integer constants −
454 Legal value 433u Legal value 4xFeeL Legal value 048 Illegal value because 8 can not be octal value 044UU Illegal value we cannot repeat any suffix
Floating-point constants
A floating-point consists of an integer, decimal, fraction, and/or an exponent. Floating point
literals can be inexponential form or decimal form.
For decimal form, the decimal point, the exponent, or both must be included; and for
presenting exponential form, integer part, the fractional part, or both must be included. The
signed exponent is presented by e.
Some floating-point constants are stated below −
6.76954 Legal value 343349E7L Legal value 452E Illegal value;exponent is incomplete 454f Illegal value; decimal or exponent is not there .e545 Illegal value; integer part missing
Character Constants
Character constants are alphabets and they are represented by using single quotes, e.g. 'a'.
A character constant can be in the form ofa single character, a universal character, or an
escape sequence (e.g., '\n').
Escape sequence characters are characters with backslash which are mostly used for
formatting purposes. Following program illustrates the use of escape sequences. −
#include <stdio.h>
int main() {
printf("Happy\tbirthday\n\n");
return 0;
}
On compiling and executing, this code produces the following result –
Happy birthday
String constants
String constants are bundles of single characters. String characters are represented by double
quotes "". A string can also containescape sequences and universal characters.
Using string constants, long line of text can be broken into multiple lines and words can be
separated with spaces.
An examples of string constant are stated below.
#include<stdio.h>
int main()
{
printf("Happy\tbirthday");
return(0);
}
On compiling and executing the program you will get the below output.
Happy birthday
Defining Constants
User can define constants in C language. There are two easy methods to define constants in C−
#define preprocessor directive
const keyword
The #define Preprocessor
To define a constant using #define Preprocessor, following syntax is used−
#define identifier
The below program illustrates this -
#include <stdio.h>
#define l 5
#define w 8
#define NEWLINEOFTEXT '\n'
int main() {
int rectanglearea;
rectanglearea = l * w;
printf("Area of rectangle is: %d", rectanglearea);
printf("%c", NEWLINEOFTEXT);
return 0;
}
On compiling and executing the above program, it produces the below result −
Area of rectangle is : 40
The const Keyword
Constants of a specific data type are declared by using const keyword −
const type variable = value;
The below program illustrates this −
#include <stdio.h>
int main() {
const int l= 5;
const int w = 8;
const char NEWLINEOFTEXT = '\n';
int rectanglearea;
rectanglearea = l * w;
printf("Area of rectangle is: %d", rectanglearea);
printf("%c", NEWLINEOFTEXT);
return 0;
}
On compiling and executing the above program, it produces the below result −
Area of rectangle is : 40
Variables in C
A variable is a memory location on the hard disk of a computer. Every variable has its own data
type which describes the size of memory associated with the variable, range of values which a
variable holds and operations which can be used with the variable.
Variable name can consist of alphabets, numbers, and the underscore. It must start with either
an alphabet or the underscore. Mostly lower case letters areused to name the variables. Keep
in mind that C is a case sensitive language. Following are the fundamental types of variables –
Data Type Description
char Generally it represents character or alphabet.
int It represents an integer.
float It represents a decimal point value.
double It represents a double-precision floating point decimal value.
void It indicates that there is no type assigned to any variable.
In C language other types of variables can also be defined which we will discuss in next
When you define the variable you tell the compiler how much space is allocated to this
variable and where this variable is located. For this purpose, data type is used. In C language
following syntax is used to declare variable(s)-
Data type variablename;
To declare more than one variables of same data type they are separated by commas. Some
examples are shown below -
int a, b, c; char d, e; float f, g; double h;
Initializing a variable means assigning a value (mostly numerical) to a variable in declaration.
“Equal to’’ sign is used to assign any constant to a variable. As illustrated below -
type variablename = any value;
Some examples are as follows −
extern int a = 2, b = 3; declaring of and b variables. int a = 2, b = 3; defining and initializing a and b variables. byte c = 4; defining and initializing c. char i = 'i'; the value 'i' is given to variable i
variables which are not initialized while declaration have null initial values.
Declaring a variable in C
Where used, variable declaration serves as a statement for compiler that there is a variable(s)
and compiler moves on for further compilation without going into the definition of the
variable. Compiler accesses the definition of variable only for linking the program.
Although a variable can be declaredmultiple times in a C program, it is defined only one time in
a file, a function, or a block of code.
In the below example, variables are declared at top, but are defined and initialized in the main
function body-
#include <stdio.h>
// Declaring a variable:
extern int x, y;
extern int z;
extern float a;
int main () {
/* defining the variable */
int x, y;
int c;
float a;
/* actual initialization */
x = 5;
y = 7;
c = x + y;
printf("The value of z : %d \n", c);
a = 60.0/16.0;
printf("The value of a : %f \n", a);
return 0;
}
When the above code is compiled and executed, it produces the following result −
The value of z : 12
The value of a : 3.75
Keywords in C
Keywords are predefined or built-in words whose meaning is already known to compiler. We cannot
use keywords as Variable Name. There are 32 Keywords in C language. They are also known
as reserved words. All the keywords are described below.
Auto
The auto keyword is used to declare automatic variables. Its standard syntax is as follows-
auto int variablename;
Variables which are declared within a function are by default automatic. It means that these variables are recreated every time a function is executed.
As automatic variables operate within a function, they are also known as local variables.
break and continue
The break keyword is used to make unconditional exit from any inner loop or function in a C program.
The continue statement is used to skip some statements in a loop. Following example illustrates this -
#include <stdio.h>
int main() {
int a;
for (a=1;a<=5;++a)
{
if (a==3)
continue;
if (a==4)
break;
printf("%d ",a);
}
return 0;
}
Output of this program is –
1 2
switch, case and default
we use switch and case statement when a certain block of statements is to be executed among many blocks of the programming code. For example:
#include <stdio.h>
int main()
{
int number=5;
switch(number+5)
{
case 1:
printf(" Value of number is: %d", number);
case 2:
printf(" Value of number is: %d", number);
case 3:
printf(" Value is: %d", number);
default:
printf("Default: Value of number is: %d", number);
}
return 0;
}
Output of this program would be-
Default: Value of number is: 5
char
The char keyword is used to declare a character variable. For example-
char variablename;
const
By using const keyword any identifier can be declared as constant.
const int i = 7;
do...while
do and while keywords are used in do-while loops. This will be described in next chapters.
#include <stdio.h>
int main() {
int a;
do
{ printf("%d ",a);
a++;
}
while (a<5);
return 0;
}
Output of this program will be –
0 1 2 3 4
double and float
For declaring floating type variables keywords double and float are used. For example-
float variablename;
double long variablename;
if and else
In C programming, if and else are conditional operators and they are used to make decisions.
#include <stdio.h>
int main() {
int a;
if (a == 5)
printf("a is 5.");
else
printf("a is not 5.");
return 0;
}
If value of a is other than 5 , output will be :
a is not 5
enum
Enumeration types are declared by using keyword enum. We will discuss enumeration types in next chapters. Its example is –
#include <stdio.h>
enum person { a, b, c, d, e, f, g };
int main()
{ enum person today;
today = c;
printf("person %d",today+1);
return 0;
}
Output of this program is-
person 3
extern
The extern keyword is used to declare the external link of a variable or function with other variables or functions outside the parent file.
for
for keyword is used to run the for loop in C programming. For example-
#include <stdio.h>
int main() {
int a;
for (a=0; a< 5;++a)
{ printf("%d ",a);
} return 0;
}
Output of this program would be as follows-
0 1 2 3 4
goto
The goto keyword serves as a shortcut to jump to a pre-labeled variable or statement in a function.For example-
#include <stdio.h>
int main() {
int a;
for(a=1; a<5; ++a)
{
if (a==11)
goto error;
}
printf("a is not 11");
error:
printf("Error, count value cannot be 11.");
return 0;
}
On compiling and executing, output of this program is as follows-
Error, count value cannot be 11.
int
The int keyword is used to declare integer type variables. For example-
int variablename;
short, long, signed and unsigned
The short, long, signed and unsigned keywords are known as type modifiers which alter the meaning of base data type to produce a new type.
short int smallvalueInteger;
long int bigvalueInteger;
signed int normalvalueInteger;
unsigned int positivevalueInteger;
return
The return keyword is used to terminate the function and return a value.
#include<stdio.h>
float perimeter(int);
int main()
{
int rad;
float peri;
printf("\nProvide radius of circle : ");
scanf("%d",&rad);
peri= perimeter(rad);
printf("\nperimeter of Circle : %f ",peri);
return(0);
}
float perimeter(int rad)
{
double circleperimeter;
circleperimeter=2*3.14*rad;
return(circleperimeter);
}
This program returns the following output-
Provide radius of circle :
perimeter of Circle : 0.000000
sizeof
The sizeof keyword is used to check the size of data (a variable or a constant).
#include <stdio.h>
int main()
{
printf("%u bytes.",sizeof(float));
}
On compiling and executing, output of this program is as follows-
4 bytes.
register
The register keyword is used to create register variables. Register variables work faster than normal variables of C program.
register char variablename;
static
The static keyword is used to create static variable. The value of the static variables remains til the end of program. For example-
static int variablename;
struct
The struct keyword is used for declaring a structure in C language. A structure has a single label and it can hold many variables of different nature in its body.
#include <stdio.h>
#include <string.h>
struct employee
{
int employeeid;
char nameofemployee[20];
float percent;
};
int main()
{
struct employee record = {0}; //Initializing to null
record.employeeid=1;
strcpy(record.nameofemployee, "jhon");
record.percent = 86.5;
printf(" Id is: %d \n", record.employeeid);
printf(" Name: %s \n", record.nameofemployee);
printf(" Percent: %f \n", record.percent);
return 0;
}
Output-
Id is: 1
Name: jhon
Percent: 86.500000
typedef
The typedef keyword explicitly associates a type with an identifier.
#include<stdio.h>
int main()
{
typedef int calculation;
calculation number1 = 50,number2 = 60;
calculation ans;
ans = number1 + number2;
printf("ans : %d",ans);
return(0);
}
Output-
ans : 110
union
A Union keyword groups different types of variables under a single name.
#include <stdio.h>
#include <string.h>
union material {
int a;
float b;
char str[30];
};
int main( ) {
union material data;
printf( "Memory of data : %d\n", sizeof(data));
return 0;
}
Output-
Memory of data : 32
void
The void keyword is used to indicate that a function doesn't return a value.
void Function(int i)
volatile
For creating volatile objects in C Language volatile keyword is used. A volatile object can be modified in an unspecified manner by hardware.
const volatile numeric
How to get input from user
In C language input can be given in the form of a file or command. It has a set of built-in functions
which read the given input and insert it into the program where required.
The getchar() function
The getchar() function reads the very next character which is available on the screen and return
an integer value. This function can read only single character at once. In order to read more than
one character from the screen, use this function with loop. Following example illustrates its use−
#include <stdio.h>
int main()
{
int a;
printf("enter any key: ");
getchar();
a = 'H';
putchar(a);
a = 'i';
putchar(a);
putchar('!');
return(0);
}
On compiling and executing, this program waits for input text from user. On entering the text, output of this program is as follows-
enter any key: Hi!
The gets() function
It is also an input function. The gets() function is used to read a line from stdin (standard input). For
example-
#include <stdio.h>
int main( ) {
char str[100];
printf( "Please Enter any value :");
gets( str );
printf( "\n Entered value is : ");
puts( str );
return 0;
}
On compiling and executing, this program waits for input text from user. On entering the text, output of this program is as follows-
Please Enter any value : suppose you enter c language
Entered value is : c language
The scanf() function
The scanf() function is used to read the input from the stdin (standard input) and it accepts the
provided input only in given format.
The format can be of many types e.g. %s, %d, %f, etc., for reading strings, integer or float
respectively. Many other formats are also found in C. following example illustrates the concept
-
#include <stdio.h>
int main( ) {
char str[100];
int a;
printf( "Please Enter a value :");
scanf("%s %d", str, &a);
printf( "\n Entered value is : %s %d ", str, a);
return 0;
}
On compiling and executing, this program waits for input text from user. On entering the text, output of this program is as follows-
Please Enter a value: suppose you enter one 1
Entered value is : one 1
It is important to note that scanf() accepts inputs only in the prescribed format. If you provide
input in any other format which is not specified in scanf() it will consider it as a wrong input.
Secondly, scanf() terminates to read the string if space is encountered.
How to display output to user with practical
In C language output can be produced on screen or in the form of any file. It has a set of built-in
functions which produce the given output and save it in text or machine code files.
The putchar() function
The putchar() function is used to display the input character on the screen. This function returns
the same character which is displayed. This function can read only single character at once. In
order to read more than one character from the screen use this function with loop. following
example illustrates its use−
#include <stdio.h>
int main()
{
int a;
printf("enter any key: ");
getchar();
a = 'H';
putchar(a);
a = 'i';
putchar(a);
putchar('!');
return(0);
}
On compiling and executing, this program waits for input text from user. On entering the text, output of this program is as follows-
enter any key: Hi!
The puts() function
It is also an output function in C. The puts() function is used to display output on screen. For
example -
#include <stdio.h>
int main( ) {
char str[100];
printf( "Please Enter any value :");
gets( str );
printf( "\n Entered value is : ");
puts( str );
return 0;
}
On compiling and executing, this program waits for input text from user. On entering the text, output of this program is as follows-
Please Enter any value : suppose you enter c language
Entered value is : c language
The printf() function
The printf() function is used to display the output to the stdout (standard output ). it is used to
produce output onlyin the prescribed format.
The format can be of many types e.g. %s, %d, %f, etc., for readingstrings, integer or float
respectively. Many other formatsare also found in C. following example illustrates the concept
-
#include <stdio.h>
int main( ) {
char str[100];
int a;
printf( "Please Enter any value :");
scanf("%s %d", str, &a);
printf( "\n Entered value is: %s %d ", str, a);
return 0;
}
On compiling and executing, this program waits for input text from user. On entering the text, output of this program is as follows-
Please Enter any value : suppose you enter three 3
Entered value is : three 3
It is important to note that print() accepts inputs only in the prescribed format. If you provide
input in any other format which is not specified in printf() it will consider it as a wrong input.
Chapter Two
Statement
In C Language statements are the specific commands for the computer to take actions. Actions
can be of many types e.g. displaying output on the screen and taking input from the user. A C
Program is a bundle of statements. C statements can be any of the following types
Simple Statements
Variable definition, initialization and declaration are examples of simple statements.
Simple statements are terminated by semi-colon. return, break, continue, and goto are
also some examples of simple statements.
Compound Statements
Compound statements are of two types; conditional statements and iterative
statements. Conditional statements are used for making decisions and iterative
statements are used for repeatedly executing a set of statements.
Major statements are described below.
IF-Else Statement
If and if-else statements are conditional operators. They are used to make decisions in C
programs by using Boolean expressions. There are three major variations of IF statements
Simple IF Statement
If statement contains a Boolean expression and if this expression becomes true,
a set of statements under the IF are executed.
IF-IF statement
It is used to make multiple decisions by using multiple decision making Boolean
expressions.
IF – ELSE statement
It is also used for making multiple decisions. When IF statement becomes false
the else statement is executed.
Nested IF statement
We can place many IF and IF-ELSE statements inside an IF statements
depending on the requirements. Nested IF statement is used to make multiple
decisions on a value on the basis of more than one if statements.
This program displays a negative number using IF statement. If user enters positive number
output will not be displayed
#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d", &number);
// Test expression is true if number is less than 0
if (number < 0)
{
printf("You entered %d.\n", number);
}
printf("The if statement is easy.");
return 0;
}
On compiling and executing the program you will get the below output.
Enter an integer: -2
You entered -2.
The if statement is easy.
This program takes a number from the user and displays whether it is even or odd number using IF-ELSE.
#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d",&number);
// True if remainder is 0
if( number%2 == 0 )
printf("%d is an even integer.",number);
else
printf("%d is an odd integer.",number);
return 0;
}
On compiling and executing the program you will get the below output.
Enter an integer: 7
7 is an odd integer.
This program is used to check equality and inequality of two numbers using nested IF.
32
On compiling and executing the program you will get the below output.
Enter two integers: 12
23
Result: 12 < 23
for Loop
In C language Loops are used to repeat a set of statements multiple times. Loops use a conditional expression to repeatedly execute various statements. The statements are executed until the condition remains true. When condition becomes false, the loop stops. The standard syntax of for loop in C programming is
for (variable initialization; conditional Expression; variable update statement)
{
// body of loop
}
Following program is used to add n natural numbers using for loop.
#include <stdio.h>
int main()
{
int num, count, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &num);
// for loop terminates when n is less than count
for(count = 1; count <= num; ++count)
{
sum += count;
}
printf("Sum = %d", sum);
return 0;
}
On compiling and executing the program you will get the below output.
Enter a positive integer: 10
Sum = 55
While Loop
While loop is used to repeatedly execute a block of code by satisfying a conditional expression which is there at the starting point of the loop. While loop can repeat as many times as required until the conditional expression remains true. It can also act as an infinite loop. The standard syntax of while loop in C programming is
while (conditional Expression)
{
// body of loop
}
While loop first executes the conditional expression and body of loop is repeatedly executed until the condition remains true. Following program is used to calculate factorial of a number using while loop.
#include <stdio.h>
int main()
{
int number;
longlong factorial;
printf("Enter an integer: ");
scanf("%d",&number);
factorial = 1;
// loop terminates when number is less than or equal to 0
On compiling and executing the program you will get the below output.
Enter an integer: 5
Factorial = 120
Do-While Loop
Body of loop is executed once without any judgment and at end of loop body conditional expression is executed and body of loop is repeatedly executed until the condition remains true. Do-while loop differs from while loop on the location of conditional expression, in while loop condition is at start and in do-while loop condition is at end of the loop. The standard syntax of do-while loop in C programming is
do
{
// body of loop
}
while (conditional Expression);
Following program is used for adding numbers. Addition is stopped when user enters zero.
#include <stdio.h>
int main()
{
double number, sum = 0;
// loop body is executed at least once
do
{
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
}
while(number != 0.0);
printf("Sum = %.2lf",sum);
return 0;
}
On compiling and executing the program you will get the below output.
Enter a number: 1.5
Enter a number: 2.4
Enter a number: -3.4
Enter a number: 4.2
Enter a number: 0
Sum = 4.70
Break
It is used for controlling a loop. It is used to terminate a loop statement and control is shifted to any statement which is next to the loop statement. The standard syntax of break in C programming is
break;
The program mentioned below is used to calculate sum until user enters positive numbers. This program
uses break statement.
# include <stdio.h>
int main()
{
int i;
double number, sum = 0.0;
for(i=1; i <= 10; ++i)
{
printf("Enter a n%d: ",i);
scanf("%lf",&number);
// If user enters negative number, loop is terminated
if(number < 0.0)
{
break;
}
sum += number; // sum = sum + number;
}
printf("Sum = %.2lf",sum);
return 0;
}
On compiling and executing the program you will get the below output.
Enter a n1: 2.4
Enter a n2: 4.5
Enter a n3: 3.4
Enter a n4: -3
Sum = 10.30
Continue
It is also used for controlling a loop. It is used to skip a set of statements inside a loop. It is commonly used with conditional expressions e.g. if, else. The standard syntax of continue in C programming is
continue;
The program mentioned below is used to calculate sum until user enters positive numbers and it skips
negative numbers. This program uses continue statement.
# include <stdio.h>
int main()
{
int i;
double number, sum = 0.0;
for(i=1; i <= 10; ++i)
{
printf("Enter a n%d: ",i);
scanf("%lf",&number);
// If user enters negative number, loop is terminated
if(number < 0.0)
{
continue;
}
sum += number; // sum = sum + number;
}
printf("Sum = %.2lf",sum);
return 0;
}
On compiling and executing the program you will get the below output.
Enter a n1: 1.1
Enter a n2: 2.2
Enter a n3: 5.5
Enter a n4: 4.4
Enter a n5: -3.4
Enter a n6: -45.5
Enter a n7: 34.5
Enter a n8: -4.2
Enter a n9: -1000
Enter a n10: 12
Sum = 59.70
Switch
Switch is also a decision making operator. It is preferred when a single variable is going to have a set of values. The expression used in the switch should produce a numeric value. The standard syntax of switch in C programming is
switch (expression)
{
case anyconstantnumber1:
//body of case1;
break;
case anyconstantnumber:
//body of case2;
break;
.
.
.
default:
// body of default which is executed when value of n is not equal to any case.
}
Following program is used to perform basic arithmetic operations using switch.
On compiling and executing the program you will get the below output.
please provide operator (+, -, *,): -
provide two operand numbers: 32,5
12.4
32.5 - 12.4 = 20.1
Function
Set of statements in C program which perform a specific task is called functions. Every C program has a main() function which is executed first of all functions present in any program. Functions in C, are of two types
Built-in functions
User-defined functions
Built-in functions are the standard library functions which are already present in C library and are used for performing specific tasks e.g. clrscr(), scanf() and getchar() etc. User defined functions are defined by user by following the below mentioned syntax
datatype_of_outputname_of_function(list of input parameters separated by commas) {
Function body
}
Wherever we need to use the function whether it is a built-in or user-defined function we just call it. The standard syntax for calling a function is
Name_of_function();
datatype_of_outputname_of_function(list of input parameters separated by commas);
Below program uses function for adding two numbers.
#include <stdio.h>
intaddNumbers(int a, int b); // function prototype
int main()
{
int n1,n2,sum;
printf("Enters two numbers: ");
scanf("%d %d",&n1,&n2);
sum = addNumbers(n1, n2); // function call
printf("sum = %d",sum);
return 0;
}
intaddNumbers(int a,int b) // function definition
{
int result;
result = a+b;
return result; // return statement
}
On compiling and executing the program you will get the below output.
Enters two numbers: sum =
Passing Values between Functions
To pass values to a function we use arguments. Arguments are also known as parameters. Arguments are placed inside the parenthesis.
Call by Value
A function is called by passing actual value of the input variable to the function. Advantage of this method is that if the formal parameter of the function is changed inside the function it has no effect on the input argument. Following program is used to display prime number by using functions. Function is called by value.
#include <stdio.h>
intcheckPrimeNumber(int n);
int main()
{
int n, flag;
printf("Enter a positive integer: ");
scanf("%d",&n);
// n is passed to the checkPrimeNumber() function
// the value returned from the function is assigned to flag variable
flag = checkPrimeNumber(n);
if(flag==1)
printf("%d is not a prime number",n);
else
printf("%d is a prime number",n);
return 0;
}
// integer is returned from the function
intcheckPrimeNumber(int n)
{
/* Integer value is returned from function checkPrimeNumber() */
int i;
for(i=2; i <= n/2; ++i)
{
if(n%i == 0)
return 1;
}
return 0;
}
On compiling and executing the program you will get the below output.
Enter a positive integer: 3
3 is a prime number
Call by Reference
A function is called by passing only the address of input variable as formal parameter of the function and address of the argument is used in the function to access its value. In this case, if the formal parameter of the function is changed inside the function it has effect on the input argument. Program to interchange two numbers using pointers and function is called by reference.
#include <stdio.h>
void swap(int *n1, int *n2);
int main()
{
int num1 = 5, num2 = 10;
// address of num1 and num2 is passed to the swap function
swap(&num1, &num2);
printf("Number1 = %d\n", num1);
printf("Number2 = %d", num2);
return 0;
}
void swap(int * n1, int * n2)
{
// pointer n1 and n2 points to the address of num1 and num2 respectively
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
On compiling and executing the program you will get the below output.
Number1 = 10
Number2 = 5
Pointer
A pointer is a type of variable which is used to store the address of another variable. Just like ordinary variables; pointers also need to be declared before use.
Pointer Notation
The standard syntax to declare pointer in C programming is
datatype *name_of_variable;
Asterisk is used to differentiate a pointer from other variables.
Int *a; double *b; float *c; char *d;
Function Calls and pointers
Mostly pointers are used with functions in one of the following ways
Pointer as input parameter to a function Pointer is passed as parameter to the called function by reference or by address and passed parameter can be modified by that function.
Pointer as output from a function A function can return a pointer to any of the local, static or dynamic variable.
Following program is used to interchange two numbers using pointers and function call by reference.
#include <stdio.h>
void swap(int *n1, int *n2);
int main()
{
int num1 = 5, num2 = 10;
// address of num1 and num2 is passed to the swap function
swap(&num1, &num2);
printf("Number1 = %d\n", num1);
printf("Number2 = %d", num2);
return 0;
}
void swap(int * n1, int * n2)
{
// pointer n1 and n2 points to the address of num1 and num2 respectively
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
On compiling and executing the program you will get the below output.
Number1 = 10
Number2 = 5
Recursion
Expressing the programming operations in terms of themselves is called recursion. For example, a function that is calling itself inside its body is known as recursive function. Recursions make programs cleaner and slower. Following program is used to addnatural numbersby using recursion.
#include <stdio.h>
int sum(int n);
int main()
{
int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number);
result = sum(number);
printf("sum=%d", result);
}
int sum(int num)
{
if (num!=0)
return num + sum(num-1); // sum() function calls itself
else
return num;
}
On compiling and executing the program you will get the below output.
Enter a positive integer:
3
6
Preprocessor
C language uses Preprocessor to process the source code of program before compiling. All preprocessing directives are defined by using a # symbol.
Features of C Preprocessor
Preprocessor is not included in compiler and it is executed as a separate entity.
The preprocessor can be used to serve below purposes o including header files o macro expansions o conditional compilation o line control.
Preprocessors provide following advantages in writing the program o Easy to create o Easy to edit o Easy to read by compiler o The code becomes transferable between various computer machines.
#define area
Macro Expansion
Preprocessors are used to define macros. Macro mostly has neutral data type and is used directly in the code without any function call over it. The usual syntax to define macro is as follows
#define name_of_macro(arguments separated by commas) [code for expand expansion]
Macro expansion is explained well by below example.
#include<stdio.h>
#define LENGTH 3
#define WIDTH 2
int main()
{
int r,c;
for(r=1; r<=LENGTH; r++)
{
for(c=1; c<=WIDTH; c++)
printf("%d%d",c,r);
printf("\n");
}
return 0;
}
On compiling and executing the program you will get the below output.
1121
1222
1323
Macros with Arguments
Macros can also take arguments. These arguments are placed in parenthesis while defining the macro. Only valid C language identifiers can be passed as arguments to a macro. Calling a macro is similar to calling a function.
#include <stdio.h>
#define MAX(x,y) ((x) > (y) ? (x) : (y))
int main(void) {
printf("Max between 20 and 10 is %d\n", MAX(10, 20));
return 0;
}
On compiling and executing the program you will get the below output.
Max between 20 and 10 is 20
Macros versus Functions
Macros and functions can carry out similar functions. Basic difference between macro and function is that macro is not compiled it is preprocessed and function is not preprocessed it is compiled.it is very hard to find any bug in macros because their implementation is not visible. The difference of macro and function is explained by below programs. First program uses macro and second program uses function to produce same output.
#include<stdio.h>
#define NUMBER 10
int main()
{
printf("%d", NUMBER);
return 0;
}
On compiling and executing the program you will get the below output.
10
#include<stdio.h>
int number()
{
return 10;
}
int main()
{
printf("%d", number());
return 0;
}
On compiling and executing the program you will get the below output.
10
File Inclusion
The #include directive is used to include parts of a specified file in a program which is delivered to the compiler. Generally, the #include directive is used to insert global definitions and standard header files in the program.
#include "filename"
#include <filename>
Following program uses stdio.h header file to add n natural numbers using for loop.
#include <stdio.h>
int main()
{
int num, count, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &num);
// for loop terminates when n is less than count
for(count = 1; count <= num; ++count)
{
sum += count;
}
printf("Sum = %d", sum);
return 0;
}
On compiling and executing the program you will get the below output.
Enter a positive integer: 10
Sum = 55
#if and #elif Directives
These are the conditional preprocessor directives. They use output of a constant expression to include a set of code in the program for compilation.#elif Directive indicates “else if”. Other conditional preprocessor directives include
#ifdef
#ifndef -
#else -
#endif - Below is an example program describing the use of the above mentioned directives.
#include<stdio.h>
#define NUM 10
void main()
{
#if(NUM == 0)
printf("\nNumber is Zero");
#elif(NUM > 0)
printf("\nNumber is Positive");
#else
printf("\nNumber is Negative");
#endif
}
On compiling and executing the program you will get the below output.
Number is Positive
Miscellaneous Directives in C Language
Miscellaneous preprocessor directives are not generally used. They are used for special purposes. Miscellaneous directives work like other directives. They can be used for un-define a defined identifier or they can be used to turn on or turn off certain features of a program. Choice of a miscellaneous directive depends on the end application of the program.
#undef Directive
It is used to make a defined variable undefined. For example, to un-define a macro which was defined by using #define, #undef directive is used. Below is an example program describing the use of the #undefdirective.
#include <stdio.h>
#define YEARS_OLD 12
#undef YEARS_OLD
int main()
{
#ifdef YEARS_OLD
printf("Ali is over %d years old.\n", YEARS_OLD);
#endif
printf("Ali is a great man.\n");
return 0;
}
On compiling and executing the program you will get the below output.
Ali is a great man
#pragma Directive
Pragma directives are used to turn off and on some features of a program. With different types
of compilers there are different pragma directives. Some pragmas are described below
#pragma startup
It allows defining those functions which are executed before the main function.
#pragma exit
It allows defining those functions which are executed at the end of the main function.
Below is an example program describing the use of the #pragma directive.
#include<stdio.h>
#include<conio.h>
void School();
void College() ;
#pragma startup School 105
#pragma startup College
#pragma exit College
#pragma exit School 105
void main(){
printf("\nI am in main");
getch();
}
void School(){
printf("\nI am in School");
getch();
}
void College(){
printf("\nI am in College");
getch();
}
On compiling and executing the program you will get the below output.
I am in College
I am in School
I am in main
I am in School
I am in College
Chapter Three
Arrays
An array is a data structure that is used to hold a fixed number of values of same data type. It can be thought of as collection of variables of same type. Instead of defining each variable individually we place all the variables of same type in an array. For example: if you can store ages of 50 students in an array.
float age[50];
An array consists of a set of memory locations. As illustrated in the below figure
It stores list of one or more lists i.e. array of one
or more arrays.
Declaration data_typevariable_name[ size of
array ];
data_typevariable_name[size of array 1][size of
array 2];
Total Size in
Bytes
Total Bytes =sizeof(data type of
variable of array)* array size
Total Bytes= sizeof(datatype of variable of
array)* size of first index of array*size of
second index of array.
Receiving
parameter
A pointer, sized and any un-sized
array can receive it.
The parameter which receives it must always
define the first right side of the array.
Dimensions It has only one dimension. It has Two dimensions.
A Simple Program Using Array
#include <stdio.h>
int main()
{
int i, n;
floatarr[100];
printf("Enter size of array (1 to 100): ");
scanf("%d", &n);
printf("\n");
for(i = 0; i < n; ++i)
{
printf("Enter Number %d: ", i+1);
scanf("%f", &arr[i]);
}
for(i = 1; i < n; ++i)
{
if(arr[0] <arr[i])
arr[0] = arr[i];
}
printf("Largest element = %.2f", arr[0]);
return 0;
}
On compiling and executing the program you will get the below output.
Enter total number of elements(1 to 100):
Largest element =
This is a simple program which gets values of arrays elements from the user and displays them.
First it asks the user to tell the number of elements of the array. This number is used to run the
loop which stores the values of array elements sequentially. Finally, values of the array are
displayed using C output functions.
How to Initialize Array in C Language.
Array declaration is similar to variable declaration. Data type of array and number of variables of the array are specified. For example;
data_typearray_name[array_size];
Initialization means assigning value to array variable on declaration. We can initialize an array by using the below syntax
#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0, average;
printf("Enter n: ");
scanf("%d", &n);
for(i=0; i<n; ++i)
{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
sum += marks[i];
}
average = sum/n;
printf("Average = %d", average);
return 0;
}
On compiling and executing the program you will get the below output.
Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39
This program illustrates array declaration. An array of marks[10] is declared and is used to get marks of students from the user. These marks are used for computing the average marks of the class.
Passing Array Elements in C Language to a Function In C language we can pass whole array or any element or group of elements of an array to a function as argument. The program in below example passes an element of an array to the function as argument.
#include <stdio.h>
void display(int age)
{
printf("%d", age);
}
int main()
{
intageArray[] = { 2, 3, 4 };
display(ageArray[2]); //Passing array element ageArray[2] only.
return 0;
}
On compiling and executing the program you will get the below output.
4
In this program an array named ‘ageArray’ is declared and its third element ageArray[2] is passed as input argument function.
Pointers and Arrays in C Language. In C programming, Pointers and arrays are in close relationship with each other. A pointer differs from array in such a way that a pointer which is used as a variable, uses different address values and In the case of arrays the address value is fixed. Name of the array,all the times refers to the memory address of the first element of an array. Pointers
denote the memory addresses, in spite of specific values. They are represented by an asterisk (*). Pointers may be incremented, and we can use pointers for repeatedly executing an array.
The program below is used to display addresses of array elements.
#include <stdio.h>
int main()
{
charcharArr[4];
int i;
for(i = 0; i < 4; ++i)
{
printf("charArr[%d] = %u\n", i, &charArr[i]);
}
return 0;
}
On compiling and executing the program you will get the below output.
charArr[0] = 28ff44
charArr[1] = 28ff45
charArr[2] = 28ff46
Address of charArr[3] = 28ff47
In C programming language, an array’s name every time indicates the address of first element
of that array.
In this program a character array named as ‘charArr’ is declared and is used to display memory
addresses of all the array elements.
Passing an Entire Array to a Function in C Language.
Functions are there to perform specialized operations. Sometimes, we need to provide a list of values as input to a function. This is done by passing arrays to functions. The function processes the input array and produces the required output in the specified format. Below program passes whole one dimensional array as argument to a function.
#include<stdio.h>
void fun(int arr[])
{
int i;
for(i=0;i< 5;i++)
arr[i] = arr[i] + 10;
}
void main()
{
intarr[5],i;
printf("\nEnter the array elements : ");
for(i=0;i< 5;i++)
scanf("%d",&arr[i]);
printf("\nPassing entire array .....");
fun(arr); // Pass only name of array
for(i=0;i< 5;i++)
printf("\nAfter Function call a[%d] : %d",i,arr[i]);
}
On compiling and executing the program you will get the below output.
Enter the array elements :
Passing entire array .....
After Function call a[0] :
After Function call a[1] :
After Function call a[2] :
After Function call a[3] : 10
After Function call a[4] : -755152422
In the above program an integer array named as ‘arr[5]’ is passed as input argument to the function declared as ‘fun’. note that only array name is used for passing the entire array as argument to the function.
Two Dimensional Arrays in C Language.
In C programming language, an array which is made up of arrays is called multidimensional array. For example,
float a[5][7];
In the above example, a two-dimensional array of float data type, this array can have 20 elements. A two-dimensional array is just like a table which has rows and columns. The above two dimensional array can be thought to have 5 rows and 7 columns.
Initializing a 2-Dimensional Array.
Two dimensional array initialization is similar to one-dimensional array initialization. There are more than one methods to initialize a two dimensional array. A two dimensional array can be initialized by one of the below mentioned three methods. Method 1: Initializing all Elements row-wise
In this method of initializing a two dimensional array all the elements of the array are assigned values
by using the below mentioned syntax.
int a[3][2] = {
{ 1 , 4 },
{ 5 , 2 },
{ 6 , 5 }
};
Consider the below program –
#include<stdio.h>
int main() {
int i, j;
int a[3][2] = { { 1, 4 },
{ 5, 2 },
{ 6, 5 }};
for (i = 0; i < 3; i++) {
for (j = 0; j < 2; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}
return 0;
}
On compiling and executing the program you will get the below output.
1 4
5 2
6 5
An array of 3 X 2 size has been declared in the above program and it contains total 6 elements.
Row 1 : { 1 , 4 },
Row 2 : { 5 , 2 },
Row 3 : { 6 , 5 }
Each row has been initialized in an independent way.
a[0][0] = 1
a[0][1] = 4
Method 2: Combine and Initializing 2D Array
All the elements of the array are initialized and it is a much convenient way. All the values are
allocated row by row and in a sequential manner.
int a[3][2] = {1 , 4 , 5 , 2 , 6 , 5 };
Consider the below example program –
#include <stdio.h>
int main() {
int i, j;
int a[3][2] = { 1, 4, 5, 2, 6, 5 };
for (i = 0; i < 3; i++) {
for (j = 0; j < 2; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}
return 0;
}
Output of this program will be like the output of program mentioned in first method.
Method 3 : Some Elements could be initialized
int a[3][2] = {
{ 1 },
{ 5 , 2 },
{ 6 }
};
This method is exactly like method 1 but we have removed some elements of array. In this method, a
two dimensional array is declared as mentioned below,
#include <stdio.h>
int main() {
int i, j;
int a[3][2] = { { 1 },
{ 5, 2 },
{ 6 }};
for (i = 0; i < 3; i++) {
for (j = 0; j < 2; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}
return 0;
}
On compiling and executing the program you will get the below output.
1 0
5 2
6 0
Elements which are not initialized will get a value of 0.
Pointers and 2-Dimensional Arrays.
In case of simple one dimensional array, the name of array serves as a pointer of the first array element. In case of 2 dimensional array, the case is not the same. We can take two-dimensional array as a table of simple one dimensional arrays. So, First element of the array i.e. arr[0] will indicate first row and arr[1] will indicate second row and so on. The below program illustrates this concept in detail.
#include <stdio.h>
#define ROWS 4
#define COLS 3
int main ()
{
// matrix of 4 rows and 3 columns
int matrix[ROWS][COLS] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}};
int** pmat = (int **)matrix;
printf("&matrix[0][0] = %u\n", &matrix[0][0]);
printf("&pmat[0][0] = %u\n", &pmat[0][0]);
return 0;
}
On compiling and executing the program you will get the below output.
&matrix[0][0] = 940278400
&pmat[0][0] = 1
This program uses two dimensional array named as ‘matrix[ROWS][COLS]’ which has 4 rows and 3 columns to print the address of matrix[0][0] and its pointer.
This program uses a six elements double data type array named as ‘balance[5]’. All the array elements are initialized first and then displayed using pointers and array addresses. In both ways same output is produced.
Passing 2-D array to a Function. Functions are there to perform specialized operations. Sometimes, we need to provide a list of values as input to a function. This is done by passing arrays to functions. The function processes the input array and produces the required output in the specified format.
For passing a 2-D array to a function in the form of an argument, number of elements in the each row of the 2-D array should be specified. By default, arrays are passed to functions by reference and we can pass array to the function by two ways either by using name of array or address of the starting element of array. When a two dimensional array is passed to a function first memory address of the array is passed as happens when one dimensional array is passed. For instance, for initializing each element of array to 0, below syntax is used.
The prerequisite to mention the row length in the argument makes this to some degree a cumbersome approach. For further notice, we can sidestep the complexities engaged with passing two-dimensional arrays to functions by utilizing a different approach. The approach is to declare any two-dimensional array we have to use in a program by pronouncing them as global variables. A global variable is any variable that is declared outside the scope of any function in the program. Variables declared in a function are called local variables, and just exist inside of the function they are declared in. To get a local variable starting with one function then onto the next, we need to pass it in as a parameter. Global variables are obvious in each function in a program and don't need to be passed in as parameters. Below program passes whole two dimensional array as argument to a function.
#include <stdio.h>
voiddisplayNumbers(int num[2][2]);
int main()
{
int num[2][2], i, j;
printf("Enter 4 numbers:\n");
for (i = 0; i < 2; ++i)
for (j = 0; j < 2; ++j)
scanf("%d", &num[i][j]);
// passing multi-dimensional array to displayNumbers function
displayNumbers(num);
return 0;
}
voiddisplayNumbers(int num[2][2])
{
// Instead of the above line,
// void displayNumbers(int num[][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", num[i][j]);
}
On compiling and executing the program you will get the below output.
Enter 4 numbers:
Displaying:
4196736
0
4196256
0
This program uses an integer data type two dimensional array named as ‘num[2][2]’. Values of array elements are got from the user and whole array is passed to ‘displayNumbers’ function for displaying it.
Array of Pointers.
Before discussing the array of pointers, first go through the below program example −
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i;
for (i = 0; i < MAX; i++) {
printf("Value of var[%d] = %d\n", i, var[i] );
}
return 0;
}
On compiling and executing the program you will get the below output.
Value of var[0] = 10 Value of var[1] = 100 Value of var[2] = 200
This program uses a simple array named ‘var[]’. This array is initialized and displayed by using a
constant key word MAX.
In many circumstances we need to make an array of pointers which are storing addresses of
other data types and variables. Below example describes a pointer array which has double
data type.
double *arr[MAX];
Here, arr is declared as an array with MAX double type pointers. So, every memory location
arr, is having a pointer to a double value. The below example is explaining the concept in
detail.
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr[MAX];
for ( i = 0; i < MAX; i++) {
ptr[i] = &var[i];
}
for ( i = 0; i < MAX; i++) {
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
return 0;
}
On compiling and executing the program you will get the below output.
var[0] = 10 var[1] = 100 var[2] = 200
We can employ a pointers array to store characters of strings. As illustrated by the below
program example.
#include <stdio.h>
const int MAX = 4;
int main () {
char *names[] = {
"hassan",
"mohsin",
"ahsan",
"salman"
};
int i = 0;
for ( i = 0; i < MAX; i++) {
printf("Value of names[%d] = %s\n", i, names[i] );
}
return 0;
}
On compiling and executing the program you will get the below output.
Value of names[0] = hassan Value of names[1] = mohsin Value of names[2] = ahsan Value of names[3] = salman
Three Dimensional Array.
Three dimensional array is also a collection of simple one dimensional arrays. We can declare a three dimensional array by using the below syntax,
float y[2][4][3];
In this example,the array y has maximum 24 member elements.
This three dimensional array can be understood aseach of the 2 elements having 4 elements with them making them total 8 elements and in these 8 elements each element has 3 elements attached.
A three dimensional array can be initialized in a similar way to two dimensional array.
The below program example stores the values provided by user in the form of a three-dimensional array and then this three dimensional array is displayed.
#include <stdio.h>
int main()
{
// this array can store 12 elements
int i, j, k, test[2][3][2];
printf("Enter 12 values: \n");
for(i = 0; i < 2; ++i) {
for (j = 0; j < 3; ++j) {
for(k = 0; k < 2; ++k ) {
scanf("%d", &test[i][j][k]);
}
}
}
// Displaying values with proper index.
printf("\nDisplaying values:\n");
for(i = 0; i < 2; ++i) {
for (j = 0; j < 3; ++j) {
for(k = 0; k < 2; ++k ) {
printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]);
}
}
}
return 0;
}
On compiling and executing the program you will get the below output.
Enter 12 values:
Displaying values:
test[0][0][0] = 1
test[0][0][1] = 0
test[0][1][0] = 4196877
test[0][1][1] = 0
test[0][2][0] = 4196256
test[0][2][1] = 0
test[1][0][0] = 0
test[1][0][1] = 0
test[1][1][0] = 4196800
test[1][1][1] = 0
test[1][2][0] = 4196256
test[1][2][1] = 0
String
What are Strings in C Language In C programming, an array which is made up of allcharacters is known as string. A null
character /0is used for terminating a string. For example:
"programming is fun"
Here, "programming is fun" is a string. Whenever a compiler comes over any string, it attaches a null character /0 after the last character of the string.
Declaring strings
For using strings in the C language programs first they are declared just like arrays, variables and functions.
Declaring strings by using arrays
Declaration syntax of strings is similar to that for arrays. Strings declaration differs from array declaration only in the way that string can have only char data type.
char a[10];
Declaring strings by using pointers
We can also declare strings by means of pointers.
char *p;
Initializing a string
In C programming, there are many ways for declaring strings. Just like arrays, functions and variables we can declare and initialize a string in the same step.
char c[] = "abcd";
OR,
char c[50] = "abcd";
OR,
char c[] = {'a', 'b', 'c', 'd', '\0'};
OR,
char c[5] = {'a', 'b', 'c', 'd', '\0'};
Frequently employed string handling functions are mentioned hereunder:
Function Operation of function
strlen() Computes length of a string
strcpy() For Copying a string into any other string
strcat() For joining two strings together
strcmp() For Comparing two strings with each other
strlwr() For converting string to lowercase letters
strupr() For converting string to uppercase letters
How to get length of a string in C Language using strlen( ). Thestrlen( ) function uses a single input argument. The string variable of the string whose length is to be calculated is passed as argument to this function. The length of string is returned as output of the function. The header file <string.h> is employed for using this function.The standard syntax for the strlen( ) function is mentioned below.
size_tstrlen(const char *str);
The below program is used to calculate length of string by using strlen( ) function.
//calculates the length of string before null charcter.
printf("Length of string b = %d \n",strlen(b));
printf("Length of string c = %d \n",strlen(c));
return 0;
}
On compiling and executing the program you will get the below output.
Enter string: String
Length of string a = 7
Length of string b = 7
Length of string c = 6
How to copy a string in C Language using strcpy( ).
The strcpy() function is used to copy acharacter string into another character string. The standard syntax for the strcpy() function is mentioned below.
The strcpy() function operates by using source and destination. The string which is pointed on by the source is copied into the string / character array at the destinationalong with the null character. This function produces destinationstring / character array as output. The header file <string.h> must be used for using this function.
The below program is used to copy string by using strcpy() function.
On compiling and executing the program you will get the below output.
good
night
It is essential to remember that, the destination string / array must have sufficient size to accommodate the string which is going to be copied otherwise string will not be copied properly.
How to concatenate a string in C Language with strcat().
The strcat( ) function uses two input arguments which are in the form of two character strings or arrays. The concatenated string which results after concatenation is stored in the first string listed in the argument.strcat( ) function returns the pointer to the resultant string is passed as an output value. The header file <string.h> is employed for using this function. The standard syntax for the strcat( ) function is mentioned below.
char *strcat(char *dest, const char *src)
The below program is used to concatenate two strings by using strcat( ) function.
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "great ", str2[] = "programming";
//concatenates str1 and str2 and resultant string is stored in str1.
On compiling and executing the program you will get the below output.
great programming
programming
How to compare two string in C Language using strcmp( ).
The strcmp() function inputs two character arrays or strings and produces output as an integer. The strcmp() is used to compare two input strings character to character. It compares all the characters of two strings with each other, If first characters of two strings are same, next characters of the two strings are checked and checking continues till end of two strings until the characters from two strings does not match. The header file <string.h> is employed for using this function.The standard syntax for the strcmp( ) function is mentioned below.
printf(" Percentage is: %f\n\n",record[i].percentage);
}
return0;
}
OUTPUT:
Records of STUDENT : 1
Id is: 1
Name is: Raju
Percentage is: 86.500000
Records of STUDENT : 2
Id is: 2
Name is: Surendren
Percentage is: 90.500000
Records of STUDENT : 3
Id is: 3
Name is: Thiyagu
Percentage is: 81.500000
Structure is used to store the data of One specific object but if we need to store such 100 objects
then Array of Structure is used.
Example :
struct Bookinfo
{
char[20] bname;
int pages;
int price;
}Book[100];
Explanation :
1. Here Book structure is used to Store the data of one Book.
2. In case if we need to store the data of 100 books then Array of Structure is used.
3. b1[0] stores the data of 1st Book , b1[1] stores the information of 2nd Book and So on
We can store the information of 100 books.
Example :
#include <stdio.h>
struct Bookinfo
{
char[20] bname;
int pages;
int price;
}book[3];
int main(int argc, char *argv[])
{
int i;
for(i=0;i<3;i++)
{
printf("\nEnter the Name of Book : ");
gets(book[i].bname);
printf("\nEnter the Number of Pages : ");
scanf("%d",book[i].pages);
printf("\nEnter the Price of Book : ");
scanf("%f",book[i].price);
}
printf("\n--------- Book Details ------------ ");
for(i=0;i<3;i++)
{
printf("\nName of Book : %s",book[i].bname);
printf("\nNumber of Pages : %d",book[i].pages);
printf("\nPrice of Book : %f",book[i].price);
}
return 0;
}
Output of the Structure Example:
Enter the Name of Book : ABC
Enter the Number of Pages : 100
Enter the Price of Book : 200
Enter the Name of Book : EFG
Enter the Number of Pages : 200
Enter the Price of Book : 300
Enter the Name of Book : HIJ
Enter the Number of Pages : 300
Enter the Price of Book : 500
--------- Book Details ------------
Name of Book : ABC
Number of Pages : 100
Price of Book : 200
Name of Book : EFG
Number of Pages : 200
Price of Book : 300
Name of Book : HIJ
Number of Pages : 300
Price of Book : 500
Additional Features of Structures with practical
C – Passing struct to function
A structure can be passed to any function from main function or from any sub function.
Structure definition will be available within the function only.
It would not be exist to other functions but it is passed to those functions by value or by
address(reference).
Also, we have to declare structure variable as global variable. That means, structure variable
should be declared outside the main function. So, this structure will be seen to all the
functions in a C program.
Passing structure to function in c:
It can be done in below 2 ways.
1. Passing structure to a function by value
2. Passing structure to a function by address(reference)
Example program – passing structure to function in c by value:
In this program, the whole structure is passed to another function by value. It means the complete
structure is passed to another function with all members and their values. So, this structure can
be accessed from called function. This idea is very convenient while writing major programs in
C.
#include <stdio.h>
#include <string.h>
structstudent
{
intid;
charname[20];
floatpercentage;
};
voidfunc(structstudent record);
intmain()
{
structstudent record;
record.id=1;
strcpy(record.name,"Raju");
record.percentage=86.5;
func(record);
return0;
}
voidfunc(structstudent record)
{
Id is: 1
Name is: Raju
Percentage is: 86.500000
EXAMPLE PROGRAM – PASSING STRUCTURE TO FUNCTION IN C BY
ADDRESS:
In this program, the complete structure is passed to another function by address(reference). It
means only the address of the structure is passed to another function. The complete structure is
not passed to another function with all members and their values. So, this structure can be
accessed from called function by its address.
#include <stdio.h>
#include <string.h>
structstudent
{
intid;
charname[20];
floatpercentage;
};
voidfunc(structstudent*record);
intmain()
printf(" Id is: %d \n",record.id);
printf(" Name is: %s \n",record.name);
printf(" Percentage is: %f \n",record.percentage);
}
Output
{
structstudent record;
record.id=1;
strcpy(record.name,"Raju");
record.percentage=86.5;
func(&record);
return0;
}
voidfunc(structstudent*record)
{
printf(" Id is: %d \n",record->id);
printf(" Name is: %s \n",record->name);
printf(" Percentage is: %f \n",record->percentage);
}
OUTPUT:
Id is: 1
Name is: Raju
Percentage is: 86.500000
Example program to declare a structure variable as global in c:
Structure variables can also be declared as global variables as we declare various variables in C.
So, When a structure variable is declared as global, then it is seen to all the functions in a program. In this condition, we don‟t want to pass the structure to any function separately.
#include <stdio.h>
#include <string.h>
structstudent
{
intid;
charname[20];
floatpercentage;
};
structstudent record;// Global declaration of structure
voidstructure_demo();
intmain()
{
record.id=1;
strcpy(record.name,"Raju");
record.percentage=86.5;
structure_demo();
return0;
}
voidstructure_demo()
{
printf(" Id is: %d \n",record.id);
printf(" Name is: %s \n",record.name);
printf(" Percentage is: %f \n",record.percentage);
}
OUTPUT:
Id is: 1
Name is: Raju
Percentage is: 86.500000
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 comp;
int real;
} num1, num2;
Suppose, you want to access imag_value for num2 structure variable then, following structure
member is used.
num2.comp.imag_value
see the following program.
#include <stdio.h>
typedef struct person
{
int age;
float weight;
};
int main()
{
struct person *personPtr, person1;
personPtr = &person1; // Referencing pointer to memory address of person1
Let us compile and run the above program that will create a file file.txt with the following
content −
We are in 2012
String (line) I/O in Files How to read/ write (I/O) Strings in Files – fgets & fputs
Here we will learn strings I/O from/into files. We have two functions to do that –
char*fgets(char*s,int rec_len, FILE *fpr)
Consider the example first –
#include<stdio.h>
int main()
{
FILE *fpr;
/*Char array to store strings */
char str[100];
/*Opening the file in "r" mode*/
fpr = fopen("FILER.TXT","r");
/*Error handling for file open*/
if(fpr == NULL)
{
puts("Issue in opening the input file");
}
/*Loop for reading the file till end*/
while(1)
{
if(fgets(str,10, fpr)==NULL)
break;
else
printf("%s", str);
}
/*Closing the input file after reading*/
fclose(fpr);
return0;
}
Operator &Enum
An enumeration is a user-defined data type that contains of integral constants. To define an
enumeration, keyword enum is used.
enum flag { const1, const2, ..., constN };
Here, name of the enumeration is flag.
And, const1, const2,...., constN are values of type flag.
By default, const1 is 0, const2 is 1 and so on. You can change default values of enum elements
during declaration (if necessary).
// Changing default values of enum
enum suit {
club = 0,
diamonds = 10,
hearts = 20,
spades = 3,
};
Operations On Bits in C Language with practical
The following table lists the Bitwise operators supported by C. Imagine
variable 'A' takes 60 and variable 'B' takes 13, then –
One’s Complement Operator with practical
Right Shift Operator with practical
Left Shift Operator with practical
Bitwise AND Operator with practical
Bitwise OR Operator with practical
Bitwise XOR Operator with practical
Operator Description Example
& Binary AND Operator copies a bit to the result if it present in both operands.
(A & B) =
12 i.e., 0000 1100
∣ Binary OR Operator copies a bit if it present in either operand.
(A ∣ B) = 61
i.e., 0011 1101
^ Binary XOR Operator copies the bit if it is set in one operand but not both.
(A ^ B) = 49 i.e., 0011 0001
~ Binary Ones Complement Operator is unary and has the result of 'flipping' bits.
(~A ) = -61
i.e., 1100 0011 in 2's complement form.
<< Binary Left Shift Operator. The left operands value is moved left by the number of bits particular by the right operand.
A << 2 = 240 i.e., 1111 0000
>> Binary Right Shift Operator. The left operands value is moved right by the number of bits particular by the
A >> 2 = 15 i.e.,
right operand. 0000 1111
Example see the following example to understand all the bitwise operators present in
C −
#include <stdio.h>
main() {
unsigned int a = 60; /* 60 = 0011 1100 */
unsigned int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a & b; /* 12 = 0000 1100 */
printf("Line 1 - Value of c is %d\n", c );
c = a | b; /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %d\n", c );
c = a ^ b; /* 49 = 0011 0001 */
printf("Line 3 - Value of c is %d\n", c );
c = ~a; /*-61 = 1100 0011 */
printf("Line 4 - Value of c is %d\n", c );
c = a << 2; /* 240 = 1111 0000 */
printf("Line 5 - Value of c is %d\n", c );
c = a >> 2; /* 15 = 0000 1111 */
printf("Line 6 - Value of c is %d\n", c );
}
When you compile and execute the program, it gives the following result as
follows −
Line 1 - Value of c is 12 Line 2 - Value of c is 61 Line 3 - Value of c is 49 Line 4 - Value of c is -61 Line 5 - Value of c is 240 Line 6 - Value of c is 15
Bitwise Operators with practical
Bitwise operator performs on bits and perform bit-by-bit operation. The
truth tables for &, |, and ^ is as follows −
P Q p & q p | q p ^ q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Imagine A = 60 and B = 13 in binary format, they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The following table lists the bitwise operators given by C. Imagine variable
'A' takes 60 and variable 'B' takes 13, then −
See Examples
Operator Description Example
& Binary AND Operator copies a bit to the result if it
present in both operands.
(A & B) =
12, i.e.,
0000 1100
| Binary OR Operator copies a bit if it present in either
operand.
(A | B) =
61, i.e.,
0011 1101
^ Binary XOR Operator copies the bit if it is set in one
operand but not both.
(A ^ B) =
49, i.e.,
0011 0001
~ Binary Ones Complement Operator is unary and has the
effect of 'flipping' bits.
(~A ) = -
61, i.e,.
1100 0011
in 2's
complement
form.
<< Binary Left Shift Operator. The left operands value is
moved left by the number of bits particular by the right
operand.
A << 2 =
240 i.e.,
1111 0000
>> Binary Right Shift Operator. The left operands value is
moved right by the number of bits particular by the