<<

Introduction to programming with -19CSE23 Module 1

Hardware Components

Processor, memoryand Input/Output devices, are the important components of adigital computer. Processor will have ALU (Arithmetic Logic Unit) and Control Unit(CU) as its components. Memory can be subdivided into primary and secondary memory. Input devices accept data and control signals from the user. Examples of input devices are keyboard, mouse, pen based systems, data scanners, game controllers, voice recognition systems etc. Output devices communicate the processed data to the user. Examples of output devices are Monitor, Printer, Plotter, sound system etc.

Processor

Central Processing Unit (CPU) -It is the brain of the computer. It performs the bulk ofthe data processing operations. The function of the processor is to fetch the instructionfrom memory, examine (decode) the instruction and execute the instructions. It consists of Control unit, Arithmetic Logic Unit (ALU) and registers. Control unit is responsible for fetching the instructions from memory and interpreting them. ALU performs arithmetic and logical operations. Registers are very high speed memory unitsfor storing very small amount of data. Program counter, Instruction register, Memoryaddress register, memory buffer register and accumulator are some examples of registers.Bus is a collection of wires. They may be unidirectional or bidirectional. Bus is usedto connect different parts of a computer. Bus may be serial or parallel. USB is anexample of a serial bus. Bus connecting computer and a dot matrix printer is normallya parallel bus. Parallel bus carries several bits at a time. These bits may indicateinstruction, data, address or commands. Bus width and Bus speed are the two major components for performance measure of a computer.

Memory

In the memory, the information is stored in terms of bits or bytes or words. Byte ismade of 8 bits and word is a collection of 16, 32 or 64 bits. Memory can be volatile ornon volatile. Information present in Volatile memory is lost as soon as the power isturned off. Figure-1 gives the classification of memory devices in a digital computer. Secondary memories are non volatile in nature. Examples of secondary memoryinclude Hard disk, Pen drive, DVD-ROM, Recordable DVD,CD-RW, Blue-Ray,Magnetic tapes. Main memory devices are ones in which any memory location can beaccessed in any order (not necessarily in a sequential order). RAM (Random AccessMemory) and ROM(Read Only Memory) are the two types of main memory devices.RAM is also called Read-Write Memory. It is volatile memory. ROM is non- volatilememory. It is also considered an example of firmware. Cache memory is a memory placed between CPU and main memory. It contains a partof main memory content. Processor when needs some information, first looks in thecache. If not found in cache, the portion of memory containing the needed information ismoved to the cache and is also read by the processor. Both internal and external cache memories are volatile in nature. External cache is mounted on the motherboard. Registers are small memory units internally available within the processor.

C Language : An Introduction

C is a procedural programming language. It was initially developed by Dennis Ritchie between 1969 and 1973. It was mainly developed as a system programming language to write operating system. The main features of C language include low-level access to memory, simple set of keywords, and clean style, these features make C language suitable for system programming like operating system or compiler development. Many later languages have borrowed syntax/features directly or indirectly from C language. Like syntax of Java, PHP, JavaScript and many other languages is mainly based on C language. C++ is nearly a superset of C language (There are few programs that may compile in C, but not in C++).

Basic Structure of a C program

1. Documentation section:

The documentation section consists of a set of comment lines giving the name of the program, the author and other details, which the programmer would like to use later.

2. Link section: The link section provides instructions to the compiler to link functions from the system library such as using the #include directive. 3. Definition section: The definition section defines all symbolic constants such using the #define directive. 4. Global declaration section: There are some variables that are used in more than one function. Such variables are called global variables and are declared in the global declaration section that is outside of all the functions. This section also declares all the user-defined functions. 5. main () function section: Every C program must have one main function section. This section contains two parts; declaration part and executable part 1. Declaration part: The declaration part declares all the variables used in the executable part. 2. Executable part: There is at least one statement in the executable part. These two parts must appear between the opening and closing braces. The program executionbegins at the opening brace and ends at the closing brace. The closing brace of the main function is the logical end of the program. All statements in the declaration and executable part end with a semicolon. 6. Subprogram section: If the program is a multi-function program then the subprogram section contains all the user-defined functions that are called in the main () function. User-defined functions are generally placed immediately after the main () function, although they may appear in any order.

All section, except the main () function section may be absent when they are not required.

2) Writing first program:

Following is first program in C

#include void main() { printf("Welcome to C Programming!!");

}

Output:

Welcome to C Programming!!

Let us analyze the program line by line. Line 1: [ #include ] In a C program, all lines that start with # are processed by preprocessor which is a program invoked by the compiler. In a very basic term, preprocessor takes a C program and produces another C program. The produced program has no lines starting with #, all such lines are processed by the preprocessor. In the above example, preprocessor copies the preprocessed code of stdio.h to our file. The .h files are called header files in C. These header files generally contain declaration of functions. We need stdio.h for the function printf() used in the program.

Line 2 [voidmain() ] There must to be starting point from where execution of compiled C program begins. In C, the execution typically begins with first line of main(). The void written before main indicates return type of main(). The value returned by main indicates status of program termination.

Line 3 and 6: [ { and } ] In C language, a pair of curly brackets define a scope and mainly used in functions and control statements like if, else, loops. All functions must start and end with curly brackets.

Line 4 [ printf(“Welcome to C Programming!!");”); ]printf() is a standard library function to print something on standard output. The semicolon at the end of printf indicates line termination. In C, semicolon is always used to indicate end of statement.

Interesting Facts about Macros and Preprocessors in C

In a C program, all lines that start with # are processed by preprocessor which is a special program invoked by the compiler. In a very basic term, preprocessor takes a C program and produces another C program without any #.

Following are some interesting facts about preprocessors in C. 1) When we use includedirective, the contents of included header file (after preprocessing) are copied to the current file. Angular brackets < and > instruct the preprocessor to look in the standard folder where all header files are held. Double quotes “ and“ instruct the preprocessor to look into the current folder and if the file is not present in current folder, then in standard folder of all header files. 2) When we use define for a constant, the preprocessor produces a C program where the defined constant is searched and matching tokens are replaced with the given expression. For example in the following program max is defined as 100.

#include #define max 100 int main() { printf("max is %d", max); return 0; } // Output: max is 100 // Note that the max inside "" is not replaced

4) The macro arguments are not evaluated before macro expansion. For example consider the following program

#include #define MULTIPLY(a, b) a*b int main() { // The macro is expended as 2 + 3 * 3 + 5, not as 5*8 printf("%d", MULTIPLY(2+3, 3+5)); return 0; } // Output: 16

Benefits of C language

1. As a middle level language, C combines the features of both high level and low level languages. It can be used for low-level programming, such as scripting for drivers and kernels and it also supports functions of high level programming languages, such as scripting for software applications etc. 2. C is a structured programming language which allows a complex program to be broken into simpler programs called functions. It also allows free movement of data across these functions. 3. Various features of C including direct access to machine level hardware APIs, presence of C compilers, deterministic resource use and dynamic memory allocation make C language an optimum choice for scripting applications and drivers of embedded systems. 4. C language is case-sensitive which means lowercase and uppercase letters are treated differently. 5. C is highly portable and is used for scripting system applications which form a major part of Windows, UNIX and Linux operating system. 6. C is a general purpose programming language and can efficiently work on enterprise applications, games, graphics, and applications requiring calculations etc. 7. C language has a rich library which provides a number of built-in functions. It also offers dynamic memory allocation.

Escape Sequences in C

In C programming language, there are 256 numbers of characters in character set. The entire character set is divided into 2 parts i.e. the ASCII characters set and the extended ASCII characters set. But apart from that, some other characters are also there which are not the part of any characters set, known as ESCAPE characters.

List of Escape Sequences

\a Alarm or Beep \b Backspace \f Form Feed \n New Line \r Carriage Return \t Tab (Horizontal) \v Vertical Tab \\ \' Single Quote \" Double Quote \? \ooo number \xhh number \0 Null

C Tokens

A token is the smallest element of a program that is meaningful to the compiler. Tokens can be classified as follows:

1. Keywords 2. Identifiers 3. Constants 4. Strings 5. Special Symbols 6. Operators

Keyword: Keywords are pre-defined or reserved words in a programming language. Each keyword is meant to perform a specific function in a program. Since keywords are referred names for a compiler, they can’t be used as variable names because by doing so, we are trying to assign a new meaning to the keyword which is not allowed. You cannot redefine keywords. However, you can specify text to be substituted for keywords before compilation by using C/C++ preprocessor directives.C language supports 32 keywords which are given below:

1. auto double intstruct 2. break else long switch 3. case enum register typedef 4. char extern return union 5. const float short unsigned 6. continue for signed void 7. default gotosizeof volatile 8. do if static while

While in C++ there are 31 additional keywords other than C Keywords they are:

asmbool catch class const_cast delete dynamic_cast explicit export false friend inline mutable namespace new operator private protected public reinterpret_cast static_cast template this throw true try typeidtypename using virtual wchar_t

Identifiers: Identifiers are used as the general terminology for naming of variables, functions and arrays. These are user defined names consisting of arbitrarily long sequence of letters and digits with either a letter or the underscore(_) as a first character. Identifier names must differ in spelling and case from any keywords. You cannot use keywords as identifiers; they are reserved for special use. Once declared, you can use the identifier in later program statements to refer to the associated value. A special kind of identifier, called a statement label, can be used in gotostatements.

There are certain rules that should be followed while naming c identifiers:

. They must begin with a letter or underscore(_). . They must consist of only letters, digits, or underscore. No other special character is allowed. . It should not be a keyword. . It must not contain white space. . It should be up to 31 characters long as only first 31 characters are significant.

Some examples of c identifiers:

name Remark _A9 Valid Temp.var Invalid as it contains special character other than the underscore void Invalid as it is a keyword

C program:

void main() { int a = 10; }

In the above program there are 2 identifiers:

6. main: method name. 7. a: variable name.

Constants: Constants are also like normal variables. But, only difference is, their values can not be modified by the program once they are defined. Constants refer to fixed values. They are also called as literals. Constants may belong to any of the data type.Syntax:

const

data_typevariable_name; (or) constdata_type *variable_name;

Types of Constants:

Integer constants – Example: 0, 1, 1218, 12482

Real or Floating point constants – Example: 0.0, 1203.03, 30486.184

Octal & Hexadecimal constants – Example: octal: (013 )8 = (11)10, Hexadecimal: (013)16 = (19)10

Character constants -Example: ‘a’, ‘A’, ‘z’

String constants -Example: “GeeksforGeeks”

Strings: Strings are nothing but an array of characters ended with a (‘\0’).This null character indicates the end of the string. Strings are always enclosed in double quotes. Whereas, a character is enclosed in single quotes in C and C++.Declarations for String:

. char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘\0’}; . char string[20] = “geeksforgeeks”; . char string [] = “geeksforgeeks”;

Difference between above declarations are: when we declare char as “string[20]”, 20 bytes of memory space is allocated for holding the string value.

When we declare char as “string[]”, memory space will be allocated as per the requirement during execution of the program

Special Symbols: The following special symbols are used in C having some special meaning and thus, cannot be used for some other purpose.[] () {}, ; * = #

Brackets[]: Opening and closing brackets are used as array element reference. These indicate single and multidimensional subscripts.

Parentheses(): These special symbols are used to indicate function calls and function parameters.

Braces{}: These opening and ending curly braces marks the start and end of a block of code containing more than one executable statement. comma (, ): It is used to separate more than one statements like in for loop is separates initialization, condition and increment. semi colon : It is an operator that essentially invokes something called an initialization list. asterick (*): It is used to create pointer variable. assignment operator: It is used to assign values. pre processor(#): The preprocessor is a macro processor that is used automatically by the compiler to transform your program before actual compilation.

Operators: Operators are symbols that triggers an action when applied to C variables and other objects. The data items on which operators act upon are called operands. Depending on the number of operands that an operator can act upon, operators can be classified as follows:

Unary Operators: Those operators that require only single operand to act upon are known as unary operators.For Example increment and decrement operators

Binary Operators: Those operators that require two operands to act upon are called binary operators. Binary operators are classified into :

1. Arithmetic operators 2. Relational Operators 3. Logical Operators 4. Assignment Operators 5. Conditional Operators 6. Bitwise Operators Ternary Operators:These operators requires three operands to act upon. For Example Conditional operator(?:).

Variables and Keywords in C

A variable in simple terms is a storage place which has some memory allocated to it. So basically a variable used to store some form of data. Different types of variables require different amounts of memory and have some specific set of operations which can be applied on them.

Variable Declaration: A typical variable declaration is of the form: typevariable_name; or for multiple variables: type variable1_name, variable2_name, variable3_name;

A variable name can consist of alphabets (both upper and lower case), numbers and the underscore ‘_’ character. However, the name must not start with a number.

Difference b/w variable declaration and definition Variable declaration refers to the part where a variable is first declared or introduced before its first use. Variable definition is the part where the variable is assigned a memory location and a value. Most of the times, variable declaration and definition are done together

See the following C program for better clarification:

#include intmain() { // declaration and definition of variable 'a123' chara123 = 'a'; // This is also both declaration and definition as 'b' is allocated // memory and assigned some garbage value. floatb; // multiple declarations and definitions int_c, _d45, e; // Let us print a variable printf("%c \n", a123); return0; }

Output: a

Keywords are specific reserved words in C each of which has a specific feature associated with it. Almost all of the words which help us use the functionality of the C language are included in the list of keywords. So you can imagine that the list of keywords is not going to be a small one!

There are a total of 32 keywords in C: auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while const: const can be used to declare constant variables. Constant variables are variables which when initialized, can’t change their value. Or in other words, the value assigned to them is unmodifiable. Syntax: constdata_typevar_name = var_value;

Note: Constant variables need to be compulsorily be initialized during their declaration itself. const keyword is also used with pointers. Please refer the const qualifier in C for understanding the same. static: static keyword is used to declare static variables which are popularly used while writing programs in C language. Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve the value of their last use in their scope. So we can say that they are initialized only once and exist till the termination of the program. Thus, no new memory is allocated because they are not re-declared. Their scope is local to the function to which they were defined. Global static variables can be accessed anywhere in the program. By default, they are assigned the value 0 by the compiler. Syntax: staticdata_typevar_name = var_value;

How are variables scoped in C – Static or Dynamic?

In C, variables are always statically (or lexically) scoped i.e., binding of a variable can be determined by program text and is independent of the run-time function call stack.

For example, output for the below program is 0, i.e., the value returned by f() is not dependent on who is calling it. f() always returns the value of global variable x. intx = 0; intf() { returnx; } intg() { intx = 1; returnf(); } intmain() { printf("%d", g()); printf("\n"); getchar(); }

Scope rules in C

Scope of an identifier is the part of the program where the identifier may directly be accessible. In C, all identifiers are lexically (or statically) scoped. C scope rules can be covered under following two categories.

Global Scope: Can be accessed anywhere in a program.

// filename: file1.c inta; intmain(void) { a = 2; } // filename: file2.c // When this file is linked with file1.c, functions of this file can access a externinta; intmyfun() { a = 2; }

To restrict access to current file only, global variables can be marked as static.

Block Scope: A Block is a set of statements enclosed within left and right braces ({ and } respectively). Blocks may be nested in C (a block may contain other blocks inside it). A variable declared in a block is accessible in the block and all inner blocks of that block, but not accessible outside the block. What if the inner block itself has one variable with the same name? If an inner block declares a variable with the same name as the variable declared by the outer block, then the visibility of the outer block variable ends at the pint of declaration by inner block. intmain() { { intx = 10, y = 20; { // The outer block contains declaration of x and y, so // following statement is valid and prints 10 and 20 printf("x = %d, y = %d\n", x, y); { // y is declared again, so outer block y is not accessible // in this block inty = 40;

x++; // Changes the outer block variable x to 11 y++; // Changes this block's variable y to 41

printf("x = %d, y = %d\n", x, y); }

// This statement accesses only outer block's variables printf("x = %d, y = %d\n", x, y); } } return0; }

Output: x = 10, y = 20 x = 11, y = 41 x = 11, y = 20

What about functions and parameters passed to functions? A function itself is a block. Parameters and other local variables of a function follow the same block scope rules.

Can variables of block be accessed in another subsequent block?* No, a variabled declared in a block can only be accessed inside the block and all inner blocks of this block. For example, following program produces compiler error. intmain() {

{

intx = 10;

}

{

printf("%d", x); // Error: x is not accessible here

}

return0;

}

Output: error: 'x' undeclared (first use in this function)

As an exercise, predict the output of following program. intmain() { intx = 1, y = 2, z = 3; printf(" x = %d, y = %d, z = %d \n", x, y, z); { intx = 10; floaty = 20; printf(" x = %d, y = %f, z = %d \n", x, y, z); { intz = 100; printf(" x = %d, y = %f, z = %d \n", x, y, z); } } return0; }

C Input/Output Statements

Unformatted I/O functions There are mainly six unformatted I/O functions discussed as follows: a)getchar() b)putchar() c)gets() d)puts() e)getch() f)getche() a) getchar()

This function is an Input function. It is used for reading a single character from the keyborad. It is buffered function. Buffered functions get the input from the keyboard and store it in the memory buffer temporally until you press the Enter key.

The general syntax is as: v = getchar(); where v is the variable of character type. For example: char n; n = getchar();

A simple C-program to read a single character from the keyboard is as:

/*To read a single character from the keyboard using the getchar() function*/ main() { charn; n = getchar(); }

b) putchar()

This function is an output function. It is used to display a single character on the screen. The general syntax is as: putchar(v); where v is the variable of character type. For example: char n; putchar(n);

A simple program is written as below, which will read a single character using getchar() function and display inputted data using putchar() function:

/*Program illustrate the use of getchar() and putchar() functions*/ main() { char n; n = getchar(); putchar(n); }

c) gets()

This function is an input function. It is used to read a string from the keyboar. It is also buffered function. It will read a string, when you type the string from the keyboard and press the Enter key from the keyboard. It will mark nulll character ('\0') in the memory at the end of the string, when you press the enter key. The general syntax is as: gets(v); where v is the variable of character type. For example: char n[20]; gets(n);

A simple C program to illustrate the use of gets() function:

/*Program to explain the use of gets() function*/ main() { char n[20]; gets(n); }

d) puts()

This is an output function. It is used to display a string inputted by gets() function. It is also used to display an text (message) on the screen for program simplicity. This function appends a ("\n") character to the output.

The general syntax is as: puts(v); or puts("text line"); where v is the variable of character type. A simple C program to illustrate the use of puts() function:

/*Program to illustrate the concept of puts() with gets() functions*/ main() { char name[20]; puts("Enter the Name"); gets(name); puts("Name is :"); puts(name); }

OUTPUT IS: Enter the Name Laura Name is: Laura

e) getch()

This is also an input function. This is used to read a single character from the keyboard like getchar() function. But getchar() function is a buffered is function, getchar() function is a non- buffered function. The character data read by this function is directly assign to a variable rather it goes to the memory buffer, the character data directly assign to a variable without the need to press the Enter key. Another use of this function is to maintain the output on the screen till you have not press the Enter Key. The general syntax is as: v = getch(); where v is the variable of character type. A simple C program to illustrate the use of getch() function:

/*Program to explain the use of getch() function*/ main() { char n; puts("Enter the Char"); n = getch(); puts("Char is :"); putchar(n); getch(); }

OUTPUT IS: Enter the Char Char is L f) getche()

All are same as getch(0 function execpt it is an echoed function. It means when you type the character data from the keyboard it will visible on the screen. The general syntax is as: v = getche(); where v is the variable of character type. A simple C program to illustrate the use of getch() function:

/*Program to explain the use of getch() function*/ main() { char n; puts("Enter the Char"); n = getche(); puts("Char is :"); putchar(n); getche(); }

OUTPUT IS: Enter the Char L Char is L

Formatted I/O functions

Formatted I/O functions which refers to an Input or Ouput data that has been arranged in a particular format. There are mainly two formatted I/O functions discussed as follows: a)scanf() b)printf() a) scanf()

The scanf() function is an input function. It used to read the mixed type of data from keyboard. You can read integer, float and character data by using its control codes or format codes. The general syntax is as: scanf("controlstrings",arg1,arg2,...... argn); or scanf("control strings",&v1,&v2,&v3,...... &vn); Where arg1,arg2,...... argn are the arguments for reading and v1,v2,v3,...... vn all are the variables.

The scanf() format code (spedifier) is as shown in the below table: Format Code Meaning %c To read a single character %d To read a signed decimal integer (short) %ld To read a signed long decimal integer %e To read a float value exponential %f To read a float (short0 or a single precision value %lf To read a double precision float value %g To read double float value %h To read short integer %i To read an integer (decimal, octal, hexadecimal) %o To read an octal integer only %x To read a hexadecimal integer only %u To read unsigned decimal integer (used in pointer) %s To read a string %[..] To read a string of words from the defined range %[^] To read string of words which are not from the defined range

/*Program to illustrate the use of formatted code by using the formatted scanf() function */ main() { char n,name[20]; intabc; float xyz; printf("Enter the single character, name, integer data and real value"); scanf("\n%c%s%d%f", &n,name,&abc,&xyz); getch(); }

b) printf()

This ia an output function. It is used to display a text message and to display the mixed type (int, float, char) of data on screen. The general syntax is as: printf("controlstrings",&v1,&v2,&v3,...... &vn); or printf("Message line or text line"); Where v1,v2,v3,...... vn all are the variables. The control strings use some printf() format codes or format specifiers or conversion characters.

These all are discussed in the below table as:

Format Code Meaning %c To read a single character %s To read a string %d To read a signed decimal integer (short) %ld To read a signed long decimal integer %f To read a float (short0 or a single precision value %lf To read a double precision float value %e To read a float value exponential %g To read double float value %o To read an octal integer only %x To read a hexadecimal integer only %u To read unsigned decimal integer (used in pointer)

/*Below the program which show the use of printf() function*/ main() { int a; float b; char c; printf("Enter the mixed type of data"); scanf("%d",%f,%c",&a,&b,&c); getch(); }

Data Types in C

Each variable in C has an associated data type. Each data type requires different amounts of memory and has some specific operations which can be performed over it. Let us briefly describe them one by one:

Following are the examples of some very common data types used in C: char: The most basic data type in C. It stores a single character and requires a single byte of memory in almost all compilers. int: As the name suggests, an int variable is used to store an integer. float: It is used to store decimal numbers (numbers with floating point value) with single precision. double: It is used to store decimal numbers (numbers with floating point value) with double precision. Different data types also have different ranges upto which they can store numbers. These ranges may vary from compiler to compiler. Below is list of ranges along with the memory requirement and format specifiers on 32 bit gcc compiler.

Data Type Memory (bytes) Range Format Specifier shortint 2 -32,768 to 32,767 %hd unsigned short int 2 0 to 65,535 %hu unsignedint 4 0 to 4,294,967,295 %u int 4 -2,147,483,648 to 2,147,483,647 %d longint 4 -2,147,483,648 to 2,147,483,647 %ld unsigned long int 4 0 to 4,294,967,295 %lu longlongint 8 -(2^63) to (2^63)-1 %lld unsigned long longint8 0 to 18,446,744,073,709,551,615 %llu signed char 1 -128 to 127 %c unsigned char 1 0 to 255 %c float 4 %f double 8 %lf long double 12 %Lf

Type modifiers/qualifiers : A type modifiers alter the meaning of the base data type to yield a new type. There are four types of modifiers in C they are

 signed  unsigned  short  long

1. Each of these type modifiers can be applied to the base type int. 2. Type modifiers signed and unsigned can also be applied to the base type char. 3. In addition, long can be applied to double.

Accessibility range Data type Format Memory size

unsigned char %c 1 Byte 0 to 255 char %c 1 Byte -128 to 127 int %d 2 Bytes -32768 to 32767 unsigned int %u 2 Bytes 0 to 65535 long (or) -2147483648 to long int %ld 4 Bytes 2147483647 unsigned long (or) %lu 4 Bytes unsigned long int 0 to 4294967295

3.4*(10 power -38) to float %f 4 Bytes 3.4*(10 power 38)

1.7*(10 power -308) to double %lf 8 Bytes 1.7*(10 power 308)

3.4*(10 power -4932) to long double %Lf 10 Bytes 1.1*(10 power 4932) char[ ] (string) %s

%o Octal Base

%x Hexa decimal base

%p Memory address

Type Conversion in C

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

1. Implicit Type Conversion Also known as ‘automatic type conversion’.

Done by the compiler on its own, without any external trigger from the user.

Generally takes place when in an expression more than one data type is present. In such condition type conversion (type promotion) takes place to avoid lose of data.

All the data types of the variables are upgraded to the data type of the variable with largest data type. bool-> char -> short int ->int -> unsignedint -> long -> unsigned -> longlong -> float -> double -> long double

It is possible for implicit conversions to lose information, signs can be lost (when signed is implicitly converted to unsigned), and overflow can occur (when long long is implicitly converted to float). Example of Type Implicit Conversion:

// An example of implicit conversion #include int main() { int x = 10; // integer x char y = 'a'; // character c

// y implicitly converted to int. ASCII // value of 'a' is 97 x = x + y;

// x is implicitly converted to float float z = x + 1.0;

printf("x = %d, z = %f", x, z); return 0; }

1. Output:

x = 107, z = 108.000000

2. Explicit Type Conversion– This process is also called type casting and it is user defined. Here the user can type cast the result to make it of a particular data type.

The syntax in C:

(type) expression

Type indicated the data type to which the final result is converted.

// C program to demonstrate explicit type casting #include

int main() { double x = 1.2;

// Explicit conversion from double to int int sum = (int)x + 1;

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

return 0; }

Output: sum = 2

Operators in C

Operators are the foundation of any programming language. Thus the functionality of C language is incomplete without the use of operators. Operators allow us to perform different kinds of operations on operands. In C, operators in Can be categorized in following categories:

 Arithmetic Operators (+, -, *, /, %, post-increment, pre-increment, post-decrement, pre- decrement)  Relational Operators (==, != , >, <, >= &<=) Logical Operators (&&, || and !)  Bitwise Operators (&, |, ^, ~, >> and <<)  Assignment Operators (=, +=, -=, *=, etc)  Other Operators (conditional, comma, sizeof, address, redirecton)

Arithmetic Operators: These are used to perform arithmetic/mathematical operations on operands. The binary operators falling in this category are:

o Addition: The ‘+’ operator adds two operands. For example, x+y. o Subtraction: The ‘-‘ operator subtracts two operands. For example, x-y. o Multiplication: The ‘*’ operator multiplies two operands. For example, x*y. o Division: The ‘/’ operator divides the first operand by the second. For example, x/y. o Modulus: The ‘%’ operator returns the remainder when first operand is divided by the second. For example, x%y.

// C program to demonstrate working of binary arithmetic operators #include int main() { int a = 10, b = 4, res;

//printing a and b printf("a is %d and b is %d\n", a, b);

res = a+b; //addition printf("a+b is %d\n", res);

res = a-b; //subtraction printf("a-b is %d\n", res);

res = a*b; //multiplication printf("a*b is %d\n", res);

res = a/b; //division printf("a/b is %d\n", res);

res = a%b; //modulus printf("a%%b is %d\n", res);

return 0; }

Output: a is 10 and b is 4 a+b is 14 a-b is 6 a*b is 40 a/b is 2 a%b is 2

The ones falling into the category of unary arithmetic operators are:

 Increment: The ‘++’ operator is used to increment the value of an integer. When placed before the variable name (also called pre-increment operator), its value is incremented instantly. For example, ++x. And when it is placed after the variable name (also called post-increment operator), its value is preserved temporarily until the execution of this statement and it gets updated before the execution of the next statement. For example, x++.  Decrement: The ‘–‘ operator is used to decrement the value of an integer. When placed before the variable name (also called pre-decrement operator), its value is decremented instantly. For example, –x. And when it is placed after the variable name (also called post-decrement operator), its value is preserved temporarily until the execution of this statement and it gets updated before the execution of the next statement. For example, x–.

// C program to demonstrate working of Unary arithmetic operators #include int main() { int a = 10, b = 4, res;

// post-increment example: // res is assigned 10 only, a is not updated yet res = a++; printf("a is %d and res is %d\n", a, res); //a becomes 11 now

// post-decrement example: // res is assigned 11 only, a is not updated yet res = a--; printf("a is %d and res is %d\n", a, res); //a becomes 10 now

// pre-increment example: // res is assigned 11 now since a is updated here itself res = ++a; // a and res have same values = 11 printf("a is %d and res is %d\n", a, res);

// pre-decrement example: // res is assigned 10 only since a is updated here itself res = --a; // a and res have same values = 10 printf("a is %d and res is %d\n",a,res);

return 0; }

Output: a is 11 and res is 10 a is 10 and res is 11 a is 11 and res is 11 a is 10 and res is 10

Relational Operators: Relational operators are used for comparison of two values. Let’s see them one by one:

 ‘==’ operator checks whether the two given operands are equal or not. If so, it returns true. Otherwise it returns false. For example, 5==5 will return true.  ‘!=’ operator checks whether the two given operands are equal or not. If not, it returns true. Otherwise it returns false. It is the exact boolean complement of the ‘==’ operator. For example, 5!=5 will return false.  ‘>’ operator checks whether the first operand is greater than the second operand. If so, it returns true. Otherwise it returns false. For example, 6>5 will return true.  ‘<‘ operator checks whether the first operand is lesser than the second operand. If so, it returns true. Otherwise it returns false. For example, 6<5 will return false.  ‘>=’ operator checks whether the first operand is greater than or equal to the second operand. If so, it returns true. Otherwise it returns false. For example, 5>=5 will return true.  ‘<=’ operator checks whether the first operand is lesser than or equal to the second operand. If so, it returns true. Otherwise it returns false. For example, 5<=5 will also return true.

// C program to demonstrate working of relational operators #include int main() { int a=10, b=4;

// relational operators // greater than example if (a > b) printf("a is greater than b\n"); else printf("a is less than or equal to b\n");

// greater than equal to if (a >= b) printf("a is greater than or equal to b\n"); else printf("a is lesser than b\n");

// less than example if (a < b) printf("a is less than b\n"); else printf("a is greater than or equal to b\n");

// lesser than equal to if (a <= b) printf("a is lesser than or equal to b\n"); else printf("a is greater than b\n");

// equal to if (a == b) printf("a is equal to b\n"); else printf("a and b are not equal\n");

// not equal to if (a != b) printf("a is not equal to b\n"); else printf("a is equal b\n");

return 0; }

Output: a is greater than b a is greater than or equal to b a is greater than or equal to b a is greater than b a and b are not equal a is not equal to b

Logical Operators: They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition in consideration. They are described below:  Logical AND: The ‘&&’ operator returns true when both the conditions in consideration are satisfied. Otherwise it returns false. For example, a && b returns true when both a and b are true (i.e. non-zero).  Logical OR: The ‘||’ operator returns true when one (or both) of the conditions in consideration is satisfied. Otherwise it returns false. For example, a || b returns true if one of a or b is true (i.e. non-zero). Of course, it returns true when both a and b are true.  Logical NOT: The ‘!’ operator returns true the condition in consideration is not satisfied. Otherwise it returns false. For example, !a returns true if a is false, i.e. when a=0.

// C program to demonstrate working of logical operators #include int main() { int a=10, b=4, c = 10, d = 20;

// logical operators

// logical AND example if (a>b && c==d) printf("a is greater than b AND c is equal to d\n"); else printf("AND condition not satisfied\n");

// logical AND example if (a>b || c==d) printf("a is greater than b OR c is equal to d\n"); else printf("Neither a is greater than b nor c is equal " " to d\n");

// logical NOT example if (!a) printf("a is zero\n"); else printf("a is not zero");

return 0; }

Output:

AND condition not satisfied a is greater than b OR c is equal to d a is not zero

Short-Circuiting in Logical Operators: In case of logical AND, the second operand is not evaluated if first operand is false. For example, program 1 below doesn’t print “GeeksQuiz” as the first operand of logical AND itself is false.

#include #include int main() { int a=10, b=4; bool res = ((a == b) &&printf("GeeksQuiz")); return 0; }

But below program prints “GeeksQuiz” as first operand of logical AND is true.

#include #include int main() { int a=10, b=4; bool res = ((a != b) &&printf("GeeksQuiz")); return 0; }

In case of logical OR, the second operand is not evaluated if first operand is true. For example, program 1 below doesn’t print “GeeksQuiz” as the first operand of logical OR itself is true.

#include #include int main() { int a=10, b=4; bool res = ((a != b) || printf("GeeksQuiz")); return 0; }

But below program prints “GeeksQuiz” as first operand of logical OR is false.

#include #include int main() { int a=10, b=4; bool res = ((a == b) || printf("GeeksQuiz")); return 0; }

Interesting Facts about Bitwise Operators in C

In C, following 6 operators are bitwise operators (work at bit-level) & (bitwise AND) Takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.

| (bitwise OR)Takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 any of the two bits is 1.

^ (bitwise XOR) Takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different.

<< (left shift)Takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift.

>> (right shift)Takes two numbers, right shifts the bits of the first operand, the second operand decides the number of places to shift.

~ (bitwise NOT) Takes one number and inverts all bits of it

Following is example C program.

/* C Program to demonstrate use of bitwise operators */

#include intmain()

{

unsigned chara = 5, b = 9; // a = 5(00000101), b = 9(00001001)

printf("a = %d, b = %d\n", a, b);

printf("a&b = %d\n", a&b); // The result is 00000001

printf("a|b = %d\n", a|b); // The result is 00001101

printf("a^b = %d\n", a^b); // The result is 00001100

printf("~a = %d\n", a = ~a); // The result is 11111010

printf("b<<1 = %d\n", b<<1); // The result is 00010010

printf("b>>1 = %d\n", b>>1); // The result is 00000100

return0;

}

Output: a = 5, b = 9 a&b = 1 a|b = 13 a^b = 12 ~a = 250 b1 = 4

Following are interesting facts about bitwise operators.

1) The left shift and right shift operators should not be used for negative numbersThe result of is undefined behaviour if any of the operands is a negative number. For example results of both -1 << 1 and 1 << -1 is undefined. Also, if the number is shifted more than the size of integer, the behaviour is undefined. For example, 1 << 33 is undefined if integers are stored using 32 bits. See this for more details.

2) The bitwise XOR operator is the most useful operator from technical interview perspective. It is used in many problems. A simple example could be “Given a set of numbers where all elements occur even number of times except one number, find the odd occurring number” This problem can be efficiently solved by just doing XOR of all numbers.

// Function to return the only odd occurring element intfindOdd(intarr[], intn) {

intres = 0, i;

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

res ^= arr[i];

returnres;

}

voidmain() {

intarr[] = {12, 12, 14, 90, 14, 14, 14};

intn = sizeof(arr)/sizeof(arr[0]);

printf("The odd occurring element is %d ", findOdd(arr, n));

return0;

}

// Output: The odd occurring element is 90 The following are many other interesting problems which can be used using XOR operator. Find the Missing Number, swap two numbers without using a temporary variable, A Memory Efficient Doubly Linked List, and Find the two non-repeating elements. There are many more (See this, this, this, this, this and this)

3) The bitwise operators should not be used in place of logical operators. The result of logical operators (&&, || and !) is either 0 or 1, but bitwise operators return an integer value. Also, the logical operators consider any non-zero operand as 1. For example, consider the following program, the results of & and && are different for same operands. intmain()

{

intx = 2, y = 5;

(x& y)? printf("True ") : printf("False ");

(x&& y)? printf("True ") : printf("False ");

return0;

}

// Output: False True

4) The left-shift and right-shift operators are equivalent to multiplication and division by 2 respectively. As mentioned in point 1, it works only if numbers are positive. intmain()

{

intx = 19;

printf("x << 1 = %d\n", x << 1);

printf("x >> 1 = %d\n", x >> 1);

return0;

}

// Output: 38 9

5) The & operator can be used to quickly check if a number is odd or even The value of expression (x & 1) would be non-zero only if x is odd, otherwise the value would be zero. intmain()

{

intx = 19;

(x& 1)? printf("Odd"): printf("Even");

return0;

}

// Output: Odd

6) The ~ operator should be used carefully The result of ~ operator on a small number can be a big number if the result is stored in an unsigned variable. And result may be negative number if result is stored in signed variable (assuming that the negative numbers are stored in 2’s complement form where leftmost bit is the sign bit)

// Note that the output of the following program is compiler dependent intmain()

{

unsigned intx = 1;

printf("Signed Result %d \n", ~x);

printf("Unsigned Result %ud \n", ~x);

return0;

}

/* Output:

Signed Result -2

Unsigned Result 4294967294d */

Interesting facts about Operator Precedence and Associativity

Operator precedence determines which operator is performed first in an expression with more than one operators with different precedence. For example 10 + 20 * 30 is calculated as 10 + (20 * 30) and not as (10 + 20) * 30. Associativity is used when two operators of same precedence appear in an expression. Associativity can be either Left to Right or Right to Left. For example ‘*’ and ‘/’ have same precedence and their associativity is Left to Right, so the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.

Precedence and Associativity are two characteristics of operators that determine the evaluation order of subexpressions in absence of brackets.

1) Associativity is only used when there are two or more operators of same precedence. The point to note is associativity doesn’t define the order in which operands of a single operator are evaluated. For example consider the following program, associativity of the + operator is left to right, but it doesn’t mean f1() is always called before f2(). The output of following program is in-fact compiler dependent. See this for details.

// Associativity is not used in the below program. Output

// is compiler dependent. intx = 0; intf1() {

x = 5;

returnx;

} intf2() {

x = 10;

returnx;

} intmain() {

intp = f1() + f2();

printf("%d ", x);

return0;

}

2) All operators with same precedence have same associativity This is necessary, otherwise there won’t be any way for compiler to decide evaluation order of expressions which have two operators of same precedence and different associativity. For example + and – have same associativity. 3) Precedence and associativity of postfix ++ and prefix ++ are different Precedence of postfix ++ is more than prefix ++, their associativity is also different. Associativity of postfix ++ is left to right and associativity of prefix ++.

Operator Description Associativity ( ) Parentheses (function call) (see Note 1) left-to-right [ ] Brackets (array subscript) . Member selection via object name -> Member selection via pointer ++ — Postfix increment/decrement (see Note 2) ++ — Prefix increment/decrement right-to-left + – Unary plus/minus ! ~ Logical negation/bitwise complement (type) Cast (convert value to temporary value of type) * Dereference & Address (of operand) sizeof Determine size in bytes on this implementation * / % Multiplication/division/modulus left-to-right + – Addition/subtraction left-to-right << >> Bitwise shift left, Bitwise shift right left-to-right < <= Relational less than/less than or equal to left-to-right > >= Relational greater than/greater than or equal to == != Relational is equal to/is not equal to left-to-right & Bitwise AND left-to-right ^ Bitwise exclusive OR left-to-right | Bitwise inclusive OR left-to-right && Logical AND left-to-right | | Logical OR left-to-right ? : Ternary conditional right-to-left = Assignment right-to-left += -= Addition/subtraction assignment *= /= Multiplication/division assignment %= &= Modulus/bitwise AND assignment ^= |= Bitwise exclusive/inclusive OR assignment <<= >>= Bitwise shift left/right assignment , Comma (separate expressions) left-to-right

Expressions and statements

Expression

 Expression is a sequence of operators and operands that specifies computation of a value. An expressions may consist of single entity or some combination of such entities interconnected by one or more operators. In C every expression evaluates to a value i.e., every expression results in some value of a certain type(that can be assigned to a variable). Some examples of expression are shown in the table given below. a+b

3.14*r*r b*b-4*a*c

The statements of a C program, control the flow of program execution. In C language several kinds of statements are available, which can be classified as

1) Expression Statements 2) Compound Statements 3) Control Statements

Expression Statements:Most of the statements in a C program are expression statements. An expression statement consists of an expression followed by a semicolon. The execution of an expression causes the expression to be evaluated.

Examples:7 expression statements are given below

a=10; a+=20; printf(“Hello,Goodmorning!\n”); display(a,b); /*A function call*/ c=a+b; /* An assignment statement*/ c+sum(a+b); /* A valid , but strange statement*/ ; /*An empty or null statement*/

Compound Statements:A compound statement (also called a “block”) typically appears as the body of another statement, such as the if statement, for statement, while statement, etc

It consists of several individual statements enclosed within a pair of braces { }. The individual statements may themselves be expression statements, compound statements or control statements. Unlike expression statements, a compound statements does not end with a semicolon. A typical Compound statements is given below.

{ pi=3.14; area=pi*radius*radius; }

The particular compound statement consists of two assignment-type expression statements.

Control Statements:Statements used to specify the flow of program control; ie, the order in which the instructions in a program must be executed. It is possible to make decisions, to perform tasks repeatedly or to jump from one section of code to another.

There are four types of control statements in C:

1. Decision making statements (Conditional Branching) 2. Selection statements(Multi-way selection-switch statement) 3. Iteration statements (Loop control statements) 4. Jump statements (Unconditional branching)

Sample Questions

Questions CO’s RBT Levels Define tokens in C with examples. CO1,CO2 L1 Explain all the operators present in C. CO1,CO2 L1 Define algorithm and write its uses. CO1,CO2 L1 Define flowchart. List its symbols with meaning. CO1,CO2 L1 Describe the different data types in C with CO1,CO2 L1 example of each Define constant and its classification by giving CO1,CO2 L1 suitable example Differentiate keyword and identifier with rules CO1,CO2 L1 and suitable examples.

Discuss different types of data types available in C CO1,CO2 L2 Language with Memory layout example Explain implicit and explicit type conversion with CO1,CO2 L2 example Explain Logical and Relational operators with CO1,CO2 L2 example of each Explain Bitwise and Conditional operators with CO1,CO2 L2 example of each Explain the structure of a C program. CO1,CO2 L2 Explain the increment and decrement operators in CO1,CO2 L2 C with syntax Discuss && and & operators with suitable CO1,CO2 L2 example. Applyconditional operator into a suitable program CO1,CO2 L3 Develop a Flowchart & write an Algorithm to CO1,CO2 L3 swap three numbers Illustrate conditional operator with syntax and a CO1,CO2 L3 suitable programming example. (a)If a=20 Evaluate a+=a+ ++a CO1,CO2 L4

(b)Solve the expression a+2>b&&!c||a!=d&&a- 2<=e

Where a=11, b=6, c=0, d=7, e=5 Test the following code for ERRORS and write the CO1,CO2 L4 OUTPUTof it. void main() int a ,b , clrscr(); a=5;b=3; d=a+b; d=a-b; d=a/b; Solve the following expressions for CO1,CO2 L4 A=2,b=3,c=4,d=3,e=7. (a) A++ + b++ - ++b / ++c (b) A+b*c&d*e/c (c) (a>b) + |c / d++

Compare the working of increment CO1,CO2 L4 anddecrement operator with example Explain the usage of = and = = operatorwith a CO1,CO2 L4 programming example. Explain standard input, output functions CO1,CO2 L4 (scanf(),printf()) with syntax and programming example. Solve the expression a+2>b&&!c||a!=d&&a-2<=e CO1,CO2 L5

Where a=11, b=6, c=0, d=7, e=5 a)If a=20 Evaluate a+=a+ ++a CO1,CO2 L5 (b) Solve int p=7; int q=2; float r; r=p/q; Find the OUTPUT of the following code : CO1,CO2 L5 #include void main() { int i=1,k=0,j=1,a; a=i++*!k&&j; printf("\n %d",a>1); } Solve the following expressions for CO1,CO2 L5 a=17,b=8,c=4,d=2,e=3. (a) a && b++*d--/e (b) a+b*c&d*e%c Design a flowchart and pseudo code to find sum of CO1,CO2 L6 ‘n’ natural number without using any looping statement. Design a Flowchart & write an Algorithm to swap CO1,CO2 L6 three numbers Write an algorithm to find roots of a quadratic CO1,CO2 L6 equation. Design a Flowchart to find the result of a student CO1,CO2 L6 as distinction, first class, pass, fail and absent. What is the output of the following program CO1,CO2 L6 #include void main() { inti = 0; for (i = 0;i < 5; i++) if (i< 4) { printf("Hello"); break; } } Write a program to swap two numbers without CO1,CO2 L6 using 3rd variable.

MODULE 2

Branching (Conditional and Unconditional branching)

Control Flow

A program consists of a number of statements which are usually executed in sequence. Programs can be much more powerful if we can control the order in which statements are run. Statements fall into three general types;  Assignment statements, where values, usually the results of calculations, are stored in variables.  Input / Output statements, data is read in or printed out.  Control statements, the program makes a decision about which statement should be executed next.

Control statements can be

Branching: Selecting between optional sections of a program.

Looping: Repeating important sections of the program.

Branching:

1) The Simple if statement

if (testExpression)

{

// statements

}

Statement x;

The if statement evaluates the test expression inside the parenthesis.

If the test expression is evaluated to true (nonzero), statements inside the body of if is executed.

If the test expression is evaluated to false (0), statements inside the body of if is skipped from execution and control goes to statement x

Flowchart of if statement .

// Program to display a number if user enters negative number

#include void 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 a negative number %d”,number); } printf("The if statement is easy."); }

Output 1:

Enter an integer: -2

You entered a negative number -2.

The if statement is easy.

Output 2:

Enter an integer: 5

The if statement in C programming is easy.

2) The if else Statement

The if...else statement executes some code if the test expression is true (nonzero) and some other code if the test expression is false (0).

Syntax of if...else if (testExpression) {

// codes inside the body of if

} else {

// codes inside the body of else

} If test expression is true, codes inside the body of if statement is executed and, codes inside the body of else statement is skipped.

If test expression is false, codes inside the body of else statement is executed and, codes inside the body of if statement is skipped.

Flowchart of if...else statement

// Program to check whether an integer entered by the user is odd or even

#include 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); return0; }

Output:1

Enter an integer: 7

7 is an odd integer.

When user enters 7, the test expression ( number%2 == 0 ) is evaluated to false. Hence, the statement inside the body of else statement printf("%d is an odd integer"); is executed and the statement inside the body of if is skipped.

Output:2

Enter an integer: 4

4 is an even integer.

Nested if...else statement (if...elseif....else Statement) The nested if...else statement allows you to check for multiple test expressions and execute different codes for more than two conditions.

Syntax of nested if...else statement. When an if else statement is present inside the body of another “if” or “else” then this is called nested if else. Syntax of Nested if else statement: if(condition){ //Nested if else inside the body of "if" if(condition2){ //Statements inside the body of nested "if" } else{ //Statements inside the body of nested "else" } } else{ //Statements inside the body of "else" } Example of nested if..else

#include int main() { int var1, var2; printf("Input the value of var1:"); scanf("%d",&var1); printf("Input the value of var2:"); scanf("%d",&var2); if(var1 != var2) { printf("var1 is not equal to var2\n"); //Nested if else if(var1 > var2) { printf("var1 is greater than var2\n"); } else { printf("var2 is greater than var1\n"); } } else { printf("var1 is equal to var2\n"); } return0; } Output:

Input the value of var1:12 Input the value of var2:21 var1isnot equal to var2 var2is greater than var1

3) C – else..if ladder statement

The else..if statement is useful when you need to check multiple conditions within the program, nesting of if-else blocks can be avoided using else..if statement.

Syntax of else..if statement: if(condition1) { //These statements would execute if the condition1 is true } elseif(condition2) { //These statements would execute if the condition2 is true } elseif(condition3) { //These statements would execute if the condition3 is true } . . else { //These statements would execute if all the conditions return false. }

Example of else..if statement program check whether a student passed or failed in examination using if statement.

#include #include intmain(){ intmarks;

printf("Enter your marks between 0-100\n"); scanf("%d", &marks); /* Using if else ladder statement to print Grade of a Student */ if(marks >= 90){ /* Marks between 90-100 */ printf("YOUR GRADE : A\n"); } elseif(marks >= 70 && marks < 90){ /* Marks between 70-89 */ printf("YOUR GRADE : B\n"); } elseif(marks >= 50 && marks < 70){ /* Marks between 50-69 */ printf("YOUR GRADE : C\n"); } else{ /* Marks less than 50 */ printf("YOUR GRADE : Failed\n"); }

getch(); return(0); }

Output Enter your marks 96 YOUR GRADE : A Enter your marks 75 YOUR GRADE : B Enter your marks 60 YOUR GRADE : C Enter your marks 35 YOUR GRADE : Failed

Cascaded if..else

A cascading if-else is a composite of if-else statements where the false path of outer if statement is a nested if-else statement. The nesting can continue to several levels. if ( expression ) statement else if (expression ) statement else

if ( expression ) statement

else statement

C switch...case Statement

The if..else..if ladder allows you to execute a block code among many alternatives. If you are checking on the value of a single variable in if...else...if, it is better to use switchstatement.

The switch statement is often faster than nested if...else (not always)

Syntax of switch...case

switch (int_expr)

{ case constant1:

// code to be executed if n is equal to constant1; break;

case constant2:

// code to be executed if n is equal to constant2; break;

. .

. default:

// code to be executed if n doesn't match any constant

}

When a case constant is found that matches the switch expression, control of the program passes to the block of code associated with that case.

In the above pseudocode, suppose the value of n is equal to constant2. The compiler will execute the block of code associate with the case statement until the end of switch block, or until the break statement is encountered.

The break statement is used to prevent the code running into the next case. switch Statement Flowchart

Example: switch Statement

// Program to create a simple calculator // Performs addition, subtraction, multiplication or division depending the input from user

# include int main(){ charoperator; doublefirstNumber,secondNumber; printf("Enter an operator (+, -, *, /): "); scanf("%c",&operator); printf("Enter two operands: "); scanf("%lf %lf",&firstNumber,&secondNumber); switch(operator) { case'+': printf("%.1lf + %.1lf = %.1lf",firstNumber,secondNumber,firstNumber+secondNumber); break; case'-': printf("%.1lf - %.1lf = %.1lf",firstNumber,secondNumber,firstNumber-secondNumber); break; case'*': printf("%.1lf * %.1lf = %.1lf",firstNumber,secondNumber,firstNumber*secondNumber); break; case'/': printf("%.1lf / %.1lf = %.1lf",firstNumber,secondNumber,firstNumber/firstNumber); break;

// operator is doesn't match any case constant (+, -, *, /) default: printf("Error! operator is not correct"); } return0; }

Output

Enter an operator (+, -, *,): -

Enter two operands: 32.5

12.4

32.5 - 12.4 = 20.1

he - operator entered by the user is stored in operator variable. And, two operands 32.5 and 12.4 are stored in variables firstNumber and secondNumber respectively.

Then, control of the program jumps to printf("%.1lf / %.1lf = %.1lf",firstNumber, secondNumber, firstNumber/firstNumber);

Finally, the break statement ends the switch statement.

If break statement is not used, all cases after the correct case is executed.

If none of cases match then default statement is executed.

Unconditional Branching Statements

C – goto statement

When a goto statement is encountered in a C program, the control jumps directly to the label mentioned in the goto statement

Syntax of goto statement in C gotolabel_name; .. .. label_name: C-statements

Example of goto statement

#include int main() { int sum=0; for(int i =0; i<=10; i++){ sum=sum+i; if(i==5){ goto addition; } } addition: printf("%d", sum); return0; } Output:

15 Explanation: In this example, we have a label addition and when the value of i (inside loop) is equal to 5 then we are jumping to this label using goto. This is reason the sum is displaying the sum of numbers till 5 even though the loop is set to run from 0 to 10.

It is sometimes desirable to skip some statements inside the loop or terminate the loop immediately without checking the test expression.

In such cases, break and continue statements are used. break Statement The break statement terminates the loop (for, while and do...while loop) immediately when it is encountered. The break statement is used with decision making statement such as if...else. In C programming, break statement is also used with switch...case statement. Syntax of break statement break;

Flowchart of break statement

How break statement works?

Example #1: break statement

// Program to calculate the sum of maximum of 10 numbers // Calculates sum until user enters positive number

# include void 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); }

Output

Enter a n1: 2.4

Enter a n2: 4.5

Enter a n3: 3.4

Enter a n4: -3

Sum = 10.30

Continue Statement The continue statement skips some statements inside the loop. The continue statement is lso used with decision making statement such as if...else.

Syntax of continue Statement continue; Flowchart of continue Statement

How continue statement works?

// Program to calculate sum of maximum of 10 numbers // Negative numbers are skipped from calculation

# include int main() { int i; double number, sum =0.0; for(i=1; i <=10;++i) { printf("Enter a n%d: ",i); scanf("%lf",&number);

// If user enters negative number, loop is terminated if(number <0.0) { continue; } sum+= number;// sum = sum + number; } printf("Sum = %.2lf",sum); return0; }

Output

Enter a n1: 1.1

Enter a n2: 2.2

Enter a n3: 5.5

Enter a n4: 4.4

Enter a n5: -3.4

Enter a n6: -45.5

Enter a n7: 34.5 Enter a n8: -4.2

Enter a n9: -1000

Enter a n10: 12

Sum = 59.70

In the program, when the user enters positive number, the sum is calculated using sum += number; statement.

When the user enters negative number, the continue statement is executed and skips the negative number from calculation.

Branching & Looping

Looping (repetition)

A set of statements may have to be repeatedly executed for a specified number of times or till a condition is satisfied. The statements that help us to execute a set of statements repeatedly are called looping or repetitive or iterative statements.

There are 3 types of loops in C

 while loop

 for loop

 do-while loop any looping construct will have to perform 3 tasks namely initialization, condition checking and incrementation. The difference between yhe three looping control constructs is the order in which they perform the 3 tasks i.i (initialization, increment, condition checking)

The while loop

It’s a pretest or entry controlled loop and hence the condition is evaluated first and body of the loop is executed only if the condition is true. Its also a condition controlled or event controlled loop.

Syntax initialization;

while(condition)

{

Statement;

updation;

}

Statement;

Working

1. Initialization of loop control variable is done.

2. Next condition is checked

3. If the condition is evaluated to true then control enters the body of the loop and executes the statements in the body.

4. Next updates the loop counter variable after which control goes back to the condition check. If the condition is true, again the body is executed.

5. This process repeats as long as the condition evaluates to be true. Once, the condition evaluates to be false, the control flows to the statement outside the body of the loop.

Example:

/* program to display numbers from 1-10*/

#include

void main()

{

int i;

i=0; /* initialization*/

while(i<=10) /*condition checking*/

{

printf(“%d\n”,i); i++; /*updation*/

}

getch();

}

Note: study corresponding lab programs and the programs given in theory class.

for loop

Using this we can execute set of statements repeatedly for a specified number of times. So it’s also called as counter controlled loop. It’s a pretest or top testing loop.

Syntax

for(initialization;condition check; updation)

{

Statements

}

working:

1. Here initialization, condition check and updation is done in same statement.

2. Initialization of the loop counter is performed

3. Condition is checked. If the condition evaluates to be true , then the control enter the body of the loop. The statements in the body are executed.

4. Updation of the loop counter is performed. After which again the control goes back to condition check. . If the condition is true, again the body is executed.

5. This process repeats as long as the condition evaluates to be true. Once, the condition evaluates to be false, the control flows to the statement outside the body of the loop.

Example:

/* program to display numbers from 1-10*/ #include

void main()

{

int i;

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

{

printf(“%d\n”,i);

}

getch();

}

Note: study corresponding lab programs and the programs given in theory class.

Do-while:

It is post-test or bottom test loop and hence the body of the loop is executed first and then the condition is checked.

Syntax:

Initialization;

do

{

statement;

updation;

}while(condition); [note: there is a semi colon at the end of while]

statements

Working:

1. Initialization is performed first

2. Then the statements inside the body of the loop are executed one after another

3. Updation is performed at the end of the body and then the condition is checked 4. If the condition is evaluated to be true, then the control re-enters the body and executes the statements within the body

5. This process repeats as long as the condition evaluates to be true.

6. When the condition becomes false , the control comes out of the loop body.

Example:

/* program to display numbers from 1-10*/

#include

void main()

{

int i;

i=0; /* initialization*/

do

{

printf(“%d\n”,i);

i++; /*updation*/

}while(i<=10); /*condition checking*/

getch();

}

Note: study corresponding lab programs and the programs given in theory class.

Difference between while-loop and do-while loop

While loop Do-while loop 1 Syntax Syntax:

initialization; Initialization;

while(condition) do

{ {

Statement; statement;

updation; updation;

} }while(condition);

Statement; Statement;

2 It is a top-testing or entry control loop since It is a bottom-testing or exit control the condition is checked in the beginning loop since the condition is checked at itself the bottom of the loop

3 It is pre-test loop and if the expression is It is post-test loop and the body of the evaluated to false in the beginning itself, loop will be executed atleast once then the statements within the body of the even if the condition is false. loop will not be executed even once.

4 Example Example

i=0; i=0;

sum=0; sum=0;

while(i<=n) do

{ {

sum=sum+i; sum=sum+i;

i=i+1; i=i+1;

} } while(i<=n);

Unconditional branching statements: It transfers control from one place to other without checking any condition. Various Unconditional branching statement are:

 goto

 break

 continue

 return (refer 3rd module)

The goto statement

It’s a jump statement that transfers the control to the specified statement in a program. This is an unconditional branch statement. Its identified by symbolic name ending with colon (:).

Syntax

goto label:

here

 goto is a keyword

 label is a variable ending with :

example

sum=0;

i=0;

top: sum=sum+i;

i++;

if(i<=n) goto top;

Disadvantage:

 Its an unstructured programming style.

 Very difficult to read and understand

 Very difficult to debug the programs The break statement

It’s a jump statement which can be used in switch statement and loops.

Working 1. In switch statement it causes control to terminate switch statement and statement following switch statement will be executed.

2. If break is executed in loop(for, while, do-while), the control comes out of the loop and the statement following the loop will be executed.

Note: if break appears in the inner loop of a nested loop, control only comes out of the inner loop.

for(…………)

{

for(…………)

{

…………………..

if(error)

break;

………

}

………………………………

}

Continue statement:

It is used to skip a part of the loop based on some conditions.

Working: On encountering continue statement , the rest of the statements within the body of the loop are skipped and the conditional expression in the loop is executed.

Pictorial representation:

While(expression) do for(exp1;exp2;exp3)

{ { {

Action -1; Action-1; Action-1;

Continue; continue; continue;

Action -n Action-n; Action-n;

} } while(expression); }

Difference between break and continue statement

Break Continue

1 When break is executed, the statements When continue statement is executed , following break are skipped and causes the statements following continue are the loop to be terminated. skipped and causes the loop to be continued with the next iteration

2 It can be used in switch statement to It cannot be used in switch statement transfer the control outside switch

3 Example: Example:

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

{ {

if(i==3) if(i==3)

break; continue;

printf(“%d\t”,i) printf(“%d\t”,i)

} } Output: Output:

1 2 1 2 4 5

Nested loops:

The loop within another loop is called as nested loop.

for( ; ; )

{

…………

for( ; ; )

{

……………….

}

} SAMPLE QUESTIONS

Questions CO’S RBT Levels Explain in brief the simple if, if-else and CO2,CO3 L2 nested if-else statement with example Explain the concept of For, While and CO2,CO3 L2 Do-While loops with example. Explain switch-case statement with CO2,CO3 L2 syntax Discuss break and continue statements CO2,CO3 L2 with an example. Discuss for loop with syntax and an CO2,CO3 L2 example Apply conditional operator into a CO2,CO3 L3 suitable program Develop a Flowchart & write an CO2,CO3 L3 Algorithm to swap three numbers Illustrate conditional operator with CO2,CO3 L3 syntax and a suitable programming example. With example explain the while and do- CO2,CO3 L4 while loop, and justify your opinion which one is best with one scenario Analogy: CO2,CO3 L4 Student is categorized based on the marks they secured in the CIE, the analogy is show below: Marks>=75 Distinction Marks >=60 and <75 First Class Marks >=50 and <60 Second Class Marks >=40 and <50 Third Class Marks <40 Fail Design a flow chart for above scenario with proper message and flow. Design a flowchart and pseudo code to CO2,CO3 L6 find sum of ‘n’ natural number without using any looping statement. Design a Flowchart & write an Algorithm CO2,CO3 L6 to swap three numbers Explain switch-case statement in C with CO2,CO3 L6 an example. Write an algorithm to find roots of a CO2,CO3 L6 quadratic equation. Design a Flowchart to find the result of a CO2,CO3 L6 student as distinction, first class, pass, fail and absent. Write a C program to find whether a CO2,CO3 L6 given year is leap year or not. Write a C program to find the sum of 1st CO2,CO3 L6 100 numbers Write a C program to find the given CO2,CO3 L6 triangle is equilateral, isosceles or scalene. What is the output of the following CO2,CO3 L6 program #include void main() { inti = 0; for (i = 0;i < 5; i++) if (i< 4) { printf("Hello"); break; } } Write a program to find whether a given CO2,CO3 L6 number is even or odd

Write a C program to print 1st ten prime CO2,CO3 L6 numbers. Write a C program to print Fibonacci CO2,CO3 L6 series upto 100. Write aprogram to read a 3 digit number CO2,CO3 L6 and print the digits at units place,10’s place,100’s place. Evaluate the concept of For, While C02,CO3 L5 and Do-While loops with example. Describe for loop with syntax and an CO3 L1 example With example explain the while and C02,CO3 L4 do-while loop, and justify your opinion which one is best with one scenario

Explain the different looping CO3 L2 concepts with example

Apply nested looping in an example C02,CO3 L3 of your own

Write a C program to find the sum of CO3 L6 1st 100 numbers

What is the output of the following CO3 L6 program

#include

void main()

{

Int i = 0;

for (i = 0;i > 5; i++)

if (i> 4)

{

printf(“Hello”);

break;

} }

Write a C program to print 1st ten CO3 L6 prime numbers.

Write a C program to print Fibonacci CO3 L6 series upto 100.

Write a program to read a 3 digit CO3 L6 number and print the digits at units place,10’s place,100’s place.

Write a C program to find the CO3 L6 factorial of a given number.

Write a C program to find the sum of CO3 L6 even and odd numbers

Write a C program to find the CO3 L6 reverse of a given number.

Write a C program to find the given CO3 L6 number is prime or not

Write a C program to generate the CO3 L6 right triangle

1

1 2

1 2 3

1 2 3 4

Module 3 Arrays, Strings AndFunctions

What is function?

A large program can be divided into manageable pieces called modules where each module does a specific task. Each module is called as function. It’s a self contained small program called program segment that carry out some specific, well-defined task.

Its classified into

 Library function/pre-defined function  User defined functions(UDF)

Library functions

The functions written by the manufacturers of c compilers are called library functions. The implementation details of these functions are not known to the programmers. The library functions are also called as predefined or built -in or in- built or standard library functions. C library has a collection of various functions which perform standard and pre-defined tasks. These functions are ready to be used in our program.

Ex: sqrt(x) -computes square root of x

Printf() -used to print data on the screen

Scanf() -used to read data from the keyboard

/* program to demonstrate the use of library function*/

#include

#include void main()

{

floats,n;

printf(“enter value of n\n”);

scanf(“%d”,&n);

s=sqrt(n); printf(“Squareroot=%d\n”,s);

}

Note: declaration of printf and scanf are available in stdio.h and declaration of sqrt is available in math.h header file. main() is a user defined function, it controls and coordinates all the activities by executing each statements in sequence.

Called and calling function

A function that is invoked by writing the name of the function is called “called function” and the invoking function is called “calling function”.

In the above example, main() is calling function and sqrt() is called function

Advantage and disadvantage of using library functions

Advantage:

 The programmer’s job is made easier because, the functions are already available.  It reduces program development time.

Disadvantage:

They are limited in number, programmer cannot completely rely on these library functions.

User –defined functions

The functions written by the user/programmer to do the specific tasks are called user defined functions. They are also called as programmer defined functions.

Elements of user defined function:

 Function definition  Function call  Function declaration

Function definition

The program module that is written to achieve a specific task is called function definition. Each function definition consists of two parts:

 Function header: consisting of datatype of the value returned by the function, the name of the function and parameters.  Function body: consisting of set of statements to do the specific task.

Syntax: return_type function name(parameters)

{

Declaration part;

Executable part;

Return statement;

}

Example: int add(int a, int b) ------ function header

{

int sum;

sum=a+b; function body

return sum;

}

Function header:

It consists of 3 parts.

 Return type: this is the data type of the value that the function is expected to return. The data type can be int, float, char, double, void etc.. (any valid C data type)  Function name: it’s the name of the function. It can be any valid identifier.  Parameters: these are list of variables enclosed within parentheses. All these variables should be separately declared and each declaration should be separated by comma.

Function body:

The compound statement immediately following the function header is function body. It consists of 3 elements.  Declaration: all the variables used in the function body should be declared in the declaration part. But, the variables used in the function header should not be declared again.  Executable part: this part contains statements or instructions that perform the specified activity.  return: it’s a keyword. It’s used to return control to the calling function with/without a value.

Note: if the function is not returning any value, then we need to specify the return type as void.

If return type is not explicitly written, it’s assumed that return type is integer. So, integer is the default return value.

Function declaration

The function should be declared before they are used. This process of declaring the functions before they are used is called function prototype or function declaration.

Function declaration contains only the function header but terminated with semi colon. It informs the compiler about

 The type of value returned by the function  The name of the function  The number of parameters passed to that function  The type of each parameter in the function header

Syntax: type function-name(type p1, type p2, ……… type pn); /*semi colon is must*/ where type – is type of the value returned from the function such as void, int, float etc. function name- name of the function p1,p2,……….pn – are parameters. All the parameters have to be separately declared and each declaration should be separated by comma. ex 1: int add(int a, int b);

Function calls

The method of calling a function to achieve a specified task is called function call. The function can be called by writing the name of the function and passing appropriate number of arguments. The number and the type of the argument in function call should match the number and type of the parameters in function definition.

/* program to demonstrate user defined function*/

#include int add(inta,int b); /*function prototype*/ void main()

{

int result;

result=add(10,20); /* function call*/

printf(“sum=%d\n”,result);

} int add(inta,int b) /*function definition*/

{

returna+b;

}

The sequence of operations performed here are:

 The function add() is called with two arguments 10 and 20  Control is transferred to function add() and the values 10 and 20 are received using the variables a and b.  The result is computed by adding 10 and 20  The result is returned to main() and copied to variable result  The result is displayed n the screen

Rules:

 The number of arguments in the function call must be equal to the number of parameters in function prototype and header.  The type of the arguments arguments in the function call must be equal to the type of parameters in function prototype and header.  A void function doesn’t return a value. So, when a function is called , it can’t be used in an expression or print statement. It can be used only as statement.  If function return type is void, then it should not return any value. It results in syntax error.  Function can return at most one value

Formal parameters and actual parameters

Formal parameter/dummy parameter

The variables defined in the function header of function definition are called formal parameters. All the variables must be separately declared and each declaration must be separated by commas. The formal parameters receive data from actual parameters.

Actual parameters/arguments

The variables that are used in function call are called actual parameters. Using actual parameters, the data can be transferred to the function. The corresponding formal parameters in the function definition receive them. The actual parameter and formal parameter should match in number and type of data.

Categories of functions

Based on the parameters and return value, the functions are categorized as follows:

 Function with no parameters and no return values.  Function with no parameters and return values  Function with parameters and no return values  Function with parameters and return values

Function with no parameters and no return values

This category is called “void function with no parameters”. There is no data transfer between the calling function and called function. So, calling function cannot send values and called function cannot receive the data.

/*program to demonstrate Function with no parameter and no return values*/

#include void add(); void main() {

add(); /*no arguments are passed*/

} void add()

{

inta,b,c;

printf(“enter two numbers\n”);

scanf(“%d%d”,&a,&b);

c=a+b;

printf(“sum=%d\n”,c);

retun; /*returns nothing*/

}

Function with parameters and no return values

This is called “void functions with parameters”. There is a data transfer from the calling function to the called function using parameters. But, no data transfer from called function to the calling function.

/*program to demonstrate Function with parameter and no return values*/

#include void add(intx,int y); void main()

{

inta,b;

printf(“enter two numbers\n”);

scanf(“%d%d”,&a,&b);

add(a,b); /*two arguments are passed to called function*/ } void add(int x, int y)

{

int z;

z=x+y;

printf(“sum=%d\n”,z);

retun; /*returns nothing*/

}

Function with no parameters and return values

There is no data transfer from the calling function to the called function. But, there is data transfer from called function to the calling function. When the function returns a value, the calling function receives one value from the called function.

/*program to demonstrate Function with no parameter and return values*/

#include int add(); void main()

{

int z;

z=add(); /*no arguments passed returned value will be saved in variable z*/

printf(“sum=%d\n”,z);

}

int add()

{

inta,b,c;

printf(“enter two numbers\n”); scanf(“%d%d”,&a,&b);

c=a+b;

return c; /*returns the result to the calling function*/

}

Function with parameters and return values

There is data transfer between calling and called function. When parameters are passed, the called function can receive values from the calling function. When the function returns a value, the calling function can receive a value from the called function.

/*program to demonstrate Function with parameter and return values*/

#include int add(intx,int y); void main()

{

inta,b,c;

printf(“enter two numbers\n”);

scanf(“%d%d”,&a,&b);

c=add(a,b); /*two arguments are passed to the called function and result stored in c*/

printf(“sum=%d\n”,c);

}

int add(int x, int y)

{

int z;

z=x+y;

return z; }

Passing parameters to functions

There are two ways of passing parameters to the function

 Pass by value (call by value)  Pass by address

Pass by value

Here, the values of actual parameters are copied into formal parameters i.e., formal parameters contain only the copy of actual parameters. So, even if the values of the formal parameters changes in the called function, the values of the actual parameters are not changed.

Advantage:

 Makes the functions more self-contained  Protects them against accidental changes.

Disadvantage:

It does not allow information to be transferred back to calling function via arguments.

/*program to demonstrate pass by value(swapping 2 numbers)*/

#include void exchange(intm,int n); void main()

{

int a=10,b=20;

exchange(a,b);

printf(“a=%d\nb=%d\n”,a,b);

} void exchange(intm,int n) {

int temp;

temp=m;

m=n;

n=temp;

}

Output: a=10 b=20

Working:

 Execution starts from main() and the variables a and b are assigned the values 10 and 20 respectively.  The function exchange() is called with actual parameter a and b whose values are 10,20  In exchange() function, the formal parameter m and n receive 10 and 20 repectively.  The values of m and n are exchanged here.  But, the values of actual parameters a and b in function main() have not been exchanged.

Pass by address

Here, when the function is called, the addresses of actual parameters are sent. In the called function, the formal parameters should be declared as pointers with the same type as the actual parameters. The addresses of actual parameter are copied to formal parameter. Using these addresses, the values of the actual parameters can be changed. This way of changing the actual parameters indirectly using its address is called pass by address.

/*program to demonstrate pass by address(swapping 2 numbers)*/

#include void exchange(int *m,int *n); void main()

{

int a=10,b=20; exchange(&a,&b);

printf(“a=%d\nb=%d\n”,a,b);

} void exchange(int *m,int *n)

{

int temp;

temp=*m;

*m=*n;

*n=temp;

}

Output: a=20 b=10

Working:

 Execution starts from main() and variables a and b are assigned 10 and 20 respectively  The function exchange() is called by sending the address of a and b.  In function exchange(), the formal parameters m and n declared using * to hold the addresses of a and b  Using *m and *n we can access the values of a and b and they are exchanged.  When control comes to the calling function, the values of a and b have been exchanged.

Recursion

Calling a same function again and again until some termination conditions are satisfied is called recursion. Recursive function should contain base case and general case. While designing recursive function decide about the base case and general case carefully, it should not generate infinite loop.

Base case is a special case where the solution can be obtained without using the recursion. It is also called as terminal condition. Each recursive function must have a base case. A base case serves two purposes:  It acts as terminating condition  The recursive function obtains the solution from the base case it reaches.

General casethis portion of the code contains the logic required to reduce the size of the problem so as to move towards the base case or terminal condition. Here, each time the function is called, the size of the problem is reduced.

Ex:

/*factorial of a number*/

#include int fact(int m); void main()

{

intn,res;

printf(“enter the number\n”);

scanf(“%d”,&n);

res=fact(n);

printf(“factorial=%d\n”,res);

getch();

} int fact(int m)

{

if(m==0) /*base case*/

return 1;

else

return fact(m-1)*m; /*general case*/

}

Arrays

An array is a collection of similar data items. All elements of the array share a common name. Each element in the array is identified by the subscript (index).

Arrays are classified as

 Single dimensional array  Two dimensional array

Single dimensional arrays

It’s also called as one dimensional array. It’s a linear list consisting of related data items of same type. In memory, all data elements are stored in contiguous memory locations one after the other.

Ex: array containing 5 elements

2 5 10 50 34 21

a[0] a[1] a[2] a[3] a[4] a[5]

Since array is identified by a common name any element in the array can be accessed by specifying its index or subscript. Index gives the position of an element in the array.

Basic properties of an array are:

 The array elements should be of the same data type.  The data items stored contiguously in memory  The subscript of first item is always zero.  Each data item is accessed using the name of the array, but, with different subscripts.  The index of the array is always an integer.

Declaration of single dimensional array

Arrays must be declared and defined before it is used. The declaration informs the compiler about the:

 Type of each element of the array  Name of the array  Number of elements (size of an array)

Syntax:

Data_typearray_name[int expression];

Ex: inta[10]; Here a is an array of 10 integers.

Rules:

 The expression must be enclosed within brackets  The expression can be an integer constant  The expression can be an integer expression without variables.

Initialization of single dimensional arrays

Assigning values to a variable before processing is called initialization. Array elements can be initialized at the time of declaration.

Syntax:

Type array_name[expression]={v1,v2,v3,…………vn};

Where

 Type can be a data type such as int, float, char etc  Array_name is the name of the array.  Expression is an integer and should be enclosed within square brackets.  v1,v2, are values and should be enclosed within ‘{‘ and ‘}’ separated by commas. The value v1 is stored in 0th location, v2 is stored in 1st location and soon.

The various ways of initializing arrays are:

 Initializing all specified memory locations  Partial array initialization  Initialization without size

Initializing all specified memory locations

Ex:

int a[6]={10,15,20,25,30};

10 15 20 25 30 35 a[0] a[1] a[2] a[3] a[4] a[5]

Partial array initialization If the number of values to be initialized is less than the size of the array, then the elements are initialized in the order from 0th location. The remaining locations will be initialized to zero automatically. int a[5]={10,15};

10 15 0 0 0 a[0] a[1] a[2] a[3] a[4]

Initialization without size int a[]={10,20,30,40,50};

10 20 30 40 50 a[0] a[1] a[2] a[3] a[4]

The compiler will calculate the size of the array based on the number of initial values. Here the size is 5.

Reading/writing single dimensional arrays:

Syntax for reading: for(i=0; i

{

scanf(“%d”,&a[i]);

}

Where n is the no. of elements of an array.

Syntax for writing: for(i=0; i

{

printf(“%d\n”,a[i]);

}

Ex:/*program to read n items from the keyboard and display it on the monitor*/

#include void main()

{

int a[25],n ,i;

printf(“enter the no. of elements\n”);

scanf(“%d”,&n);

for(i=0;i

{

scanf(“%d”,&a[i]);

}

printf(“the array elements are\n”);

for(i=0; i

{

printf(“%d\n”, a[i]);

}

getch();

}

Arrays and functions

The arrays can be passed to functions using two methods:

 Passing individual elements of the array  Passing the whole array

Passing individual elements of the array

Individual array elements can be passed to a function like any other variable. But,

 The type of array element passed to the function and the type of parameter in the corresponding function definition should be same.  The array element is passed as a value parameter i.e., any change in the formal parameter will not affect the actual parameter i.e.,array element.

Ex: /* passing individual array element to afunction and print its square*/

#include void print_square(int x); void main()

{

int a[25],n ,i;

printf(“enter the no. of elements\n”);

scanf(“%d”,&n);

for(i=0; i

{

scanf(“%d”,&a[i]);

}

printf(“the square of array elements are\n”);

for(i=0; i

{

print_square(a[i]); /*passing individual array elements*/

}

getch();

} void print_square(int x)

{

printf(“%d”,x*x);

}

Passing the whole array When passing the whole array to a function,

 The function must be called by passing the name of an array  In the function definition, the parameter must be declared as an array of the same type as that of actual parameter. No need to specify the size of the array.

Passing whole array to a function is similar to pass by reference. Any change made to the array in the called function will reflect to the original array.

/*program to reverse array elements*/

#include void reverse(int b[]); void main()

{

int a[5]={10,20,30,40,50};

reverse(a);

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

{

printf(“%d\t”,a[i]);

}

} void reverse(int b[])

{

b[0]=50, b[1]=40,b[2]=30,b[3]=20,b[4]=10;

}

Output:

50 40 30 20 10 Note: in the above program, the parameter b is an array, any change in array b will have the corresponding changes in array a.

Searching

Process of finding a particular item in the large amount of data is called searching. There are 2 searching techniques.

 Linear search  Binary search

Linear search: it’s also called as sequential search. Here, we search for a given element in the list in linear order i.e., one after the other from first element to last element or vice versa. If the element is present, we say search is successful, otherwise, search is unsuccessful.

/*linear search program*/

#include void main()

{

int a[5],n,i,key,found=0;

printf(“Enter the size of array\n”);

scanf(“%d”,&n);

printf(“enter array elements\n”);

for(i=0; i

{

scanf(“%d”,&a[i]);

}

printf(“Enter the element to be srearched\n”);

scanf(“%d”,&key);

for(i=0; i

{

if(key==a[i]) /* compare with all array elements */ {

found=1;

break;

}

}

if(found==1)

printf(“element found at %d position\n”,i);

else

printf(“element not found\n”);

getch();

}

Advantage:

 Very simple approach  Works well for small arrays  Used to search when the elements are not sorted

Disadvantage:

 Less efficient if the array size is large  If the elements are already sorted, linear search is not efficient

Binary search: This technique can be applied if the array elements are sorted.

Working:

 Initialize position of the first element to variable low and position of last element to variable high. i.e., low=0 and high=n-1  Using above initial values obtain the position of middle element as mid=(low+high)/2  The key to be searched is compared with middle element. If the key is same as middle element, then element found and stop searching process. If key is not same as middle element, it may be present in the left part or right part of the array.  If key is less than the middle element, then left part of the array has to be compared from low to mid-1. So change upper bound as high=mid-1  If key is greater than the middle element, then right part of the array has to be compared from mid+1 to high. So change lower bound as low=mid+1 The above 4 steps has to be repeatedly executed as long as low is less than or equal to high. Finally, when the value of low exceeds the value of high indicates that key is not present in the array.

/*binary search program*/

#include void main()

{

int a[5],n,i,key,found=0,low,high;

printf(“Enter the size of array\n”);

scanf(“%d”,&n);

printf(“enter array elements in ascending order\n”);

for(i=0; i

{

scanf(“%d”,&a[i]);

}

printf(“Enter the element to be srearched\n”);

scanf(“%d”,&key);

low=0;

high=n-1;

while(low<=high) /*binary search*/

{

mid=(low+high)/2; /*compute mid*/

if(key==a[mid]) /*compare with mid if its equal stop searching*/

{

found=1; break;

}

else if(key>a[mid])

low=mid+1;

else

high=mid-1;

}

if(found==1)

printf(“element found at %d position\n”,mid);

else

printf(“element not found\n”);

getch();

}

Advantage

 Simple technique  Very efficient searching technique

Disadvantage

 The array elements should be sorted

Sorting

It is the process of arranging the random numbers either in the ascending order or in the descending order. There are many different sorting techniques such as bubble sort, selection sort, merge sort etc.

Bubble sort

Here, compare the adjacent elements. If the number to the left is greater than the number to the right, then exchange them. If the number to the left is not greater than the number to the right, then don’t exchange them. At the end of each pass largest element will be in its sorted position. This is also called as sinking sort.

/*bubble sort*/ #include #include void main() { inti,j,n,a[20],temp; clrscr(); printf("Enter the size: "); scanf("%d",&n); printf("Enter %d numbers \n",n); for(i=0;ia[j+1]) { temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } printf("\nThe sorted array is \n"); for(i=0;i

Advantage

 Very simple and easy to program  Straight forward approach

Disadvantage

 Less efficient  It requires n-1 passes even if the elements are sorted

Two dimensional arrays Arrays with two sets of square brackets [][] are called two dimensional arrays. It’s used when the data items are arranged in row-wise and column wise in a tabular fashion. To identify an item we need to specify two indices: the first index identifies the row number and second index identify the column number of the item.

Declaration of 2D array

Syntax

Data_typearray_name[exp1][exp2];

Where

 Data_type can be int, float, char etc  Array name is the name of the array  Exp1 and exp2 are constant expressions and must be enclosed within square brackets and no variables are allowed.

Ex: int a[10][20]; the array a is an integer array with 10 rows and 20 coloumns. it reserves 10*20=200 locations contiguously one after the other.

Initialization

Data_typearray_name[exp1][exp2]={ {a1,a2,……………an}, {b1,b2, ………….bn}, ……………………………. …………………………….. {z1,z2,……………….zn} }; Where  Data-type can be int,floatetc  Exp1 and exp2 are row and column numbers respectively  A1 to an are the values assigned to 1st row, b1 to bn are the values assigned to 2nd row and so on. Ex: inta[4][3]={ {11,22,33}, {44,55,66}, {77,88,99}, {10,11,12}, }; Pictorial representation of above initialization is as shown below

columns

0 1 2

11 22 33

44 55 66 rows 77 88 99

10 11 12

0 1 2 3

Partial array initialization: if the numbers of values to be initialized are less than the size of the array, then the elements are initialized from left to right one after the other. The remaining locations will be initialized to zero automatically.

ex: int a[4][3]={ {11,22},

{33,44},

{55,66},

{77,88}

};

Reading and writing two-dimensional arrays The elements of the matrix can be accessed in two different ways.

 Row major order  Column major order

Row major order

All elementsare accessed one by one row wise. Here,

 Firstly, all elements in 0th row are accessed  Secondly, all elements in 1st row are accessed  Thirdly, all elements in 3rd row are accessed and so on.

Column major order

All elementsare accessed one by one column wise. Here,

 Firstly, all elements in 0thcolumn are accessed  Secondly, all elements in 1st column are accessed  Thirdly, all elements in 3rd column are accessed and so on.

Reading matrix in row major order for(i=0; i

{

for(j=0; j

{

scanf(“%d”,&a[i][j]);

}

}

Reading matrix in column major order for(i=0; i

{

for(j=0; j

{

scanf(“%d”,&a[j][i]);

} }

Printing(writing) matrix for(i=0; i

{

for(j=0; j

{

printf(“%d\t”,a[i][j]);

}

Printf(“\n”);

}

Example programs

/*program to add two matrices*/

#include void main()

{ int a[10][10],b[10][10],c[10][10],m,n,i,j; printf(“enter the order of matrices\n”); scanf(“%d%d”,&m,&n); printf(“enter the elements of matrix a\n”); for(i=0; i

{

for(j=0; j

{

scanf(“%d”,&a[i][j]);

}

} printf(“enter the elements of matrix b\n”); for(i=0; i

for(j=0; j

{

scanf(“%d”,&b[i][j]);

}

} for(i=0; i

{

for(j=0; j

{

c[i][j]=a[i][j]+b[i][j];

}

} printf(“resultant matrix c is\n”); for(i=0; i

{

for(j=0; j

{

printf(“%d\t”,c[i][j]);

}

printf(“\n”);

} getch();

}

/*matrix multiplication*/ #include #include void main() { int a[10][10],b[10][10],c[10][10]={0}; intm,n,p,q,i,j,k; clrscr(); printf("\n Enter the order of the matrix A :"); scanf("%d%d",&m,&n); printf("\n Enter the order of the matrix B :"); scanf("%d%d",&p,&q); if(n!=p) { printf("multiplication not possible\n"); getch(); exit(0); } printf("\n Enter the elements of matrix A in row major order\n"); for(i=0;i

/*program to find transpose of a matrix*/

#include void main()

{ int a[10][10],b[10][10],m,n,i,j; printf(“enter the order of matrices\n”); scanf(“%d%d”,&m,&n); printf(“enter the elements of matrix a\n”); for(i=0; i

{

for(j=0; j

{

scanf(“%d”,&a[i][j]); }

} for(i=0; i

{

for(j=0; j

{

b[j][i]=a[i][j];

}

} printf(“resultant matrix is\n”); for(i=0; i

{

for(j=0; j

{

printf(“%d\t”,b[i][j]);

} printf(“\n”);

}

getch();

} Strings

A string is an array of characters terminated by NULL character which is denoted by the ‘\0’.

Ex: “VTU” is stored as

V T U \0

Strings are treated as an array of characters. String variable can be declared as char a[20]; the string variable a can hold maximum of 20 characters including null character. String initialization

String input/output functions

 Formatted input function (scanf)  Formatted output function (printf)  Unformatted input function (gets)  Unformatted output function (puts)

Formatted input and output function (scanf,printf)

The format specifier used is %s.

Working

 If white spaces are present before the string, then they are removed from the keyboard buffer  All nonwhite space characters are copied into the array till it finds another white space. Then the copied string is terminated by ‘\0’. Remaining characters are left in the keyboard buffer. char s1[15]; scanf(”%s”,s1); printf(%s\n”,s1);

Unformatted input and output function (gets,puts)

The gets() function used to read a string. It allows us to read al the characters including whitespace into an array. It stops on pressing ENTER key and appends null character to a string.

Syntax: gets(str); the puts() function takes string as a parameter and displays its content on the monitor and prints newline character. puts(str);

/*program to read and display string with white spaces*/

#include void main()

{ charstr[50];

printf(“enter a string\n”);

gets(str);

printf(“Entered string is\n”);

puts(str);

}

Arrays of strings

To create an array of strings, we should use two-dimensional array.

0 Syntax: 1 char a[row][col]; 2 where,

3 a ----- >name of the array

row------>number of strings

4 col------> maximum length of each string

ex: char a[5][20];

above array a can contain at most 5 strings with each string can have at most 20 characters.

char a[4][10]={“ANU”,

“BHANU”,

“DHANYA”,

“MADHU”};

Memory representation 0 1 2 3 4 5 6 7 8 9

A N U \0

B H A N U \0

D H A N Y A \0 M A D H U \0

Reading and writingto an array of strings for(i=0;i

{

scanf(“%s”,a[i]);

} for(i=0;i

{

printnf(“%s\n”,a[i]);

}

String handling functions

String handling functions are defined in string.h header. strlen(str) Returns length of the string str strcpy(dest,src) Copies the source string src to destination string dest strncpy(dest,src,n) Copies at most n characters of the source string src to destination string dest. strcat(str1,str2) Append string str2 to string str1 strncat(str1,str2,n) Append first n characters of string str2 to string str1 strcmp(str1,str2) compare two strings str1,str2 strrev(str) Reverses string

strlen(str)

This function returns the length of the string str i.e., it counts all the characters up to ‘\0’ except \0. So, an empty string has length zero.

/*program to display string length using library function*/

#include #include void main()

{

char s[]=”hello”;

printf(“length of string s=%d\n”,strlen(s);

getch();

}

Output length of string s=5

/*program to display string length without using library function*/

#include void main()

{

char s[]=”hello”;

inti=0;

while(s[i]!=’\0’)

{

i++;

}

printf(“length=%d\n”,i);

getch();

}

Output length=5 strcpy(dest,src)

Copies the contents of source string src to destination string dest including ‘\0’. So, the size of destination string dest should be greater or equal to the size of source string src. After copying, the original contents of destination string dest are lost.

/*program to demonstrate strcpy()*/

#include

#include void main()

{

char s1[]=”hello”;

char s2[10];

strcpy(s2,s1);

printf(“destination string is=%s\n”,s2;

getch();

}

Output destination string is=hello

/*program to demonstrate strcpy() without using library function*/

#include

#include void main()

{

char s1[10], s2[10];

inti;

printf(“enter source string\n”);

gets(s1); i=0;

while(s1[i]!=’\0’)

{

s2[i]=s1[i];

i++;

}

s2[i]=’\0’;

printf(“destination string is=%s\n”,s2;

getch();

}

Output

Enter source string hello destination string is=hello strncpy(dest,src,n);

Heren is the number of characters to be copied.

Working

 If source string is less than n, the entire string is copied from source to destination and then null character is placed at the end.  If the source string src is longer than n characters, only n characters are copied into destination. Then, the destination string will not have a delimiter ‘\0’ and hence it will be invalid string.

Ex: char s1[10]; char s2[8]=”VTU123”; strncpy(s1,s2,5); before copying s1

0 1 2 3 4 5 6 7 8 9

And s2

V T U 1 2 3 \0

0 1 2 3 4 5 6 7

After copying

s1

V T U 1 2 \0

0 1 2 3 4 5 6 7 8 9

And s2

V T U 1 2 3 \0

0 1 2 3 4 5 6 7

strcat(str1,str2)

This function copies all the characters of string str2 to the end of string str1. The delimiter of string str1 is replaced by the first character of str2. The size of str1 should be large enough to store a string whose length is str1+str2.

Str1 h i

Str2 h e l l o

afterstrcat Str1 h i h e l l o \0

Str2 h e l l o

Sample Questions

Questions CO’s RBT Level How functions are categorized. Explain with C02,CO3 L3 an example. Explain the characteristics of 2-Dimensional CO3 L2 array with an example Describe any 3 string handling function with C02,CO3 L1 an example. Explain with an example how arrays can be CO3 L2 passed into a function What are the characteristics of recursive C02,CO3 L4 function? Explain with an example What are arrays? Classify the declaration of CO3 L4 one dimensional and 2 dimensional array. Classify function declaration, function CO3 L4 definition and calling function with example. Classify string manipulation library function CO2, L4 and explain them with example CO3, CO5 Compare the working of recursion in a C CO3 L5 program with example. Develop a C program to search an element CO3 L6 using linear search Develop a C program to search an element CO3 L6 using binary search Develop a C program to arrange elements CO2, L6 in descending order using bubble sort CO3, CO5 Write a program to print the sum of CO2, L6 CO3, CO5 positive and negative numbers and return average value Write a program to find the Fibonacci series CO2, L6 using arrays CO3, CO5 Write a program to find the smallest CO2, L6 element in an array CO3, CO5 Develop a C program to perform addition of CO2, L6 2 matrices CO3, CO5 Develop a C program to perform product of CO2, CO3 L6 2 matrices Develop a C program to implement CO2, CO3 L6 STRCOPY operation that copies one sting STR1 to another string STR2 without using library function Develop a C program to find the Number of CO2, CO3 L6 Vowels, Consonants, Digits and White space in a String Write a program to concatenate 2 strings CO2, CO3 L6 Write a program to find the length of the CO2, CO3 L6 given string Write a program to reverse a given string CO2, CO3 L6 Write a program to find prime and CO2, CO3 L6 Armstrong number using functions Write a program to find the factorial using CO2, CO3 L6 recursion

Module 4

Structures and file management

The type definition

The typedef is a keyword that allows the programmer to create a new datatype name for an already existing data type. i.e it redefines the name of an existing data type.

Syntax: typedef datatype new_name1,new_name2,………………,new_name n; ex: typedef int MARKS,ID_NUMBER; here MARKS & ID_NUMBER are called user defined data types.

Using these types we can decalre variables..

MARKS sub1,sub2,sub3;

The typedef definitions can be placed :

  Prior to the prototype of any function   At the beginning of the program before declaring other variables. 

Advantage:

  Provides a meaningful way of declaring the variables    Increases the readability of the program    Complex and lengthy declaration can be reduced to short and meaningful declaration   Helps us to understand the source code 

Note: The user-defined data type will be in upper case

Example program:

To compute Simple interest

#include typedef float AMOUNT; typedef float TIME; typedef float RATE; void main() { AMOUNT p,si; TIME t; RATE r; printf(“Enter p,t,r\n”); scanf(“%f%f%f”,&p,&t,&r);

Page 1 si=p*t*r/100; printf(“Simple interest=%f\n”,si); } STRUCTURES

Structures:

A structure is a collection of one or more variables of same data type or dissimilar data types, grouped together under a single name.

Example: A student information to be grouped may consists of Name of the student University number Average marks

The general syntax of a structure: struct tagname

{

Type1 member1;

Type2 member2;

};

  Where struct is a keyword which tells the compiler that structure is being defined   Tagname is the name of the structure    Variables in a structure such as member1,member 2 are called as the members of the  structure of fields of the structure.    Members can be int,float,char etc..   There should be semicolon at the end of the closing brace. 

Note:

The structure definition does not reserve any space in memory for the members. It is just a template.

Structure Declaration:

There are 3 different ways to declare a structure:    Tagged structure    Structure without tag   Typedefined structure

Page 2 Tagged structure:

Synatx:

struct tagname { Type1 member1; Type2 member2; }; Example:

struct student { char name[10]; int usn, marks; };   Student is the name of the structure(tag name)    Struct student together represent the data type.   To allocate memory for structure ,variables must be declared. 

Syntax for structure variable declaration: struct tagname v1,v2,....vn;

Example: struct student s1,s2;

Once the variable are declared , memory for the variables s1 amd s2 are allocated. The number of bytes allocated for the variables s1 and s2 are 14 bytes respectively

10 bytes for name

2 bytes for usn

2 bytes for marks

The total size of the memory allocated is the sum of sizes of individual members.

Structure without tag:

The structure without a tag name is called structure without tag.

Syntax:

struct { Type1 member1; Type2 member2;

Page 3 }v1,v2…vn;

Example:

struct { char name[10]; int usn,marks; }s1,s2;

 In the absense of tag name, immediately after the right brace we have to declare the variables. 

Type-defined structure:

The structure definition associated with the keyword typedef is called typedefined structure

Syntax:

typedef struct { Type1 member1; Type2 member2; }TYPE_ID; EXAMPLE:

typedef struct { char name[10]; int usn,marks; }STUDENT;  Struct and typedef are keywords.    STUDENT is the new data type created using typedef which can be used for the variable declaration. 

Syntax for variable declaration:

TYPE_ID v1,v2..vn;

Example:

STUDENT s1,s2;

Structure initialization:

Syntax:

struct tagname variable={v1,v2..vn};

Page 4 Where struct tagname is derived data type

V1,v2..vn are all the intial values

Example:

struct student { char name[10]; int usn, marks; }s1={“ram”,10,90}; (or)

struct student { char name[10]; int usn, marks; }; struct student s1={“ram”,10,90}; (or)

struct student { char name[10]; int usn,marks; } s1={“ram”,10,90},s2={“bheem”,11,99}; Accessing structures:

The member of the structure can be accessed by specifying the variable name followed by a period(.) followed by the member name

Syntax:

Variable.member

Example:

struct student { char name[10]; int usn,marks; } s1={“ram”,10,90}; The members can be accessed as follows:

By specifying S1.name, we can access the string “ram”.

By specifying S1.usn, we can access 10.

Page 5 By specifying S1.marks, we can access 90.

NESTED STRUCTURES:

A structure which includes another strucure is called as nested structure(i.e) a structure can be used a member of another structure.

Example:

struct subject { int marks1; int marks2; int marks3; }; typedef struct { char name[10]; int usn; struct subject marks; }STUDENT; The above structure consists of a member marks whose type is struct subject(another structure). So this is called as nested structure.

STUDENT s;

We can access the fields suing the dot operator as follows: s.name; s.usn; s.marks.marks1; s.marks.marks2; s.marks.marks3;

STRUCTURE CONATINING ARRAYS:

A single or multi dimensional array of int, float,char and double can be used within the structure

Syntax:

Typedef struct { Char name[10]; Int marks[3]; }STUDENT;

Page 6 Delcaring structure variable

STUDENT S;

Accessing members:

S.name; s.marks[0]; s.marks[1]; s.marks[2];

ARRAY OF STRUCTURES:

Like an array of integers we can have an array of structures.

Example:

Suppose we want to store the details of 50 students consisting of name and marks

We can write the definitition as

typedef struct { char name[20]; int marks; }STUDENT; We can declare an array of structures as follows

STUDENT s[50];

The structure elements can be accessed by s[i].name, s[i].marks

Structures and functions:

The structure or structure members can be passed to the function in various ways

  By passing individual members    By passing the whole structure   By passign structures through pointers(Refer module 5) 

By passing individual members:

Program to display the student details

struct student { char name[50];

Page 7 int usn; };  void disp(char name[ ],int usn);------function prototype void main() { struct student s1; printf(“Enter name and usn\n”); scanf(“%s%d”,s1.name,&s1.usn);  disp(s1.name,s1.usn);----- function call getch(); }  void disp(char name[ ],int usn)-- function definition { Printf(“name=%s\n”,name); Printf(“usn=%d\n”,usn); } Explanation:

In the above example , function disp is called by passing individual member of the structure to the user-defined function. In the user-defined function, formal parameters are created to receive the value of name and usn from the actual paramters.

Passing the whole structure:

struct student { char name[50]; int usn; };  void disp(struct student stu);------function prototype

void main() { struct student s1; printf(“Enter name and usn\n”); scanf(“%s%d”,s1.name,&s1.usn);  disp(s1);----- function call getch(); }

 void disp(struct student stu)-- function definition

Page 8 { Printf(“name=%s\n”,stu.name); Printf(“usn=%d\n”,stu.usn); } Explanation:

In the above example, function disp is called by passing whole the structure to the user- defined function. In the user-defined function, formal parameter is declared is of type structure to receive the value of the actual parameter.

FILES

“File is place on the disk where a group of related data is stored”.

DEFINING AND OPENING A FILE

If you want to store the data in a file in the secondary memory we must specify certain things about the file to the os.    File name    Data structure   Purpose

File name:

File name is a string of characters that make up a valid file name for the operating system

It may contain 2 parts, a primary name and an optional period with the extension

Example:

Prog.c

Data.txt

Output.c

Data strucuture:

Data structure of a file is defined as a structure FILE in stdio.h. Therefore all files should be declared as type FILE before they are used.

When we open a file we must specify what we want ot do with the file(i.e) we may write data to the file or read the already existing data .

Syntax for declaring and opening a file:

The first statement declares the variable fp as a pointer to the datatype FILE

Page 9

The second statement opens the named file and assigns an identifier to FILE pointer fp. This pointer contains all the information about the file.

The second parameter specifies the purpose of opening the file. Mode can be    r open the file for reading only    w open the file for writing only   a open the file for appending data

a. When the mode is ‘writing’ , a file with the specified name is created if the file doesn’t exists. The contents are deleted if the file already exists. b. When the purpose is appending , the file opened with the current content safe. A file with the specified name is created if the file doesn’t exists. c. When the purpose is reading and if exists, then the file is opened with the current content safe, otherwise an error occurs.

FILE *P1,*P2,*P3;

P1=fopen(“ABC.TXT”,”r”);

P2=fopen(“xyz.c”,”w”);

P3=fopen(“pgm1.c”,”a”);

CLOSING A FILE:

A file must be closed all operations on it have been completed. It prevents any accidental misuse of a file.

Synatx:

fclose(filepointer);

File input and output functions:

  fscanf() and fprintf()    fgets() and fputs()   fgetc() and fputc()  fscanf() and fprintf():

These functions are identical to printf and scanf except that they work on files.

Syntax: fprintf(fp,”control string”,list); fscanf(fp,”control string”,list);

Page 10

In both the functions, the first parameter is a file pointer which specifies which file has to be used here. The second parameter contains format specifier for the items in the list. The third parameter list can be a variable, constant or string.

Example :

Copying the content of a file containing name and roll no to another file.

#include void main() { FILE *fp1,*fp2; char name[10]; int rollno; fp1=fopen(“file1.txt”,”r”); fp2=fopen(“file2.txt”,”w”); fscanf(fp1,”%s%d”,name,&rollno); fprintf(fp2,” ,”%s\t%d\n”,name,rollno); getch(); }

Fgets() and fputs()

These functions are used to read & write a string of character from and to file.

Syntax of fgets: ps=fgets(str,n,fp);

Here str is an array of characters

n is number of characters to be read from the file

fp is a file pointer

If this function is successful, it returns pointer to the string read in. Otherwise it returns NULL. It reads n-1 character or a newline which ever comes first.If it reads a new line, it retains it as a part of the string and appends a null character. If it does not read a new line then it reads n- 1 characters and appends null character at the end.

Example:

Page 11 Program to read a line from file

#include void main() { FILE *fp; char str[15]; char *ps; fp=fopen(“input.dat”,”r”); ps=fgets(str,10,fp); if(ps!=NULL) { puts(str); } else printf(“unsuccessfulreading”); }

Syntax of fputs:

Fputs(str,fp);

Str string to be written to a file pointed by fp.It doesn’t automatically writes a new line to file.If its present then only it writes.

Example:

void main() { FILE *fp; char str[15]; char *ps; printf(“enter the string\n”); gets(str); fp=fopen(“file.txt”,”w”); fputs(str,fp); fclose(fp); } fgetc and fputc(): fgetc () is used to read a character from the file. fputc() is used write a character to a file.

Syntax:

Page 12 fputc(c,fp1);

C is character to be inserted to a file

Fp1 is a file pointer returned by fopen

C=fgetc(fp1);

Returns a character from the file pointed by fp1.

Example:

Program to copy a single character from one file to another file.

void main() { FILE *fp1,*fp2; char c; fp1=fopen(“f1.txt”,”r”); fp2=fopen(“f2.txt”,”w”); c=fgetc(fp1); fputc(c,fp2); }

MODULE 5:

5.1 Data Structure in C

Data structures are used to store data in a computer in an organized form. In C language Different types of data structures are; Array, Stack, Queue, Linked List, Tree.

 Array: Array is collection of similar data type, you can insert and deleted element form array without follow any order.  Stack: Stack work on the basis of Last-In-First-Out (LIFO). Last entered element removed first.  Queue: Queue work on the basis of First-In-First-Out (FIFO). First entered element removed first.  Linked List: Linked list is the collection of node, Here you can insert and delete data in any order.  Tree: Stores data in a non linear form with one root node and sub nodes.

5.1.1 Array in Data Structure

An Array is a collection of similar data type value in a single variable. An array is a derived data type in C, which is constructed from fundamental data type of C language.

Insert element in array at specific position

#include #include void main() { inti,a[5],no,pos; clrscr(); printf("Enter element in array: "); for(i=0;i<5;i++) { scanf("%d",&a[i]); } printf("\nStored element in array: "); for(i=0;i<5;i++) { printf(" %d",a[i]); } printf("\nEnter position for enter element: "); scanf("%d",&pos); if(pos>5) { printf("\nThis is out of range"); } else { printf("\nEnter new element: "); scanf("%d",&no); --pos; for(i=5;i>=pos;i--) { a[i+1]=a[i]; } a[pos]=no; printf("\nStored data in array: "); for(i=0;i<6;i++) { printf(" %d",a[i]); } } getch(); }

Output Enter elements in array:4 4 2 5 7 Stored data in array:4257 Enter position for enter element:2 Enternew element:8 Stored data in array:42578

Delete array element at specific position

#include void main() { intvectorx[10]; int i, n,pos, element, found =0; printf("Enter how many elements\n"); scanf("%d",&n); printf("Enter the elements\n"); for(i =0; i < n; i++) { scanf("%d",&vectorx[i]); } printf("Input array elements are\n"); for(i =0; i < n; i++) { printf("%d\n",vectorx[i]); } printf("Enter the element to be deleted\n"); scanf("%d",&element); for(i =0; i < n; i++) { if(vectorx[i]== element) { found=1; pos= i; break; } } if(found ==1) { for(i =pos; i < n -1; i++) { vectorx[i]=vectorx[i +1]; } printf("The resultant vector is \n"); for(i =0; i < n -1; i++) { printf("%d\n",vectorx[i]); }

} else printf("Element %d is not found in the vector\n", element);

}

Program Explanation

1. Declare an array, vectorx of some fixed capacity, 10. 2. Take size of the array as input from users. 3. Using for loop, define the elements of the array. 4. Now, take a number form users as input, which needs to be deleted. 5. Run a for loop, comparing each element of the array to that number if both have same magnitude. 6. If the number is present in the array, then save its location. If number is not present in the array, then print appropriate message. 7. Run a for loop from that saved location to the size of array, shifting each element of the array leftwards by one. 8. This way, the number gets deleted. 9. Exit

Runtime Test Cases Enter how many elements 4 Enter the elements 345 234 678 987 Input array elements are 345 234 678 987 Enter the element to be deleted 234 The resultant vector is 345 678 987

5.1.2 Queue in C

Queue is work on the principal of First-In-First-Out (FIFO), it means first entered item remove first. Queue have two end front and rear, from front you can insert element and from rear you can delete element.

Real life example of Queue

A common example of queue is movie theater ticket counter, there first person who stand in front of ticket window take ticket first and remove from line and new person always stand in line from end.

Single-Lane One-Way Road: First car go first

Ticket Counter: First person get ticket first and go out first

Some other Real Life Examples of Queue are

 Queue of processes in OS.  Queue of people at any service point such as ticketing etc.  Queue of packets in data communication.  Queue of air planes waiting for landing instructions.

Application of Queue Data Structure in C

Queues are used for any situation where you want to efficiently maintain a First-in-first out order on some entities. Transport and operations research where various entities are stored and held to be processed later i.e the queue performs the function of a buffer.

In a multitasking operating system, the CPU cannot run all jobs at once, so jobs must be batched up and then scheduled according to some policy. Again, a queue might be a suitable option in this case.

Operation on a queue

The basic operation that can be perform on queue are;

 Insert an element in a queue.  Delete an element from the queue.

Insert an element in a queue.

In queue insert any element form Rear. If you insert new element in queue value of Rear will be increased by 1.

Insert element in queue void insert() { int item; printf("Element : "); scanf("%d",&item); if(front==(rear+1)%3) { printf("Queue is Full"); return; } if(front==-1) { rear=front=0; } else { rear=(rear+1)%3; } cque.cqueue[rear]=item; printf("Successfully Insert"); } Delete any element from the queue.

In queue delete an element form Front. If you delete an element from queue value of Front will be increased by 1.

Delete element from queue voiddel() { intnum; if(front==-1) { printf("Queue Empty"); return; } else { num=cque.cqueue[front]; printf("Deleted item : %d",num); } if(front==rear) { front=-1; } else front=(front+1)%3; } Example of Queue

#include #include void insert(); voiddel(); void display(); structcirc { intcqueue[5]; }; structcirccque; int rear=0,front=-1; void main() { while(1) { intnum; clrscr(); printf("1.Insertion\n2.Deletion\n3.Display\n0.Exit\n"); printf("\n\nSelect Option : "); scanf("%d",&num); switch(num) { case1: insert(); break; case2: del(); break; case3: display(); break; case0: exit(0); break; default: printf("\n\n Invalid Option "); } getch(); } } void insert() { int item; printf("Element : "); scanf("%d",&item); if(front==(rear+1)%3) { printf("Queue is Full"); return; } if(front==-1) { rear=front=0; } else { rear=(rear+1)%3; } cque.cqueue[rear]=item; printf("Successfully Insert"); } voiddel() { intnum; if(front==-1) { printf("Queue Empty"); return; } else { num=cque.cqueue[front]; printf("Deleted item : %d",num); } if(front==rear) { front=-1; } else front=(front+1)%3; } void display() { int i; if(front==-1) { printf("Queue Empty"); return; } else { printf("\n\nItems : "); for(i=front;i<=rear;i++) { printf(" %d",cque.cqueue[i]); } } }

https://www.sitesbay.com/data-structure/c-queue

5.1.3 Linked List in C

Linked list is a special type of data structure where all data elements are linked to one another. Linked list is the collection of nodes and every nodes contains two parts data part and address part.

Why use Linked List

Suppose you want ot store marks of 50 students, so need to write code like below;

Example int marks[50];

But some time you need to store more than 50 students marks, in that case you can not increase memory of array, and some time you need to store less than 50 students marks in this case extra memory will be wastage. To overcome this problem you need to use Linked List because in linked list memory will be created at run time.

Advantages of linked list

 Linked List is Dynamic data Structure.  You can change size of Linked List during program run time.  Insertion and Deletion Operations are Easier, you can insert any node at any place and also delete any node easily..  No memory wastage ,i.e no need to pre-allocate memory  Faster Access time,can be expanded in constant time without memory overhead  You can easily implement Linear Data Structures such as Stack,Queue using Linked list

Advantages of linked list

 Dynamic Data Structure: The size of linked list increase and decrease during program execution.  No memory wastage: In linked list memory will be allocated at the time of program execution so no memory wastage.  Easily insert and delete data: In linked list you can insert any data at specific position and also delete any data from specific position.

Dis-Advantages of linked list

 Need more memory: For store data in linked list you need more memory space, you need memory space for both data and address part.

Real life example of Linked list

A common example of linked list is train, in this case all the buggies are nodes and two coaches are connected using the connectors, peoples seating arrangement inside the coaches is called as data part of linked list while connection between two buggies is address filed of linked list.

Like linked list, trains also have last coach which is not further connected to any of the buggies. Engine can be called as first node of linked list and last buggies are last node of linked list. https://www.sitesbay.com/data-structure/c-linked-list

5.1.4 Stack in C

Stack is linear data structure. In stack addition of new data item and deletion of already existing data item is done from only one end, known as top. Working of stack on the basis of Last-in-First-out (LIFO) principal, it means last entered item remove first.

Real life example of stack

A most popular example of stack is plates in marriage party. Fresh plates are pushed onto to the top and popped from the top.

Stack Operation

In stack data structure mainly perform two operation; push and pop

 pop: In case of stack deletion of any item from stack is called pop.  push: In case of stack Insertion of any item in stack is called push.

Push Operation

In case of stack Insertion of any item in stack is called push. In stack any item is inserted from top of the stack, When you insert any item in stack top will be increased by 1.

Algorithm for push

1. Initialization, set top=-1 2. Repeat step 3 to 5 until top

Example of push item in stack void push() { int item; if(top==size-1) { printf("\n stack is full"); } else { top=top+1; printf("\n\n Enter element in stack: "); scanf("%d",&s.item); s.stack[top]=s.item; } }

POP Operation

In case of stack deletion of any item from stack is called pop. In any item is delete from top of the stack, When you delete any item from stack top will be decreased by 1.

Algorithm for pop

1. Repeated steps 2 to 4 until top>=0 2. Set item=stack[top] 3. Set top=top-1 4. Print "Item deleted" 5. Print "Stack under flow"

Example void pop() { int item; if(top==0) { printf("\nStack is empty: "); } else { s.item=s.stack[top]; top=top-1; printf("deleted data is: %d",s.item); } }

https://www.sitesbay.com/data-structure/c-stack-pop-operation

Example of Stack in C

Program of stack is very simple when you insert any item in stack top will be increased by 1 and when you pop any item from stack top will be decreased by 1. Both insertion and deletion operation in stack perform from top of stack.

Example

#include #include #include

#define size 5 void pop(); void push(); void display(); struct stack { int item; int stack[size]; }s; int top=-1; void push() { if(top==size-1) { printf("\n stack is full"); } else { top=top+1; printf("\n\n Enter element in stack: "); scanf("%d",&s.item); s.stack[top]=s.item; } } void pop() { if(top==0) { printf("\nStack is empty: "); } else { s.item=s.stack[top]; top=top-1; printf("deleted data is: %d",s.item); } } void display() { int i; if(top==0) { printf("\n Stack is empty: "); } else { for(i=top;i>0;i--) { printf("\n%d",s.stack[i]); } } } void main() { charch,c; do { u: clrscr(); printf("\n\n1: push"); printf("\n2: pop"); printf("\n3: display"); printf("\n4: exit"); printf("\nenter your choice: "); scanf("%d",&ch); switch(ch) { case1: up: push(); break; case2: pop(); break; case3: display(); break; case4: exit(0); break; default: printf("\nwrong choice"); } printf("\n\n Pushed an element (Y/N)"); c=getch(); if(c=='y'||c=='Y') { goto up; } else { goto u; } } while(ch!=5); } https://www.sitesbay.com/data-structure/c-stack-example 5.1.5 Binary Tree | Set 1 (Introduction)

Trees: Unlike Arrays, Linked Lists, Stack and queues, which are linear data structures, trees are hierarchical data structures.

Tree Vocabulary: The topmost node is called root of the tree. The elements that are directly under an element are called its children. The element directly above something is called its parent. For example, a is a child of f and f is the parent of a. Finally, elements with no children are called leaves. tree ---- j <-- root / \ f k / \ \ a h z <-- leaves

Why Trees? 1. One reason to use trees might be because you want to store information that naturally forms a hierarchy. For example, the file system on a computer: file system ------/ <-- root / \ ... home / \ ugrad course / / | \ ... cs101 cs112 cs113

2. Trees (with some ordering e.g., BST) provide moderate access/search (quicker than Linked List and slower than arrays). 3. Trees provide moderate insertion/deletion (quicker than Arrays and slower than Unordered Linked Lists). 4. Like Linked Lists and unlike Arrays, Trees don’t have an upper limit on number of nodes as nodes are linked using pointers.

Main applications of trees include: 1. Manipulate hierarchical data. 2. Make information easy to search (see tree traversal). 3. Manipulate sorted lists of data. 4.As a workflow for compositing digital images for visual effects. 5. Router algorithms 6. Form of a multi-stage decision-making (see business chess).

Binary Tree: A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right child.

Binary Tree Representation in C: A tree is represented by a pointer to the topmost node in tree. If the tree is empty, then value of root is NULL. A Tree node contains following parts. 1. Data 2. Pointer to left child 3. Pointer to right child 5.2 Dynamic memory allocation in C

The concept of dynamic memory allocation in c languageenables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.

1. malloc() 2. calloc() 3. realloc() 4. free()

Before learning above functions, let's understand the difference between static memory allocation and dynamic memory allocation.

static memory allocation dynamic memory allocation memory is allocated at compile time. memory is allocated at run time. memory can't be increased while memory can be increased while executing program. executing program. used in array. used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation. malloc() allocates single block of requested memory. calloc() allocates multiple block of requested memory. realloc() reallocates the memory occupied by malloc() or calloc() functions. free() frees the dynamically allocated memory.

For complete tutorial of dynamic memory allocation refer to the link below: https://www.youtube.com/watch?v=xDVC3wKjS64 5.3 C - Preprocessors

The C Preprocessor is not a part of the compiler, but is a separate step in the compilation process. In simple terms, a C Preprocessor is just a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. We'll refer to the C Preprocessor as CPP.

All preprocessor commands begin with a hash symbol (#). It must be the first nonblank character, and for readability, a preprocessor directive should begin in the first column. The following section lists down all the important preprocessor directives −

Sr.No. Directive & Description #define 1 Substitutes a preprocessor macro. #include 2 Inserts a particular header from another file. #undef 3 Undefines a preprocessor macro. #ifdef 4 Returns true if this macro is defined. #ifndef 5 Returns true if this macro is not defined. #if 6 Tests if a compile time condition is true. #else 7 The alternative for #if. #elif 8 #else and #if in one statement. #endif 9 Ends preprocessor conditional. #error 10 Prints error message on stderr. How a Preprocessor works in C?

1. #include

The #include preprocessor directive is used to paste code of given file into current file. It is used include system-defined and user-defined header files. If included file is not found, compiler renders error. It has three variants: #include

This variant is used for system header files. It searches for a file named file in a list of directories specified by you, then in a standard list of system directories.

#include "file"

This variant is used for header files of your own program. It searches for a file named file first in the current directory, then in the same directories used for system header files. The current directory is the directory of the current input file.

#include anything else

This variant is called a computed #include. Any #include directive whose argument does not fit the above two forms is a computed include.

2. Macro's (#define)

Let's start with macro, as we discuss, a macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive.

Syntax

#define token value

There are two types of macros:

1. Object-like Macros 2. Function-like Macros

1. Object-like Macros

The object-like macro is an identifier that is replaced by value. It is widely used to represent numeric constants. For example:

#define PI 3.1415

Here, PI is the macro name which will be replaced by the value 3.14. Let's see an example of Object-like Macros :

#include #define PI 3.1415 main() { printf("%f",PI); }

Output:

3.14000 2. Function-like Macros

The function-like macro looks like function call. For example:

#define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name. Let's see an example of Function-like Macros :

#include #define MIN(a,b) ((a)<(b)?(a):(b)) voidmain(){ printf("Minimum between 10 and 20 is: %d\n",MIN(10,20)); }

Output:

Minimum between 10 and 20 is: 10 Preprocessor Formatting

A preprocessing directive cannot be more than one line in normal circumstances. It may be split cosmetically with Backslash-Newline. Comments containing can also divide the directive into multiple lines. for example, you can split a line cosmetically with Backslash-Newline anywhere:

/* */ # /* */defi\ ne FO\ O 10\ 20 is equivalent into #define FOO 1020.

3. #undef

To undefine a macro means to cancel its definition. This is done with the #undef directive.

Syntax:

#undef token define and undefine example

#include #define PI 3.1415 #undef PI main(){ printf("%f",PI); }

Output:

Compile Time Error: 'PI' undeclared 4. #ifdef

The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code.

Syntax:

#ifdef MACRO //code #endif 5. #ifndef

The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code.

Syntax: #ifndef MACRO //code #endif 6. #if

The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes the code.

Syntax:

#if expression //code #endif 7. #else

The #else preprocessor directive evaluates the expression or condition if condition of #if is false. It can be used with #if, #elif, #ifdef and #ifndef directives.

Syntax:

#if expression //if code #else //else code #endif

Syntax with #elif

#if expression //if code #elif expression //elif code #else //else code #endif

Example

#include #include #define NUMBER 1 voidmain(){ #if NUMBER==0 printf("Value of Number is: %d",NUMBER); #else print("Value of Number is non-zero"); #endif getch(); }

Output

Value of Number is non-zero 8. #error

The #error preprocessor directive indicates error. The compiler gives fatal error if #error directive is found and skips further compilation process.

C #error example

#include #ifndef __MATH_H #error First include then compile #else voidmain(){ float a; a=sqrt(7); printf("%f",a); } #endif

5.4 C - Pointers

Pointers in C are easy and fun to learn. Some C programming tasks are performed more easily with pointers, and other tasks, such as dynamic memory allocation, cannot be performed without using pointers. So it becomes necessary to learn pointers to become a perfect C programmer. Let's start learning them in simple and easy steps.

As you know, every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory. Consider the following example, which prints the address of the variables defined −

Live Demo

#include int main (){ int var1; char var2[10]; printf("Address of var1 variable: %x\n",&var1 ); printf("Address of var2 variable: %x\n",&var2 ); return0; }

When the above code is compiled and executed, it produces the following result −

Address of var1 variable: bff5a400 Address of var2 variable: bff5a3f6

5.4.1 What are Pointers?

A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address. The general form of a pointer variable declaration is − type *var-name;

Here, type is the pointer's base type; it must be a valid C data type and var- name is the name of the pointer variable. The asterisk * used to declare a pointer is the same asterisk used for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Take a look at some of the valid pointer declarations − int *ip; /* pointer to an integer */ double *dp; /* pointer to a double */ float *fp; /* pointer to a float */ char *ch /* pointer to a character */

The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to.

5.4.2 How to Use Pointers?

There are a few important operations, which we will do with the help of pointers very frequently. (a) We define a pointer variable, (b) assign the address of a variable to a pointer and (c) finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. The following example makes use of these operations −

Live Demo

#include int main (){ intvar=20;/* actual variable declaration */ int*ip;/* pointer variable declaration */ ip=&var;/* store address of var in pointer variable*/ printf("Address of var variable: %x\n",&var);

/* address stored in pointer variable */ printf("Address stored in ip variable: %x\n",ip);

/* access the value using the pointer */ printf("Value of *ip variable: %d\n",*ip); return0; }

When the above code is compiled and executed, it produces the following result −

Address of var variable: bffd8b3c Address stored in ip variable: bffd8b3c Value of *ip variable: 20

5.4.3 Key points to remember about pointers in C:

 Normal variable stores the value whereas pointer variable stores the address of the variable.  The content of the C pointer always be a whole number i.e. address.  Always C pointer is initialized to null, i.e. int *p = null.  The value of null pointer is 0.

 & symbol is used to get the address of the variable.  * symbol is used to get the value of the variable that the pointer is pointing to.  If a pointer in C is assigned to NULL, it means it is pointing to nothing.  Two pointers can be subtracted to know how many elements are available between these two pointers.

 But, Pointer addition, multiplication, division are not allowed.  The size of any pointer is 2 byte (for 16 bit compiler).

5.4.4 A Simple Example of Pointers in C

This program shows how a pointer is declared and used. There are several other things that we can do with pointers, we have discussed them later in this guide. For now, we just need to know how to link a pointer to the address of a variable.

Important point to note is: The data type of pointer and the variable must match, an int pointer can hold the address of int variable, similarly a pointer declared with float data type can hold the address of a float variable. In the example below, the pointer and the variable both are of int type.

#include int main() { //Variable declaration intnum=10;

//Pointer declaration int*p;

//Assigning address of num to the pointer p p =# printf("Address of variable num is: %p", p); return0; }

Output:

Address of variable numis:0x7fff5694dc58 C Pointers – Operators that are used with Pointers

Lets discuss the operators & and * that are used with Pointers in C.

5.4.5 “Address of”(&) Operator

We have already seen in the first example that we can display the address of a variable using ampersand sign. I have used &num to access the address of variable num. The & operator is also known as “Address of” Operator. printf("Address of var is: %p",&num);

Point to note: %p is a format specifier which is used for displaying the address in hex format. Now that you know how to get the address of a variable but how to store that address in some other variable? That’s where pointers comes into picture. As mentioned in the beginning of this guide, pointers in C programming are used for holding the address of another variables. Pointer is just like another variable, the main difference is that it stores address of another variable rather than a value.

“Value at Address”(*) Operator

The * Operator is also known as Value at address operator.

How to declare a pointer? int*p1 /*Pointer to an integer variable*/ double*p2 /*Pointer to a variable of data type double*/ char*p3 /*Pointer to a character variable*/ float*p4 /*pointer to a float variable*/

The above are the few examples of pointer declarations. If you need a pointer to store the address of integer variable then the data type of the pointer should be int. Same case is with the other data types.

By using * operator we can access the value of a variable through a pointer. For example: double a =10; double*p; p =&a;

*p would give us the value of the variable a. The following statement would display 10 as output. printf("%d",*p);

Similarly if we assign a value to *pointer like this:

*p =200;

It would change the value of variable a. The statement above will change the value of a from 10 to 200.

Example of Pointer demonstrating the use of & and * #include int main() { /* Pointer of integer type, this can hold the * address of a integer type variable. */ int*p; intvar=10;

/* Assigning the address of variable var to the pointer * p. The p can hold the address of var because var is * an integer type variable. */ p=&var; printf("Value of variable var is: %d",var); printf("\nValue of variable var is: %d",*p); printf("\nAddress of variable var is: %p",&var); printf("\nAddress of variable var is: %p", p); printf("\nAddress of pointer p is: %p",&p); return0; }

Output:

Value of variable varis:10 Value of variable varis:10 Address of variable varis:0x7fff5ed98c4c Address of variable varis:0x7fff5ed98c4c Address of pointer p is:0x7fff5ed98c50

5.4.6 C - Pointer arithmetic

A pointer in c is an address, which is a numeric value. Therefore, you can perform arithmetic operations on a pointer just as you can on a numeric value. There are four arithmetic operators that can be used on pointers: ++, --, +, and -

To understand pointer arithmetic, let us consider that ptr is an integer pointer which points to the address 1000. Assuming 32-bit integers, let us perform the following arithmetic operation on the pointer − ptr++

After the above operation, the ptr will point to the location 1004 because each time ptr is incremented, it will point to the next integer location which is 4 bytes next to the current location. This operation will move the pointer to the next memory location without impacting the actual value at the memory location. If ptr points to a character whose address is 1000, then the above operation will point to the location 1001 because the next character will be available at 1001.

Incrementing a Pointer

We prefer using a pointer in our program instead of an array because the variable pointer can be incremented, unlike the array name which cannot be incremented because it is a constant pointer. The following program increments the variable pointer to access each succeeding element of the array −

Live Demo

#include constint MAX =3; int main (){ intvar[]={10,100,200}; int i,*ptr;

/* let us have array address in pointer */ ptr=var; for( i =0; i < MAX; i++){ printf("Address of var[%d] = %x\n", i,ptr); printf("Value of var[%d] = %d\n", i,*ptr);

/* move to the next location */ ptr++; } return0; }

When the above code is compiled and executed, it produces the following result −

Address of var[0] = bf882b30 Value of var[0] = 10 Address of var[1] = bf882b34 Value of var[1] = 100 Address of var[2] = bf882b38 Value of var[2] = 200 Decrementing a Pointer

The same considerations apply to decrementing a pointer, which decreases its value by the number of bytes of its data type as shown below −

Live Demo

#include constint MAX =3; int main (){ intvar[]={10,100,200}; int i,*ptr;

/* let us have array address in pointer */ ptr=&var[MAX-1]; for( i = MAX; i >0; i--){ printf("Address of var[%d] = %x\n", i-1,ptr); printf("Value of var[%d] = %d\n", i-1,*ptr);

/* move to the previous location */ ptr--; } return0; } When the above code is compiled and executed, it produces the following result −

Address of var[2] = bfedbcd8 Value of var[2] = 200 Address of var[1] = bfedbcd4 Value of var[1] = 100 Address of var[0] = bfedbcd0 Value of var[0] = 10 Pointer Comparisons

Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and p2 point to variables that are related to each other, such as elements of the same array, then p1 and p2 can be meaningfully compared.

The following program modifies the previous example − one by incrementing the variable pointer so long as the address to which it points is either less than or equal to the address of the last element of the array, which is &var[MAX - 1] −

Live Demo

#include constint MAX =3; int main (){ intvar[]={10,100,200}; int i,*ptr;

/* let us have address of the first element in pointer */ ptr=var; i =0; while(ptr<=&var[MAX -1]){ printf("Address of var[%d] = %x\n", i,ptr); printf("Value of var[%d] = %d\n", i,*ptr);

/* point to the previous location */ ptr++; i++; } return0; }

When the above code is compiled and executed, it produces the following result −

Address of var[0] = bfdbcb20 Value of var[0] = 10 Address of var[1] = bfdbcb24 Value of var[1] = 100 Address of var[2] = bfdbcb28 Value of var[2] = 200

Sample Questions

QUESTION RBT COs LEVEL Define a data-structure. List the L1 CO5,CO6 available data structures in C. Define stack. List out the L1 CO5,CO6 applications, and operations performed on stack. Explain the operations performed L2 CO5,CO6 on stack with neat diagrams. Define queue. List out the L1 CO5,CO6 applications, and operations performed on queue. Explain the operations performed L2 CO5,CO6 on queue with neat diagrams. Define linked-list. List out the L1 CO5,CO6 applications, and operations performed on list. Explain the operations performed L2 CO5,CO6 on list with neat diagrams. Define tree. List out the L1 CO5,CO6 applications, and operations performed on tree. Explain the operations performed L2 CO5,CO6 on tree with neat diagrams. Develop a C program to L5 CO5,CO6 demonstrate the operations on stack. Develop a C program to L5 CO5,CO6 demonstrate the operations on queue. List the functions available for L2 CO5,CO6 dynamic memory allocation in C? Explain any 3 with example. Define pointer. What is reference L1 CO5,CO6 and deference operator? Explain the usage of pointers with L2 CO5,CO6 example. Explain pointer arithmetic in C. L2 CO5,CO6 Develop a C program to find the L5 CO5,CO6 variance and standard deviation using pointers. List the preprocessor directives L1 CO5,CO6 available in C and their uses. Develop a C program to L5 CO5,CO6 demonstrate the preprocessor directives. Compare and contrast stacks, L4 CO5,CO6 queues, and lists with examples Compare and contrast malloc(), L4 CO5,CO6 calloc() and realloc() with examples Apply arrays to implement a stack L4 CO5,CO6 operation in C language Compare the operations of stack L6 CO5,CO6 and queue with diagrams. Show the use of malloc(), calloc() L3 CO5,CO6 and realloc() free() functions with examples List the available data structures in L1 CO5,CO6 C. List out the applications, and L1 CO5,CO6 operations performed on stack. List out the applications, and L1 CO5,CO6 operations performed on queue. Define stack. L1 CO5,CO6 Define queue. L1 CO5,CO6 Define linked-list. L1 CO5,CO6 Define pointer. L1 CO5,CO6

Page 13 Sample Questions

RBT

Questions CO’s

Levels

Describe structures. Explain how to declare and initialize a CO4,

L1 structure. CO5

CO4,

Describe file. Explain different modes of files. L1

CO5

What is the output of this C code?

#include

struct student

{

char *name;

};

CO4,

L2

void main() CO5

{

struct student s, m;

s.name = "st";

m = s;

printf("%s%s", s.name, m.name);

}

Explain the operations which are illegal in structure CO4,

L2 implementation CO5

Illustrate with an example how structures are defined, CO4,

L3 declared and initialized. CO5

Illustrate with an example how structure members are CO4,

L3 accessed CO5

CO4,

Illustrate with syntax how a file can be opened and closed. L3

CO5

CO4,

What are the characteristics of files L4

CO5

CO4,

What are the characteristics of structure L4

CO5

Trace the following code and explain what will be the output.

#include struct

{

int i;

float ft;

CO4,

}decl; L5

CO5 int main()

{

decl.i = 4;

decl.ft = 7.96623;

printf("%d %.2f", decl.i, decl.ft);

return 0;

}

What is the similarity between a structure, union and CO4,

L5 enumeration? CO5

Develop a C program to search for a name in an array of CO4,

L6 structure CO5

Develop a C program to read student name and USN from CO4, L6 two different files and write into a different file. CO5

Write a C program to read n numbers from keyboard and CO4,

L6 write into a file. CO5

Write a C program to copy contents of one file to another CO4, L6 file CO5

Write a program to Store Information(name, roll and CO4, L6 marks) of a Student Using Structure CO5

Write a C program to write all the members of an array of

CO4, structures to a file using fwrite(). Read the array from the L6

CO5 file and display on the screen.

Write a C program to read name and marks of n number CO4, of students from user and store them in a file. If the file L6

CO5 previously exits, add the information of n students.

Write a C program to Calculate Difference Between Two CO4, L6

Time Periods using structures. CO5

Page 15