Top Banner
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
160

Chapter One Overview of the Programming Languages

Mar 21, 2022

Download

Documents

dariahiddleston
Welcome message from author
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
Page 1: Chapter One Overview of the Programming Languages

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

Page 2: Chapter One Overview of the Programming Languages

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

Page 3: Chapter One Overview of the Programming Languages

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.

Page 4: Chapter One Overview of the Programming Languages

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

program, which is named MinGW-<version>.exe.

During installation of Min GW, you must install

gcc-g++,

gcc-core,

binutils,

MinGW runtime,

You can also install more items for your ease.

Page 5: Chapter One Overview of the Programming Languages

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.

Page 6: Chapter One Overview of the Programming Languages

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

Page 7: Chapter One Overview of the Programming Languages

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

Page 8: Chapter One Overview of the Programming Languages

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 −

Page 9: Chapter One Overview of the Programming Languages

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.

Page 10: Chapter One Overview of the Programming Languages

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

Page 11: Chapter One Overview of the Programming Languages

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

Page 12: Chapter One Overview of the Programming Languages

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

Page 13: Chapter One Overview of the Programming Languages

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.

Page 14: Chapter One Overview of the Programming Languages

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

chapters e.g.Structure,Array, Enumeration, Union, Pointeretc.

Defining a variable in C

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 -

Page 15: Chapter One Overview of the Programming Languages

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;

Page 16: Chapter One Overview of the Programming Languages

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.

Page 17: Chapter One Overview of the Programming Languages

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 –

Page 18: Chapter One Overview of the Programming Languages

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

Page 19: Chapter One Overview of the Programming Languages

}

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;

Page 20: Chapter One Overview of the Programming Languages

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;

Page 21: Chapter One Overview of the Programming Languages

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;

Page 22: Chapter One Overview of the Programming Languages

}

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

Page 23: Chapter One Overview of the Programming Languages

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.

Page 24: Chapter One Overview of the Programming Languages

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

Page 25: Chapter One Overview of the Programming Languages

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

Page 26: Chapter One Overview of the Programming Languages

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

Page 27: Chapter One Overview of the Programming Languages

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

Page 28: Chapter One Overview of the Programming Languages

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

Page 29: Chapter One Overview of the Programming Languages

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-

Page 30: Chapter One Overview of the Programming Languages

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

{

Page 31: Chapter One Overview of the Programming Languages

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( ) {

Page 32: Chapter One Overview of the Programming Languages

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.

Page 33: Chapter One Overview of the Programming Languages

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

Page 34: Chapter One Overview of the Programming Languages

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

Page 35: Chapter One Overview of the Programming Languages

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

Page 36: Chapter One Overview of the Programming Languages

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( ) {

Page 37: Chapter One Overview of the Programming Languages

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

Page 38: Chapter One Overview of the Programming Languages

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

Page 39: Chapter One Overview of the Programming Languages

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

Page 40: Chapter One Overview of the Programming Languages

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

Page 41: Chapter One Overview of the Programming Languages

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

}

Page 42: Chapter One Overview of the Programming Languages

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;

Page 43: Chapter One Overview of the Programming Languages

}

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.

Page 44: Chapter One Overview of the Programming Languages

#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

while (number > 0)

{

factorial *= number; // factorial = factorial*number;

--number;

}

Page 45: Chapter One Overview of the Programming Languages

printf("Factorial= %lld", factorial);

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

Page 46: Chapter One Overview of the Programming Languages

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

Page 47: Chapter One Overview of the Programming Languages

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>

Page 48: Chapter One Overview of the Programming Languages

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

Page 49: Chapter One Overview of the Programming Languages

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

Page 50: Chapter One Overview of the Programming Languages

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;

}

Page 51: Chapter One Overview of the Programming Languages

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

Page 52: Chapter One Overview of the Programming Languages

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;

.

.

Page 53: Chapter One Overview of the Programming Languages

.

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.

# include <stdio.h>

int main() {

charoprtr;

doublefirstNum,secondNum;

printf("please provide operator (+, -, *, /): ");

scanf("%c", &oprtr);

printf("providetwo operand numbers: ");

scanf("%lf %lf",&firstNum, &secondNum);

switch(oprtr)

Page 54: Chapter One Overview of the Programming Languages

{

case '+':

printf("%.1lf + %.1lf = %.1lf",firstNum, secondNum, firstNum+secondNum);

break;

case '-':

printf("%.1lf - %.1lf = %.1lf",firstNum, secondNum, firstNum-secondNum);

break;

case '*':

printf("%.1lf * %.1lf = %.1lf",firstNum, secondNum, firstNum*secondNum);

break;

case '/':

printf("%.1lf / %.1lf = %.1lf",firstNum, secondNum, firstNum/firstNum);

break;

default:

Page 55: Chapter One Overview of the Programming Languages

printf(" operator is incorrect");

}

return 0;

}

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

Page 56: Chapter One Overview of the Programming Languages

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

Page 57: Chapter One Overview of the Programming Languages

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.

Page 58: Chapter One Overview of the Programming Languages

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

Page 59: Chapter One Overview of the Programming Languages

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

Page 60: Chapter One Overview of the Programming Languages

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

Page 61: Chapter One Overview of the Programming Languages

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.

Page 62: Chapter One Overview of the Programming Languages

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

Page 63: Chapter One Overview of the Programming Languages

{

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;

Page 64: Chapter One Overview of the Programming Languages

}

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

Page 65: Chapter One Overview of the Programming Languages

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

Page 66: Chapter One Overview of the Programming Languages

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

Page 67: Chapter One Overview of the Programming Languages

{

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

Page 68: Chapter One Overview of the Programming Languages

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

Page 69: Chapter One Overview of the Programming Languages

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;

Page 70: Chapter One Overview of the Programming Languages

}

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)

Page 71: Chapter One Overview of the Programming Languages

{

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 -

Page 72: Chapter One Overview of the Programming Languages

#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

Page 73: Chapter One Overview of the Programming Languages

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;

}

Page 74: Chapter One Overview of the Programming Languages

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

Page 75: Chapter One Overview of the Programming Languages

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

Page 76: Chapter One Overview of the Programming Languages

I am in School

I am in main

I am in School

I am in College

Chapter Three

Arrays

Page 77: Chapter One Overview of the Programming Languages

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

There are two types of arrays

1. One-dimensional arrays 2. Multidimensional arrays

BASIS FOR

COMPARISON ONE-DIMENSIONAL TWO-DIMENSIONAL

Page 78: Chapter One Overview of the Programming Languages

BASIS FOR

COMPARISON ONE-DIMENSIONAL TWO-DIMENSIONAL

Basic

It Storesa list of elements of

which have same data type.

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.

Page 79: Chapter One Overview of the Programming Languages

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;

}

Page 80: Chapter One Overview of the Programming Languages

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;

Page 81: Chapter One Overview of the Programming Languages

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

{

Page 82: Chapter One Overview of the Programming Languages

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

}

Page 83: Chapter One Overview of the Programming Languages

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

Page 84: Chapter One Overview of the Programming Languages

{

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.

Page 85: Chapter One Overview of the Programming Languages

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

Page 86: Chapter One Overview of the Programming Languages

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>

Page 87: Chapter One Overview of the Programming Languages

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 },

Page 88: Chapter One Overview of the Programming Languages

{ 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 ()

Page 89: Chapter One Overview of the Programming Languages

{

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

Page 90: Chapter One Overview of the Programming Languages

Pointer to an Array.

We know that name of array serves as pointer of the first element of the array.

floatarrayname[10];

In this example, arrayname acts a pointer for &arrayname[0] element of the array. So, we can

use following segment of the program to store address of the first array element of array in a

variable ‘a’

double *a; doublearrayname[10]; a = arrayname;

In C programming It is permitted to employ array names in the form of constant pointers, and

it is also permitted to employ constant pointers as array names. So, by using the code *(array +

5) we can easily access the corresponding element of the array at location arrayname[5].

Once we are able to store the address of the first element of the array in 'a', we can easily go

to other array elements by using identifiers such as *a, *(a+1), *(a+2) and so on. Below

program example explains the above mentioned things in detail.

#include <stdio.h

int main () {

/* an array with 5 elements */

double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};

double *p;

int i;

Page 91: Chapter One Overview of the Programming Languages

p = balance;

/* output each array element's value */

printf( "Array values using pointer\n");

for ( i = 0; i < 5; i++ ) {

printf("*(p + %d) : %f\n", i, *(p + i) );

}

printf( "Array values using balance as address\n");

for ( i = 0; i < 5; i++ ) {

printf("*(balance + %d) : %f\n", i, *(balance + i) );

}

return 0;

}

Page 92: Chapter One Overview of the Programming Languages

On compiling and executing the program you will get the below output.

Array values using pointer *(p + 0) : 1000.000000 *(p + 1) : 2.000000 *(p + 2) : 3.400000 *(p + 3) : 17.000000 *(p + 4) : 50.000000 Array values using balance as address *(balance + 0) : 1000.000000 *(balance + 1) : 2.000000 *(balance + 2) : 3.400000 *(balance + 3) : 17.000000 *(balance + 4) : 50.000000

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.

voidinitTable(int T[][20],int rows) { inti,j; for(i = 0;i <rows;i++) for(j = 0;j < 20;j++) T[i][j] = 0; }

Page 93: Chapter One Overview of the Programming Languages

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

Page 94: Chapter One Overview of the Programming Languages

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

Page 95: Chapter One Overview of the Programming Languages

}

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

Page 96: Chapter One Overview of the Programming Languages

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 () {

Page 97: Chapter One Overview of the Programming Languages

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.

Page 98: Chapter One Overview of the Programming Languages

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.

int test[2][3][4] = {

{ {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },

{ {13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9} }

};

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

Page 99: Chapter One Overview of the Programming Languages

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

Page 100: Chapter One Overview of the Programming Languages

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.

Page 101: Chapter One Overview of the Programming Languages

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

Page 102: Chapter One Overview of the Programming Languages

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.

Page 103: Chapter One Overview of the Programming Languages

#include <stdio.h>

#include <string.h>

int main()

{

char a[20]="Program";

char b[20]={'P','r','o','g','r','a','m','\0'};

char c[20];

printf("Enter string: ");

gets(c);

printf("Length of string a = %d \n",strlen(a));

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

Page 104: Chapter One Overview of the Programming Languages

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.

char* strcpy(char* destination, const char* source);

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.

#include <stdio.h>

#include <string.h>

int main()

{

char str1[10]= "good";

char str2[10];

char str3[10];

strcpy(str2, str1);

strcpy(str3, "night");

puts(str2);

puts(str3);

return 0;

}

Page 105: Chapter One Overview of the Programming Languages

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.

strcat(str1,str2);

Page 106: Chapter One Overview of the Programming Languages

puts(str1);

puts(str2);

return 0;

}

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.

intstrcmp (const char* str1, const char* str2);

Output values ofstrcmp() function

Value Description

0 Both input strings are same

Page 107: Chapter One Overview of the Programming Languages

Value Description

negative ASCII value for first matchless character is smaller than the second

positive integer ASCII value for first matchless character is greater than the second

The below program is used to compare two strings by using strcmp( ) function.

#include <stdio.h>

#include <string.h>

int main()

{

char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";

int result;

// comparing strings str1 and str2

result = strcmp(str1, str2);

printf("strcmp(str1, str2) = %d\n", result);

// comparing strings str1 and str3

result = strcmp(str1, str3);

printf("strcmp(str1, str3) = %d\n", result);

return 0;

}

On compiling and executing the program you will get the below output.

strcmp(str1, str2) = 32

Page 108: Chapter One Overview of the Programming Languages

strcmp(str1, str3) = 0

Page 109: Chapter One Overview of the Programming Languages

Chapter Four

Structures

What is Structures in C Language

Structure is a combination of variables of different kinds put under a singlename. Structure is a

user-defined data type in C which permits you to collect different data types for storing a specific

type of data. It is somewhat similar to an Array. The only difference is that array is used to store

combination of similar datatypes while structure can store combination of any type of data.

Structure is used to represent a record. Suppose you want to store record of Student which

consists of student name, address, roll number and age. You can define a structure to hold this

information.

Defining a structure

Struct keyword is used to define a structure. struct defines a new data type which is a combination of various kinds of data.

Syntax :

struct structure_name

{

data_type member1;

data_type member2;

data_type memeber;

};

We can make the structure for a person as stated above :

struct person

{

Page 110: Chapter One Overview of the Programming Languages

char name[50];

intcitNo;

float salary;

};

Here the person declares a structure to hold the information of person which consists of three

data fields, namely name, citNo and salary. These fields are called structure elements or

members. Each member can have various data type,like in this case, name is of char type

and citNo is of int type etc. person is the name of the structure and is called structure tag.

.

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;

};

We can make the structure for a person as stated above :

struct person

Page 111: Chapter One Overview of the Programming Languages

{

char name[50];

int citNo;

float salary;

};

This declaration above makes the final data type struct person.

Why Use Structures in C Language

Let us take a real world example.

A showroom of cars.

A car showroom must have 2 important assets:

1) Cars

2) Employees

Now, see the below structure code for cars:

struct Cars{

char Car_Maker_Brand[50];

char Car_Model[50];

int year_Of_Manufacture;

float Price;

int Seating_Capacity;

int Maximum_Speed;

float Fuel_tank_volume;

...

...

...

...

};

Why structures are helpful here?

If you have to store the information of several cars, as in case of a car showroom it is their

requirement, maintaining a structure array is much more easier than maintaining variables for

each property of car.

Page 112: Chapter One Overview of the Programming Languages

many goes with the employee database. They also have properties like car specifications.

Name

Address

Salary

Designation

DOB

etc

etc

Similarly, everywhere you can find the use-case of a structure. take anything from your area

either it is hospital ( patient details, medicine details, staff, doctors, etc) or school ( Student,

Result, Teacher, Subjects, other Staffs, etc).

Declaring a Structure in C Language with practical

When a structure is defined, it makes a user-defined type but, no storage or memory is

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

struct person

{

char name[50];

int citNo;

float salary;

};

int main()

{

struct person person1, person2, person3[20];

return 0;

Page 113: Chapter One Overview of the Programming Languages

}

An other method of creating a structure variable is:

struct person

{

char name[50];

int citNo;

float salary;

}

person1, person2, person3[20];

In both methods, two variables person1, person2 and an array person3 having 20 elements of

type struct person are created.

Accessing Structure Elements in C Language with practical

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

1. Member operator(.)

2. Structure pointer operator(->)

Any member of a structure can be accessed as:

structure_variable_name.member_name

Suppose, we want to access salary for variable person2. Then, it can be accessed

as:person2.salar

Page 114: Chapter One Overview of the Programming Languages

EXAMPLE PROGRAM FOR C STRUCTURE:

This program is used to store and access “id, name and percentage” for one student. We can also

store and access these data for many students using array of structures. You can see “C – Array

of Structures” to know how to store and access these data for a lot of students.

#include <stdio.h>

#include <string.h>

structstudent

{

intid;

charname[20];

floatpercentage;

};

intmain()

{

structstudent record={0};//Initializing to null

record.id=1;

strcpy(record.name,"Raju");

record.percentage=86.5;

printf(" Id is: %d \n",record.id);

printf(" Name is: %s \n",record.name);

Page 115: Chapter One Overview of the Programming Languages

printf(" Percentage is: %f \n",record.percentage);

return0;

}

OUTPUT:

Id is: 1

Name is: Raju

Percentage is: 86.500000

Example program – another way of declaring c structure:

In this program, structure variable “record” is declared while declaring structure itself. In above

structure example program, structure variable “struct student record” is declared inside main function which is after declaring structure.

#include <stdio.h>

#include <string.h>

structstudent

{

intid;

charname[20];

floatpercentage;

}record;

intmain()

{

record.id=1;

strcpy(record.name,"Raju");

record.percentage=86.5;

Page 116: Chapter One Overview of the Programming Languages

printf(" Id is: %d \n",record.id);

printf(" Name is: %s \n",record.name);

printf(" Percentage is: %f \n",record.percentage);

return0;

}

OUTPUT:

Id is: 1

Name is: Raju

Percentage is: 86.500000

How Structure Elements are Stored with practical

No matter what be the elements of a structure, they are always stored in adjacent memory

locations. The following program would explains this:

/* Memory map of structure elements */

main( )

{

struct book

{

char name ;

float price ;

int pages ;

} ;

struct book b1 = { 'B', 130.00, 550 } ;

printf ( "\nAddress of name = %u", &b1.name ) ;

printf ( "\nAddress of price = %u", &b1.price ) ;

printf ( "\nAddress of pages = %u", &b1.pages ) ;

}

Here is the output of the program...

Address of name = 65518

Address of price = 65519

Address of pages = 65523

Actually the structure elements are stored in memory as shown in the Figure

Page 117: Chapter One Overview of the Programming Languages

Array of Structures in C Language with practical

Array of Structure

C Structure is combination of various datatypes ( variables ) which are grouped together. While,

array of structures is nothing but combination of structures. This is also called as structure array in C.

EXAMPLE PROGRAM FOR ARRAY OF STRUCTURES IN C:

This program is used to store and access “id, name and percentage” for 3 students. Structure

array is used in this program to store and display records for many students. You can store “n”

number of students record by declaring structure variable as „struct student record[n]“, where n can be 1000 or 5000 etc.

#include <stdio.h>

#include <string.h>

structstudent

{

intid;

charname[30];

floatpercentage;

};

Page 118: Chapter One Overview of the Programming Languages

intmain()

{

inti;

structstudent record[2];

// 1st student's record

record[0].id=1;

strcpy(record[0].name,"Raju");

record[0].percentage=86.5;

// 2nd student's record

record[1].id=2;

strcpy(record[1].name,"Surendren");

record[1].percentage=90.5;

// 3rd student's record

record[2].id=3;

strcpy(record[2].name,"Thiyagu");

record[2].percentage=81.5;

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

{

printf(" Records of STUDENT : %d \n",i+1);

printf(" Id is: %d \n",record[i].id);

printf(" Name is: %s \n",record[i].name);

printf(" Percentage is: %f\n\n",record[i].percentage);

}

return0;

Page 119: Chapter One Overview of the Programming Languages

}

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 :

Page 120: Chapter One Overview of the Programming Languages

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

Page 121: Chapter One Overview of the Programming Languages

}

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

Page 122: Chapter One Overview of the Programming Languages

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.

Page 123: Chapter One Overview of the Programming Languages

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

{

Page 124: Chapter One Overview of the Programming Languages

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

Page 125: Chapter One Overview of the Programming Languages

{

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.

Page 126: Chapter One Overview of the Programming Languages

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

Page 127: Chapter One Overview of the Programming Languages

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.

Page 128: Chapter One Overview of the Programming Languages

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

printf("Enter integer: ");

scanf("%d",&(*personPtr).age);

printf("Enter number: ");

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

printf("Displaying: ");

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

return 0;

}

In this example, the pointer variable of type struct person is referenced to the address

of person1. Then, only the structure member through pointer can can accessed.

Page 129: Chapter One Overview of the Programming Languages

Using -> operator to access structure pointer member

Structure pointer member can also be accessed using -> operator.

(*personPtr).age is same as personPtr->age

(*personPtr).weight is same as personPtr->weight

Uses of Structures with practical

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 person {

int age;

float weight;

char name[30];

};

int main()

{

Page 130: Chapter One Overview of the Programming Languages

struct person *ptr;

int i, num;

printf("Enter number of persons: ");

scanf("%d", &num);

ptr = (struct person*) malloc(num * sizeof(struct person));

// Above statement allocates the memory for n structures with pointer personPtr pointing to

base address */

for(i = 0; i < num; ++i)

{

printf("Enter name, age and weight of the person respectively:\n");

scanf("%s%d%f", &(ptr+i)->name, &(ptr+i)->age, &(ptr+i)->weight);

}

printf("Displaying Infromation:\n");

for(i = 0; i < num; ++i)

printf("%s\t%d\t%.2f\n", (ptr+i)->name, (ptr+i)->age, (ptr+i)->weight);

return 0;

}

Output

Enter number of persons: 2

Enter name, age and weight of the person respectively:

Adam

Page 131: Chapter One Overview of the Programming Languages

2

3.2

Enter name, age and weight of the person respectively:

Eve

6

2.3

Displaying Information:

Adam 2 3.20

Eve 6 2.30

.Structures permit to store various data types information inside it at adjacent memory location. It

is a combination of various data types which are at adjacent memory locations.

If we want to show too many data(too many variables) of same data type as an single unit then

we go for Array but if we need to show too many information(too many variables) of various

data types as an single entity then we go for Structure.

Now see the use of the structure,

Suppose you are having record of 100 students. Each student is having name(which is

of char[] type), id(int type) and marks(float type). All these three information is

specially owned by each student. Each student will carry this three dissimilar data type

information.

Now, imagine you have to pass whole information of all students to one function for

some reason. Then rather than passing each and every data(name, id, marks, etc...) one

by one for every student will not be a good way of programming. In this case we will

like bettercome close to in which can pass complete student information as an single

unit of one by one student.

So, when we need to pass ondifferent data types data as an single unit then we go for

structure .

.

Page 132: Chapter One Overview of the Programming Languages

File Operation

When a program is terminated, the complete data is lost. Storing in a file will save your

data even if the program terminates.

If you have to enter a large number of data, it will take a lot of time to enter them all.

However, if you have a file containing all the information, you can easily access the

contents of the file using a small number of commands in C.

You can easily move your data from one computer to another without any changes.

Types of Files

When dealing with files, there are two types of files you should know about:

1. Text files

2. Binary files

1. Text files

Text files are the usualtxt files that you can easily create using Notepad or any plain text

editors.When you open those files, you'll see all the contents within the file as plain text. You

can easily edit or delete the contents.They take minimum effort to retain, are easily readable, and

provide least safety and takes bigger storage space.

2. Binary files

Binary files are mostly the .bin files in your computer.Instead of storing data in plain text, they

store it in the binary form (0's and 1's).They can hold higher amount of data, are not readable

easily and provides a better security than text files.

File Input/Output in C Language with practical

C programming has several in-built library functions to perform input and output tasks. Two

usually used functions for I/O (Input/Output) are printf() and scanf(). The scanf() function reads

formatted input from standard input (keyboard) while the printf() function sends formatted

output to the standard output (screen).

Example #1: C Output #include <stdio.h> //This is needed to run printf() function.

Page 133: Chapter One Overview of the Programming Languages

int main()

{

return 0;

}

Output

C Programming

How this program works?

All valid C program must consists the main() function. The code execution starts from

the start of main() function.

The printf() is a library function to send formatted output to the screen.

The printf()function is declared in "stdio.h" header file.

Here, stdio.h is a header file (standard input output header file) and #include is a

preprocessor directive to paste the code from the header file when needed. When the

compiler encounters printf() function and doesn't find stdio.h header file, compiler shows

error.

The return 0; statement is the "Exit status" of the program. In simple terms, program

ends.

Example #2: C Integer Output

#include <stdio.h>

int main()

{

int testInteger = 5;

printf("Number = %d", testInteger);

return 0;

}

Output

Number = 5

Page 134: Chapter One Overview of the Programming Languages

Inside the quot of printf() function, there is a format string "%d" (for integer). If the format

string matches the argument (testInteger in this case), it is displayed on the screen.

Example #3: C Integer Input/Output

#include <stdio.h>

int main()

{

int testInteger;

printf("Enter an integer: ");

scanf("%d",&testInteger);

printf("Number = %d",testInteger);

return 0;

}

Output

Enter an integer: 4

Number = 4

The scanf() function reads formatted input from the keyboard. When user enters an integer, it is

stored in variable testInteger.Note the '&' sign before testInteger; &testInteger gets the address

of testInteger and the value is stored in that address.

Page 135: Chapter One Overview of the Programming Languages

Example #4: C Floats Input/Output

#include <stdio.h>

int main()

{

float f;

printf("Enter a number: ");

// %f format string is used in case of floats

scanf("%f",&f);

printf("Value = %f", f);

return 0;

}

Output

Enter a number: 23.45

Value = 23.450000

The format string "%f" is used to read and display formatted in case of floats.

Page 136: Chapter One Overview of the Programming Languages

Example #5: C Character I/O

#include <stdio.h>

int main()

{

char chr;

printf("Enter a character: ");

scanf("%c",&chr);

printf("You entered %c.",chr);

return 0;

}

File Operations in C Language with practical

There are a large number of functions to handle file I/O (Input Output) in C

File Operations

In C, you can perform three major operations on the file

1. Opening an existing file

2. Closing a file

3. Reading from and writing information to a file

C program to read a file: This program reads a file entered by the user and displays its contents

on the screen, fopen function is used to open a file it returns a pointer to structure FILE. FILE is

a predefined structure in stdio.h . If the file is easily opened then fopen returns a pointer to file

and if it is unable to open a file then it returns NULL. fgetc function returns a character which is

read from the file and fclose function closes the file. Opening a file means we bring file from

disk to ram to do operations on it. The file must be present in the directory in which the

executable file of this code is present.

Opening a File in C Language with practical

Opening a file is done using the library function in the "stdio.h" header file: fopen().

The syntax for opening a file in standard I/O is:

Page 137: Chapter One Overview of the Programming Languages

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

For Example:

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

fopen("E:\\cprogram\\oldprogram.bin","rb");

Let's imagine the file newprogram.txt doesn't present in the location E:\cprogram. The

first function creates a new file named newprogram.txt and opens it for writing as per the

mode 'w'.

The writing mode permits you to create and edit (overwrite) the contents of the file.

Now let's imagine the second binary file oldprogram.bin exists in the

location E:\cprogram. The second function opens the existing file for reading in binary

mode 'rb'.

The reading mode only permits you to read the file, you cannot write into the file.

.

Reading from a File in C Language with practical

Reading to a text file For reading to a text file, we use the functions fprintf() and fscanf().

They are exactly the file versions of printf() and scanf(). The only difference is that,

fprint and fscanf expects a pointer to the structure FILE.

Following is the easiest function to read a single character from a file −

int fgetc( FILE * fp );

The fgetc() function reads a character from the input file referenced by fp. The return value

is the character read, or in case of any error, it returns EOF. The following function permits

to read a string from a stream −

char *fgets( char *buf, int n, FILE *fp );

Page 138: Chapter One Overview of the Programming Languages

The functions fgets() reads up to n-1 characters from the input stream referenced by fp. It

copies the read string into the buffer buf, attaching a null character to terminate the string.

If this function encounters a newline character '\n' or the end of the file EOF before they

have read the maximum number of characters, then it returns only the characters read up to

that point involving the new line character. You can also use int fscanf(FILE *fp, const char

*format, ...) function to read strings from a file, but it stops reading after encountering the

first space character.

#include <stdio.h>

main() {

FILE *fp;

char buff[255];

fp = fopen("/tmp/test.txt", "r");

fscanf(fp, "%s", buff);

printf("1 : %s\n", buff );

fgets(buff, 255, (FILE*)fp);

printf("2: %s\n", buff );

fgets(buff, 255, (FILE*)fp);

printf("3: %s\n", buff );

fclose(fp);

}

When the above code is compiled and executed, it reads the file created in the last section

and produces the following result −

1 : This

2: is testing for fprintf...

Page 139: Chapter One Overview of the Programming Languages

3: This is testing for fputs...

. First, fscanf() read just This because after it, it encountered a space, second call is

for fgets()which reads the remaining line till it encountered end of line. Finally, the last

call fgets() reads the second line completely.

.Example 2: Read from a text file using fscanf()

#include <stdio.h>

int main()

{

int num;

FILE *fptr;

if ((fptr = fopen("C:\\program.txt","r")) == NULL){

printf("Error! opening file");

// Program exits if the file pointer returns NULL.

exit(1);

}

Reading to a binary file

Functions fread() and are used for reading from a to a file on the disk in that order in case of

binary files.Function fread() also take 4 arguments like that to fwrite() function as above.

fread(address_data,size_data,numbers_data,pointer_to_file);

Page 140: Chapter One Overview of the Programming Languages

Example 4: Reading from a binary file using fread()

#include <stdio.h>

struct threeNum

{

int n1, n2, n3;

};

int main()

{

int n;

struct threeNum num;

FILE *fptr;

if ((fptr = fopen("C:\\program.bin","rb")) == NULL){

printf("Error! opening file");

// Program exits if the file pointer returns NULL.

exit(1);

}

for(n = 1; n < 5; ++n)

{

fread(&num, sizeof(struct threeNum), 1, fptr);

Page 141: Chapter One Overview of the Programming Languages

printf("n1: %d\tn2: %d\tn3: %d", num.n1, num.n2, num.n3);

}

fclose(fptr);

return 0;

}

In this program, you read the same file program.bin and loop through the actions one by one.

Closing the File in C Language with practical fclose()

int fclose(FILE

*fp);

The fclose() function first flushes the stream opened by fopen() and then closes the fundamental

explainer. After successful completion this function returns 0 else end of file (eof) is returned. In

case of failure, if the stream is accessed then the performance remains undefined.

The code

#include<stdio.h>

#include<string.h>

#define SIZE 1

#define NUMELEM 5

int main(void)

{

Page 142: Chapter One Overview of the Programming Languages

FILE* fd = NULL;

char buff[100];

memset(buff,0,sizeof(buff));

fd = fopen("test.txt","rw+");

if(NULL == fd)

{

printf("\n fopen() Error!!!\n");

return 1;

}

printf("\n File opened successfully through fopen()\n");

if(SIZE*NUMELEM != fread(buff,SIZE,NUMELEM,fd))

{

printf("\n fread() failed\n");

return 1;

}

Page 143: Chapter One Overview of the Programming Languages

printf("\n Some bytes successfully read through fread()\n");

printf("\n The bytes read are [%s]\n",buff);

if(0 != fseek(fd,11,SEEK_CUR))

{

printf("\n fseek() failed\n");

return 1;

}

printf("\n fseek() successful\n");

if(SIZE*NUMELEM != fwrite(buff,SIZE,strlen(buff),fd))

{

printf("\n fwrite() failed\n");

return 1;

}

Page 144: Chapter One Overview of the Programming Languages

printf("\n fwrite() successful, data written to text file\n");

fclose(fd);

printf("\n File stream closed through fclose()\n");

return 0;

}

The code above imagines that you have a test file “test.txt” placed in the same location from

where this executable will be run.

Initially the content in file is :

$ cat test.txt

hello everybody

Now, run the code :

$ ./fileHandling

File opened successfully through fopen()

Some bytes successfully read through fread()

Page 145: Chapter One Overview of the Programming Languages

The bytes read are [hello]

fseek() successful

fwrite() successful, data written to text file

File stream closed through fclose()

Again see the contents of the file test.txt. Below, the content of the file was modified.

$ cat test.txt

hello everybody

hello

Counting Characters, Tabs, Spaces, with practical Learn How to Count the Number of Spaces, Tabs, Characters and Newlines in a Text File in C

Programming Language.

Compare every taking place character with each of them:

if(ch == ‘ ‘) This will see the occurring of Spaces within the Text file.

if(ch == ‘\n’) This condition will will see the Number of Newlines.

if(ch == ‘\t’) This condition will see the Number of Tabs.

C Program To Count Number of Spaces, Newlines, Tabs and

Characters in File

Page 146: Chapter One Overview of the Programming Languages

#include<stdio.h>

#include<stdlib.h>

void main()

{

FILE *fp;

char ch;

int character = 0, space = 0, tab = 0, line = 0;

fp = fopen("/home/tusharsoni/Desktop/TestFile","r");

if(fp == NULL)

{

printf("File Not Found\n");

exit(1);

}

else

{

while(1)

{

ch = fgetc(fp);

if(ch == EOF)

{

break;

}

character++;

if(ch == ' ')

space++;

else if(ch == '\t')

tab++;

else if(ch == '\n')

line++;

}

}

fclose(fp);

printf("\nNumber of Characters = %d\n", character);

printf("\nNumber of Tabs = %d\n", tab);

printf("\nNumber of New Lines = %d\n", line);

printf("\nNumber of Spaces = %d\n", space);

}

Output

Page 147: Chapter One Overview of the Programming Languages

A File-copy Program in C Language

C program to copy files: This program copies a file, firstly you will indicate the file to copy and

then you will enter the name of target file, You will have to prominent the extension of file also.

We will open the file that we want to copy in read mode and target file in write mode.

C Program to Copy Text From One File to Other File

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

void main() {

FILE *fp1, *fp2;

char ch;

clrscr();

fp1 = fopen("Sample.txt", "r");

fp2 = fopen("Output.txt", "w");

while (1) {

ch = fgetc(fp1);

if (ch == EOF)

break;

else

putc(ch, fp2);

}

printf("File copied Successfully!");

Page 148: Chapter One Overview of the Programming Languages

fclose(fp1);

fclose(fp2);

}

Explanation :

To copy a text from one file to another we have to follow following Steps :

Step 1 : Open Source File in Read Mode

1

fp1=fopen("Sample.txt","r");

Step 2 : Open Target File in Write Mode

1 fp2=fopen("Output.txt","w");

Step 3 : Read Source File Character by Character

while(1){

ch=fgetc(fp1);

if(ch==EOF)

break;

else

putc(ch,fp2);

}

Writing to a File in C Language with practical

fread() and fwrite()

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

Page 149: Chapter One Overview of the Programming Languages

size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);

The functions fread/fwrite are used for reading/writing data from/to the file opened

by fopen function. These functions take three arguments. The first argument is a

pointer to buffer used for reading/writing the data. The data read/written is in the

form of „nmemb‟ elements each „size‟ bytes long.In case of success, fread/fwrite

return the number of bytes actually read/written from/to the stream opened by fopen

function. In case of failure, a less number of byes (then requested to read/write) is

returned.

Writing to a text file

Example 1: Write to a text file using fprintf()

#include <stdio.h>

int main()

{

int num;

FILE *fptr;

fptr = fopen("C:\\program.txt","w");

if(fptr == NULL)

{

printf("Error!");

exit(1);

}

Page 150: Chapter One Overview of the Programming Languages

printf("Enter num: ");

scanf("%d",&num);

fprintf(fptr,"%d",num);

fclose(fptr);

return 0;

}

This program gets a number from user and stores in the file program.txt. Then you

compile and run this program, you can see a text file program.txt created in C drive of

your computer. When you open the file, you can see the integer you entered.

File Opening Modes

C library function - fopen()

Description

The C library function FILE *fopen(const char *filename, const char *mode) opens

the filename pointed to, by filename using the given mode.

Declaration

Given is the declaration for fopen() function.

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

Page 151: Chapter One Overview of the Programming Languages

Parameters

filename − This is the C string containing the name of the file to be opened.

mode − This is the C string containing a file access mode. It includes −

Mode Description

"r" Opens a file for reading. The file must exist.

"w" Creates an empty file for writing. If a file with the same name exists, its content

is erased and the file is assumed as a new empty file.

"a" Attaches to a file. Writing operations, attaches data at the end of the file. The file is created if it does not present.

"r+" Opens a file to update both reading and writing. The file must present.

"w+" Creates an empty file for both reading and writing.

"a+" Opens a file for reading and appending.

Return Value

This function returns a FILE pointer. Otherwise, NULL is returned and the global variable errno

is set to indicate the error.

Example

The following example shows the usage of fopen() function.

#include <stdio.h>

#include <stdlib.h>

int main()

{

FILE * fp;

Page 152: Chapter One Overview of the Programming Languages

fp = fopen ("file.txt", "w+");

fprintf(fp, "%s %s %s %d", "We", "are", "in", 2012);

fclose(fp);

return(0);

}

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)

{

Page 153: Chapter One Overview of the Programming Languages

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,

};

Page 154: Chapter One Overview of the Programming Languages

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

Page 155: Chapter One Overview of the Programming Languages

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 */

Page 156: Chapter One Overview of the Programming Languages

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

Page 157: Chapter One Overview of the Programming Languages

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

right operand.

Page 158: Chapter One Overview of the Programming Languages

return 0;

}

This program reads the integer present in the program.txt file and prints it onto the screen.

Enumerated Data Type with practical

When you create an enumerated type, only outline for the variable is created. you can create

variables of enum type.

enum boolean { false, true };

enum boolean check;

There is a variable check of type enum boolean is created.

There is a another way to declare similar check variable using other syntax.

enum boolean

{

false, true

} check;

Page 159: Chapter One Overview of the Programming Languages

Example: Enumeration Type #include <stdio.h>

enum week { sunday, monday, tuesday, wednesday, thursday, friday, saturday };

int main()

{

enum week today;

today = wednesday;

printf("Day %d",today+1);

return 0;

}

fscanf(fptr,"%d", &num);

printf("Value of n=%d", num);

fclose(fptr);

Output

Day 4

Uses of Enumerated Data Type with practical

Enum variable takes only one value out of many possible values. Example to explain it,

#include <stdio.h>

enum suit {

club = 0,

diamonds = 10,

Page 160: Chapter One Overview of the Programming Languages

hearts = 20,

spades = 3

} card;

int main()

{

card = club;

printf("Size of enum variable = %d bytes", sizeof(card));

return 0;

}

Output

Size of enum variable = 4 bytes