0% found this document useful (0 votes)
10 views

Gopi b.com CA c Notes Final

Uploaded by

t.ambika1991
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Gopi b.com CA c Notes Final

Uploaded by

t.ambika1991
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 84

UNIT I

OVERVIEW OF C:

History of C:

C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie


to develop the UNIX operating system at Bell Labs. C was originally first implemented on the
DEC PDP-11 computer in 1972.

In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available description of
C, now known as the K&R standard. The UNIX operating system, the C compiler, and
essentially all UNIX applications programs have been written in C. The C has now become a
widely used professional language for various reasons.

 Easy to learn
 Structured language

 It produces efficient programs.

 It can handle low-level activities.

 It can be compiled on a variety of computer platforms.

Facts about C

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


 C is a successor of B language which was introduced around 1970

 The language was formalized in 1988 by the American National Standard Institute
(ANSI).

 The UNIX OS was totally written in C by 1973.

 Today C is the most widely used and popular System Programming Language.

 Most of the state-of-the-art software’s have been implemented using C.

 Today's most popular Linux OS and RBDMS MySQL have been written in C.

Why to use C?

C was initially used for system development work, in particular the programs that make-up the
operating system. C was adopted as a system development language because it produces code

1
that runs nearly as fast as code written in assembly language. Some examples of the use of C
might be:

 Operating Systems
 Language Compilers

 Assemblers

 Text Editors

 Print Spoolers

 Network Drivers

 Modern Programs

 Databases

 Language Interpreters

 Utilities

BASIC STRUCTURE OF C PROGRAM:

Before we study basic building blocks of the C programming language, let us look a bare
minimum C program structure so that we can take it as a reference in upcoming chapters.

C Hello World Example

A C program basically consists of the following parts:

 Preprocessor Commands
 Functions

 Variables

 Statements & Expressions

 Comments

Let us look at a simple code that would print the words "Hello World":

#include <stdio.h>

int main()
2
{
/* my first program in C */
printf("Hello, World! \n");

return 0;
}

Let us look various parts of the above program:

1. The first line of the program #includes <stdio.h> is a preprocessor command, which tells
a C compiler to include stdio.h file before going to actual compilation.
2. The next line int main () is the main function where program execution begins.

3. The next line /*...*/ will be ignored by the compiler and it has been put to add additional
comments in the program. So such lines are called comments in the program.

4. The next line printf(...) is another function available in C which causes the message
"Hello, World!" to be displayed on the screen.

5. The next line return 0; terminates main ()function and returns the value 0.

Compile & Execute C Program:

Lets look at how to save the source code in a file, and how to compile and run it. Following are
the simple steps:

1. Open a text editor and add the above-mentioned code.


2. Save the file as hello.c

3. Open a command prompt and go to the directory where you saved the file.

4. Type gcc hello.c and press enter to compile your code.

5. If there are no errors in your code the command prompt will take you to the next line and
would generate a.out executable file.

6. Now, type a.out to execute your program.

7. You will be able to see "Hello World" printed on the screen

$ gcc hello.c
$. /a.out
Hello, World!

3
Make sure that gcc compiler is in your path and that you are running it in the directory
containing source file hello.c.

CONSTANTS, VARIABLES AND DATA TYPES:

CONSTANTS:

Constants are the terms that can't be changed during the execution of a program. For example: 1,
2.5, "Programming is easy." etc. In C, constants can be classified as:

Integer constants

Integer constants are the numeric constants(constant associated with number) without any
fractional part or exponential part. There are three types of integer constants in C language:
decimal constant(base 10), octal constant(base 8) and hexadecimal constant(base 16) .

 Decimal digits: 0 1 2 3 4 5 6 7 8 9
 Octal digits: 0 1 2 3 4 5 6 7

 Hexadecimal digits: 0 1 2 3 4 5 6 7 8 9 A B C D E F.

For example:

 Decimal constants: 0, -9, 22 etc


 Octal constants: 021, 077, 033 etc
 Hexadecimal constants: 0x7f, 0x2a, 0x521 etc

Notes:

1. You can use small caps a, b, c, d, e, f instead of uppercase letters while writing a
hexadecimal constant.
2. Every octal constant starts with 0 and hexadecimal constant starts with 0x in C
programming.

Floating-point constants

Floating point constants are the numeric constants that have either fractional form or exponent
form. For example:

-2.0
0.0000234
-0.22E-5

Note: Here, E-5 represents 10-5. Thus, -0.22E-5 = -0.0000022.

4
Character constants

Character constants are the constant which use single quotation around characters. For example:
'a', 'l', 'm', 'F' etc.

Escape Sequences

Sometimes, it is necessary to use new line (enter), tab, quotation mark etc. in the program which
either cannot be typed or has special meaning in C programming. In such cases, escape sequence
are used. For example: \n is used for new line. The backslash (\) causes "escape" from the normal
way the characters are interpreted by the compiler.

Escape Sequences

Escape Sequences Character

\b Backspace

\f Form feed

\n New line

\r Return

\t Horizontal tab

\v Vertical tab

\\ Backslash

\' Single quotation mark

\" Double quotation mark

\? Question mark

\0 Null character

String constants

String constants are the constants which are enclosed in a pair of double-quote marks. For
example:

"good" //string constant


5
"" //null string constant
" " //string constant of six white space
"x" //string constant having single character.
"Earth is round\n" //prints string with newline

Enumeration constants

Keyword enum is used to declare enumeration types. For example:

enum color {yellow, green, black, white};

Here, the variable name is color and yellow, green, black and white are the enumeration
constants having value 0, 1, 2 and 3 respectively by default.

DATA TYPES

C language data types can be broadly classified as

Primary (or fundamental) data type


Derived data type
User-defined data type

A programming language is proposed to help programmer to process certain kinds of data


and to provide useful output. The task of data processing is accomplished by executing series of
commands called program. A program usually contains different types of data types (integer,
float, character etc.) and need to store the values being used in the program. C language is rich of
data types. A C programmer has to employ proper data type as per his requirement.

All c compilers support five fundamental data types namely integer (int), character (char),
floating point (float), double precision floating point (double) and void. The basic four types are

i) Integer types

a) Integer

signed : int short int long int

unsigned : unsigned int unsigned short int unsigned long int

b) character

char signed char unsigned char


6
c) Floating type

float double long double

d) void

Integer types:

Integers are whole numbers with a range of values, range of values are machine
dependent. Generally an integer occupies 2 bytes memory space and its value range limited to -
32768 to +32767 (that is, -215 to +215-1). A signed integer use one bit for storing sign and rest
15bits for number.
To control the range of numbers and storage space, C has three classes of integer storage
namely short int, int and long int. All three data types have signed and unsigned forms.

A short int requires half the amount of storage than normal integer. Unlike signed integer,
unsigned integers are always positive and use all the bits for the magnitude of the number.
Therefore the range of an unsigned integer will be from 0 to 65535. The long integers are used to
declare a longer range of values and it occupies 4 bytes of storage space.

Syntax: int <variable name>; like


int num1;
short int num2;
long int num3;

Example: 5, 6, 100, 2500.

Integer Data Type Memory Allocation

Floating Point Types:

7
The float data type is used to store fractional numbers (real numbers) with 6 digits of
precision. Floating point numbers are denoted by the keyword float. When the accuracy of the
floating point number is insufficient, we can use the double to define the number. The double is
same as float but with longer precision and takes double space (8 bytes) than float. To extend the
precision further we can use long double which occupies 10 bytes of memory space.

Syntax: float <variable name>; like


float num1;
double num2;
long double num3;

Example: 9.125, 3.1254.

Floating Point Data Type Memory Allocation

Character Type:

Character type variable can hold a single character. As there are singed and unsigned int
(either short or long), in the same way there are signed and unsigned chars; both occupy 1 byte
each, but having different ranges. Unsigned characters have values between 0 and 255, signed
characters have values from –128 to 127.

Syntax: char <variable name>; like


char ch = ‘a’;
Example: a, b, g, S, j.
Void Type:

The void type has no values therefore we cannot declare it as variable as we did in case of
integer and float.
The void data type is usually used with function to specify its type. Like in our first C

8
program we declared “main()” as void type because it does not return any value. The concept of
returning values will be discussed in detail in the C function hub.

2. Secondary Data Types

 Array in C programming
An array in C language is a collection of similar data-type, means an array can hold
value of a particular data type for which it has been declared. Arrays can be created from
any of the C data-types int,
 Pointers in C Programming
A pointer is derived data type in c. Pointers contain memory addresses as their values.

 Structure in C Programming
We used variable in our C program to store value but one variable can store only single
piece information (an integer can hold only one integer value) and to store similar type of
values we had to declare...

3. User defined type declaration

C language supports a feature where user can define an identifier that characterizes an
existing data type. In short its purpose is to redefine the name of an existing data type.
Syntax: typedef <type> <identifier>; like
typedef int number;

User defined type declaration

In C language a user can define an identifier that represents an existing data type. The user
defined data type identifier can later be used to declare variables.

The general syntax is


typedef type identifier;
here type represents existing data type and ‘identifier’ refers to the ‘row’ name given to
the data type.
Example:
9
typedef int salary;
typedef float average;
Here salary symbolizes int and average symbolizes float. They can be later used to
declare variables as follows:
Units dept1, dept2;
Average section1, section2;
Therefore dept1 and dept2 are indirectly declared as integer datatype and section1 and
section2 are indirectly float data type.
The second type of user defined datatype is enumerated data type which is defined as
follows.
Enum identifier {value1, value2 …. Value n};
The identifier is a user defined enumerated datatype which can be used to declare
variables that have one of the values enclosed within the braces. After the definition we can
declare variables to be of this ‘new’ type as below.
enum identifier V1, V2, V3, ……… Vn

The enumerated variables V1, V2, ….. Vn can have only one of the values value1, value2
….. value n
Example:
enum day {Monday, Tuesday, …. Sunday};
enum day week_st, week end;
week_st = Monday;
week_end = Friday;
if(wk_st == Tuesday)
week_en = Saturday;

VARIABLES:

Variables are memory location in computer's memory to store data. To indicate the memory
location, each variable should be given a unique name called identifier. Variable names are just
the symbolic representation of a memory location. Examples of variable name: sum, car_no,
count etc.

10
int num;

Here, num is a variable of integer type.

Rules for writing variable name in C


1. Variable name can be composed of letters (both uppercase and lowercase letters), digits
and underscore '_' only.
2. The first letter of a variable should be either a letter or an underscore. But, it is
discouraged to start variable name with an underscore though it is legal. It is because,
variable name that starts with underscore can conflict with system names and compiler
may complain.
3. There is no rule for the length of length of a variable. However, the first 31 characters
of a variable are discriminated by the compiler. So, the first 31 letters of two variables in
a program should be different.

In C programming, you have to declare variable before using it in the program.

CHARACTER SET:

Character set

Character set are the set of alphabets, letters and some special characters that are valid in C
language.

Alphabets:

Uppercase: A B C.................................... X Y Z

Lowercase: a b c...................................... x y z

Digits:

0123456 89

Special Characters:

Special Characters in C language

, < > . _ ( ) ; $ : % [ ] # ?

' & { } " ^ ! * / | - \ ~ +

11
White space Characters:

Blank space, new line, horizontal tab, carriage return and form feed

Keywords:

Keywords are the reserved words used in programming. Each keywords has fixed meaning and
that cannot be changed by user. For example:

int money;

Here, int is a keyword that indicates, 'money' is of type integer.

As, C programming is case sensitive, all keywords must be written in lowercase. Here is the list
of all keywords predefined by ASCII C.

Keywords in C Language

auto double int struct

break Else long switch

case Enum register typedef

char extern return union

continue For signed void

do If static while

default Goto sizeof volatile

const Float short unsigned

Besides these keywords, there are some additional keywords supported by Turbo C.

Additional Keywords for Borland C

asm far Interrupt pascal near huge cdecl

All these keywords, their syntax and application will be discussed in their respective topics.

Identifiers

12
In C programming, identifiers are names given to C entities, such as variables, functions,
structures etc. Identifier are created to give unique name to C entities to identify it during the
execution of program. For example:

int money;
int mango_tree;

Here, money is a identifier which denotes a variable of type integer. Similarly, mango_tree is
another identifier, which denotes another variable of type integer.

Rules for writing identifier

1. An identifier can be composed of letters (both uppercase and lowercase letters), digits
and underscore '_' only.
2. The first letter of identifier should be either a letter or an underscore. But, it is
discouraged to start an identifier name with an underscore though it is legal. It is because;
identifier that starts with underscore can conflict with system names. In such cases,
compiler will complain about it. Some system names that start with underscore are
_fileno, _iob, _wfopen etc.
3. There is no rule for the length of an identifier. However, the first 31 characters of an
identifier are discriminated by the compiler. So, the first 31 letters of two identifiers in a
program should be different.

OPERATORS:

Operators are the symbol which operates on value or a variable. For example: + is a operator to
perform addition. C programming language has wide range of operators to perform various
operations. For better understanding of operators, these operators can be classified as:

Operators in C programming

Arithmetic Operators

Increment and Decrement Operators

Assignment Operators

Relational Operators

Logical Operators

13
Conditional Operators

Bitwise Operators

Special Operators

Arithmetic Operators
Operator Meaning of Operator

+ addition or unary plus

- subtraction or unary minus

* Multiplication

/ Division

% remainder after division( modulo division)

Example of working of arithmetic operators

/* Program to demonstrate the working of arithmetic operators in C. */


#include <stdio.h>
int main(){
int a=9,b=4,c;
c=a+b;
printf("a+b=%d\n",c);
c=a-b;
printf("a-b=%d\n",c);
c=a*b;
printf("a*b=%d\n",c);
c=a/b;
printf("a/b=%d\n",c);
c=a%b;
printf("Remainder when a divided by b=%d\n",c);
return 0;
}
}

OUTPUT:

14
a+b=13
a-b=5
a*b=36
a/b=2
Remainder when a divided by b=1

Explanation

Here, the operators +, - and * performed normally as you expected. In normal calculation, 9/4
equals to 2.25. But, the output is 2 in this program. It is because, a and b are both integers. So,
the output is also integer and the compiler neglects the term after decimal point and shows
answer 2 instead of 2.25. And, finally a%b is 1,i.e. ,when a=9 is divided by b=4, remainder is 1.

Suppose a=5.0, b=2.0, c=5 and d=2


In C programming,
a/b=2.5
a/d=2.5
c/b=2.5
c/d=2

Note: % operator can only be used with integers.

Increment and decrement operators

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

Let a=5 and b=10


a++; //a becomes 6
a--; //a becomes 5
++a; //a becomes 6
--a; //a becomes 5

Difference between ++ and -- operator as postfix and prefix

When i++ is used as prefix(like: ++var), ++var will increment the value of var and then return it
but, if ++ is used as postfix(like: var++), operator will return the value of operand first and then
only increment it. This can be demonstrated by an example:

#include <stdio.h>
int main()
{
int c=2,d=2;
printf("%d\n",c++); //this statement displays 2 then, only c incremented by 1 to 3.
15
printf("%d",++c); //this statement increments 1 to c then, only c is displayed.
return 0;
}

Output

2 4

Assignment Operators

The most common assignment operator is =. This operator assigns the value in right side to the
left side. For example:

var=5 //5 is assigned to var


a=c; //value of c is assigned to a
5=c; // Error! 5 is a constant.
Operator Example Same as

= a=b a=b

+= a+=b a=a+b

-= a-=b a=a-b

*= a*=b a=a*b

/= a/=b a=a/b

%= a%=b a=a%b

Relational Operator

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

a>b. Here, > is a relational operator. If a is greater than b, a>b returns 1 if not then, it
returns 0.

Relational operators are used in decision making and loops in C programming.

16
Operator Meaning of Operator Example

== Equal to 5= =3 returns false (0)

> Greater than 5>3 returns true (1)

< Less than 5<3 returns false (0)

!= Not equal to 5!=3 returns true(1)

>= Greater than or equal to 5>=3 returns true (1)

<= Less than or equal to 5<=3 return false (0)

Logical Operators

Logical operators are used to combine expressions containing relation operators. In C, there are 3
logical operators:

Meaning of
Operator Example
Operator

If c=5 and d=2 then,((c==5) && (d>5))


&& Logical AND
returns false.

If c=5 and d=2 then, ((c==5) || (d>5)) returns


|| Logical OR
true.

! Logical NOT If c=5 then, !(c==5) returns false.

Explanation

For expression, ((c==5) && (d>5)) to be true, both c==5 and d>5 should be true but, (d>5) is
false in the given example. So, the expression is false. For expression ((c= =5) || (d>5)) to be
true, either the expression should be true. Since, (c= =5) is true. So, the expression is true. Since,
expression (c= =5) is true! (c= =5) is false.

17
Conditional Operator

Conditional operator takes three operands and consists of two symbols? and: . Conditional
operators are used for decision making in C. For example:

c=(c>0)?10:-10;

If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10.

Bitwise Operators

A bitwise operator works on each bit of data. Bitwise operators are used in bit level
programming.

Operators Meaning of operators

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

~ Bitwise complement

<< Shift left

>> Shift right

Bitwise operator is advance topic in programming

Other Operators

Comma Operator

Comma operators are used to link related expressions together. For example:

int a,c=5,d;

The sizeof operator

It is a unary operator which is used in finding the size of data type, constant, arrays, structure etc.
For example:

18
#include <stdio.h>
int main(){
int a;
float b;
double c;
char d;
printf("Size of int=%d bytes\n",sizeof(a));
printf("Size of float=%d bytes\n",sizeof(b));
printf("Size of double=%d bytes\n",sizeof(c));
printf("Size of char=%d byte\n",sizeof(d));
return 0;
}

Output

Size of int=4 bytes


Size of float=4 bytes
Size of double=8 bytes
Size of char=1 byte

Conditional operators (? :)

Conditional operators are used in decision making in C programming, i.e, executes different
statements according to test condition whether it is either true or false.

Syntax of conditional operators


conditional_expression? expression1:expression2

If the test condition is true, expression1 is returned and if false expression2 is returned.

Example of conditional operator


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

Output
19
Enter l if the year is leap year otherwise enter n: l
Number of days in February = 29

UNIT II

DECISION MAKING AND BRANCHING:

if, if..Else and Nested if...else Statement:

Decision making are needed when, the program encounters the situation to choose a particular
statement among many statements. In C, decision making can be performed with following two
statements.

1. IF STATEMENT:

if statement syntax

if (test expression){
Statement/s to be executed if test expression is true;
}
If the test expression is true then, statements for the body if, i.e, statements inside parenthesis are
executed. But, if the test expression is false, the execution of the statements for the body of if
statements are skipped.

Flowchart of if statement

20
2. IF...ELSE STATEMENT:

The if...else statement is used, if the programmer wants to execute some code, if the test
expression is true and execute some other code if the test expression is false.

Syntax of if...else

if (test expression)
Statements to be executed if test expression is true;
else
Statements to be executed if test expression is false;

Flowchart of if...else statement

21
Example of if...else statement

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

Output

Enter a number you want to check.


25
25 is odd.

3. NESTED IF...ELSE STATEMENT (IF...ELSE IF....ELSE STATEMENT)

The if...else statement can be used in nested form when a serious decision are involved.

22
Syntax of nested if...else statement.

if (test expression)
statements to be executed if test expression is true;
else
if(test expression 1)
statements to be executed if test expressions 1 is true;
else
if (test expression 2)
.
.
.
else
statements to be executed if all test expressions are false;

How nested if...else works?

If the test expression is true, it will execute the code before else part but, if it is false, the control
of the program jumps to the else part and check test expression 1 and the process continues. If all
the test expression are false then, the last statement is executed.

The ANSI standard specifies that 15 levels of nesting may be continued.

Example of nested if else statement

#include <stdio.h>
int main(){
int numb1, numb2;
printf("Enter two integers to check".\n);
scanf("%d %d",&numb1,&numb2);
if(numb1==numb2) //checking whether two integers are equal.
printf("Result: %d=%d",numb1,numb2);
else
if(numb1>numb2) //checking whether numb1 is greater than numb2.
printf("Result: %d>%d",numb1,numb2);
else
printf("Result: %d>%d",numb2,numb1);
return 0;
}

Output 1

Enter two integers to check.

23
5
3
Result: 5>3

ELSE IF LADDER

There is another way of putting ifs together when multipath decisions are involved. A
multipath decision is a chain of it’s in which the statement associated with each else is an if. It
takes the following general form:

if (condition 1)
statement 1 ;
else if (condition 2)
statement 2;
else if (condition 3)
statement 3;
else if (condition n)
statement n;
else
default statement;
statement x;

This construct is known as the else if ladder. The conditions are evaluated from the top (of the
ladder), downwards. As soon as a true condition is found, the statement associated with is
executed and the control is transferred to the statement x (skipping the rest of the ladder).

When all the n conditions become false, then the final else containing the default
statement will be executed.

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

Syntax of switch...case
24
switch (expression)
{
case constant1:
codes to be executed if expression equals to constant1;
break;
case constant2:
codes to be executed if expression equals to constant3;
break;
.
.
.
default:
codes to be executed if expression doesn't match to any cases;
}

In switch...case, expression is either an integer or a character. If the value of switch expression


matches any of the constant in case, the relevant codes are executed and control moves out of the
switch...case statement. If the expression doesn't matches any of the constant in case, then the
default statement is executed.

Flow chart:

Example of switch...case statement


# include <stdio.h>
int main(){
char operator;
float num1,num2;

25
printf("Enter operator +, - , * or / :\n");
operator=getche();
printf("\nEnter two operands:\n");
scanf("%f%f",&num1,&num2);
switch(operator)
{
case '+':
printf("num1+num2=%.2f",num1+num2);
break;
case '-':
printf("num1-num2=%.2f",num1-num2);
break;
case '*':
printf("num1*num2=%.2f",num1*num2);
break;
case '/':
printf("num2/num1=%.2f",num1/num2);
break;
default:
printf(Error! operator is not correct");
break;
}
return 0;
}

Output
Enter operator +, -, * or /:
/
Enter two operators:
34
3
Num2/num1=11.33

GOTO STATEMENT

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

goto label;
.............
.............
.............
label:
26
statement;

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

Reasons to avoid goto statement

Though, using goto statement give power to jump to any part of program, using goto statement
makes the logic of the program complex and tangled. In modern programming, goto statement is
considered a harmful construct and a bad programming practice.

The goto statement can be replaced in most of C program with the use of break and continue
statements. In fact, any program in C programming can be perfectly written without the use of
goto statement. All programmers should try to avoid goto statement as possible as they can.

DECISION MAKING AND LOOPING:

Loops causes program to execute the certain block of code repeatedly until some conditions are
satisfied, i.e., loops are used in performing repetitive work in programming.

Suppose you want to execute some code/s 10 times. You can perform it by writing that code/s
only one time and repeat the execution 10 times using loop.

There are 3 types of loops in C programming:

 for loop

 while loop

 do...while loop

WHILE LOOP:

Syntax of while loop

while (test expression)

27
{
Statements to be executed.
}

In the beginning of while loop, test expression is checked. If it is true, codes inside the body of
while loop,i.e, code/s inside parentheses are executed and again the test expression is checked
and process continues until the test expression becomes false.

Example of while loop

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

Output

Enter a number.
5
Factorial=120

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

Syntax of do...while loops

do {
some code/s;
}
while (test expression);

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

Notice, there is semicolon in the end of while (); in do...while loop.

Example of do...while loop

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

Enter a number
3
Enter a number
-2
Enter a number
0
sum=1

In this C program, user is asked a number and it is added with sum. Then, only the test condition
in the do...while loop is checked. If the test condition is true, i.e, num is not equal to 0, the body
of do...while loop is again executed until num equals to zero.

FOR LOOP

for Loop Syntax

for(initial expression; test expression; update expression)


{
code/s to be executed;
}

How for loop works in C programming?

The initial expression is initialized only once at the beginning of the for loop. Then, the test
expression is checked by the program. If the test expression is false, for loop is terminated. But,
if test expression is true then, the codes are executed and update expression is updated. Again,
the test expression is checked. If it is false, loop is terminated and if it is true, the same process
repeats until test expression is false.

Flow chart:

30
Example Program:

#include <stdio.h>
int main ()
{
/* for loop execution */
for( int a = 10; a < 20; a = a + 1 )
{
printf("value of a: %d\n", a);
}
return 0;
}

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

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

JUMPS IN LOOPS:

 Loops perform a set of operations repeatedly until the control variables fails
to satisfy the test conditions.

31
 The number of times the loop is repeated is decided in advance and the
test conditions is returned to achieve this.
 Some times, when executing a loop it becomes desirable to skip a part of
the loop or to leave the loop as soon as a certain conditions occurs.
 C permits a jump form one statement to another within a loop as well as jump out
of a loop.
Jumping Out of a Loop:

 Exit from a loop can be accomplished by using the break statement or the goto statement.
 These statements can also be used within while, do or for loops.
 When a break statement is encountered inside a loop, the loop is immediately exited and
the program continues with the statement immediately following the loop.
 When the loops are nested the break would only exit from the loop containing it. i.e the
break will exit only a single loop.
while (------) do for (-------)

{ { {

------- ------- ------

if (condition) if (condition)
if(error)

break; break; break;

-------- -------- Exit --------

} } from }

------- while (-------); loop ---------

32
UNIT III

ARRAYS:

C programming language provides a data structure called the array, which can store a fixed-size
sequential collection of elements of the same type. An array is used to store a collection of data,
but it is often more useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables. A specific element in an array is accessed by an
index.

All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.
33
Declaring Arrays

To declare an array in C, a programmer specifies the type of the elements and the number of
elements required by an array as follows:

type arrayName [ arraySize ];

This is called a single-dimensional array. The array Size must be an integer constant greater
than zero and type can be any valid C data type. For example, to declare a 10-element array
called balance of type double, use this statement:

double balance[10];

Now balance is a variable array which is sufficient to hold upto 10 double numbers.

Initializing Arrays

You can initialize array in C either one by one or using a single statement as follows:

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

The number of values between braces { } can not be larger than the number of elements that we
declare for the array between square brackets [ ]. Following is an example to assign a single
element of the array:

If you omit the size of the array, an array just big enough to hold the initialization is created.
Therefore, if you write:

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

You will create exactly the same array as you did in the previous example.

balance[4] = 50.0;

The above statement assigns element number 5th in the array a value of 50.0. Array with 4th
index will be 5th ie. Last element because all arrays have 0 as the index of their first element
which is also called base index. Following is the pictorial representation of the same array we
discussed above:

34
ONE DIMENSIONAL ARRAY:

Declaration of one-dimensional array


data_type array_name[array_size];

For example:
int age[5];

Here, the name of array is age. The size of array is 5, i.e., there are 5 items (elements) of array
age. All elements in an array are of the same type (int, in this case).

Array elements

Size of array defines the number of elements in an array. Each element of array can be accessed
and used by user according to the need of program. For example:

int age[5];

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

Here, the size of array age is 5 times the size of int because there are 5 elements.

Suppose, the starting address of age [0] is 2120d and the size of int be 4 bytes. Then, the next
address (address of a [1]) will be 2124d, address of a [2] will be 2128d and so on.

Initialization of one-dimensional array:

Arrays can be initialized at declaration time in this source code as:

int age[5]={2,4,34,3,4};

It is not necessary to define the size of arrays during initialization.

int age[]={2,4,34,3,4};

In this case, the compiler determines the size of array by calculating the number of elements of
an array.

35
TWO-DIMENSIONAL ARRAYS:

The simplest form of the multidimensional array is the two-dimensional array. A two-
dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional
integer array of size x,y you would write something as follows:

type arrayName [ x ][ y ];

Where type can be any valid C data type and arrayName will be a valid C identifier. A two-
dimensional array can be think as a table which will have x number of rows and y number of
columns. A 2-dimensional array a, which contains three rows and four columns can be shown as
below:

Thus, every element in array a is identified by an element name of the form a[i] [j], where a is
the name of the array, and i and j are the subscripts that uniquely identify each element in a.

Initializing Two-Dimensional Arrays:

Multidimensional arrays may be initialized by specifying bracketed values for each row.
Following is an array with 3 rows and each row has 4 columns.

int a[3][4] = {
{0, 1, 2, 3}, /* initializes for row indexed by 0 */
{4, 5, 6, 7}, /* initializes for row indexed by 1 */
{8, 9, 10, 11} /* initializes for row indexed by 2 */
};

The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to previous example:

int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Accessing Two-Dimensional Array Elements:

An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and
column index of the array. For example:

int val = a[2][3];

36
The above statement will take 4th element from the 3rd row of the array. You can verify it in the
above diagram. Let us check below program where we have used nested loop to handle a two
dimensional array:

#include <stdio.h>
int main ()
{
/* an array with 5 rows and 2 columns*/
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;
/* output each array element's value */
for ( i = 0; i < 5; i++ )
{
for ( j = 0; j < 2; j++ )
{
printf("a[%d][%d] = %d\n", i,j, a[i][j] );
}
}
return 0;
}

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

a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8

READING STRINGS FROM THE TERMINAL:

The function scanf with %s format specification is needed to read the character string from the
terminal.

Example:

char address[15];
scanf(“%s”,address);
37
Scanf statement has a draw back it just terminates the statement as soon as it finds a
blank space, suppose if we type the string new york then only the string new will be read and
since there is a blank space after word “new” it will terminate the string.

The scanf function automatically terminates the string that is read with a null character
and therefore the character array should be large enough to hold the input string plus the null
character.

Reading a Line of Text:

In many applications it is required to process text by reading an entire line of text from the
terminal.

 Using getchar Functions

We can read a single character from the terminal, using the function getchar. We can use
this function repeatedly to read successive single characters from the input and place them into a
character array. Thus, an entire line of text can be read and stored in an array. The reading is
terminated when the newline character (‘\n’) is entered and the null character is then inserted at
the end of the string.

The getchar function call takes the form:

char ch;

ch = getchar ( );

 Using gets Functions

A more convenient method of reading a string of text containing whitespaces is to use the
library function gets available in the <stdlio.h> header file.

gets(str);

38
Here gets reads characters into str from the keyboard until a new line character is
encountered and then appends a null character to the string. Unlike the scanf, it does not skip
whitespaces. For ex:

char line [80];

gets (line);

printf (“%s”, line)

WRITING STRINGS TO SCREEN

The printf statement along with format specifier %s to print strings on to the screen. The
format %s can be used to display an array of characters that is terminated by the null character

for example printf(“%s”,name); can be used to display the entire contents of the array name.

 Using putchar functions

The putchar functions to output the values of character variable. It takes the following form

Char ch=’a’;

Putchar(ch);

We can use putchar function to write characters to the screen. We can use this function
repeatedly to output a string of characters stored in an array using a loop.

For ex:

Char name[6] =”APPLE”

For(i=0, i<5; i++)

Putchar(name[i];

39
Putchar(‘\n’);

 Using puts function

Another more convenient way of printing string values is to use the function puts declared
in the header<stdio.h>. It is invoked as under

Puts(str);

Where str is a string variable containing a string value. This print the value of the string
variable str and then moves the curser to the beginning of the next line on the screen.

STRING – HANDLING FUNCTIONS

We can also get the support of the c library function to converts a string of digits into
their equivalent integer values the general format of the function in x=atoi(string) here x is an
integer variable & string is a character array containing string of digits.

String operations (string.h)

C language recognizes that string is a different class of array by letting us input and
output the array as a unit and are terminated by null character. C library supports a large number
of string handling functions that can be used to array out many o f the string manipulations such
as:

 Length (number of characters in the string).


 Concatenation (adding two are more strings)

 Comparing two strings.

 Substring (Extract substring from a given string)

 Copy(copies one string over another)

40
To do all the operations described here it is essential to include string.h library header file in the
program.

 strlen() function:

This function counts and returns the number of characters in a string. The length does not include
a null character.

Syntax n=strlen(string);

Where n is integer variable. This receives the value of length of the string.

Example

length=strlen(“Hollywood”);

The function will assign number of characters 9 in the string to a integer variable length.

/*Write a c program to find the length of the string using strlen() function*/
#include < stdio.h >
include < string.h >
void main()
{
char name[100];
int length;
printf(“Enter the string”);
gets(name);
length=strlen(name);
printf(“\nNumber of characters in the string is=%d”,length);
}

 strcat() function

The strcat function joins two strings together. This process is called concatenation. The strcat()
function joins 2 strings together. It takes the following form
41
strcat(string1,string2)

string1 & string2 are character arrays. When the function strcat is executed string2 is appended
to string1. the string at string2 remains unchanged.

Example

strcpy(string1,”sri”);
strcpy(string2,”Bhagavan”);
Printf(“%s”,strcat(string1,string2);

From the above program segment the value of string1 becomes sribhagavan. The string at str2
remains unchanged as bhagawan.

 Strcmp() function:

In c you cannot directly compare the value of 2 strings in a condition like if(string1==string2)
Most libraries however contain the strcmp() function, which returns a zero if 2 strings are equal,
or a non zero number if the strings are not the same. The syntax of strcmp() is given below:

Strcmp(string1,string2)

String1 & string2 may be string variables or string constants. String1, & string2 may be string
variables or string constants some computers return a negative if the string1 is alphabetically less
than the second and a positive number if the string is greater than the second.

Example:
strcmp(“Newyork”,”Newyork”) will return zero because 2 strings are equal.
strcmp(“their”,”there”) will return a 9 which is the numeric difference between ASCII ‘i’ and
ASCII ’r’.
strcmp(“The”, “the”) will return 32 which is the numeric difference between ASCII “T” &
ASCII “t”.

42
strcmpi() function

This function is same as strcmp() which compares 2 strings but not case sensitive.

Example

strcmpi(“THE”,”the”); will return 0.

 strcpy() function:

The strcpy function works almost like a string-assignment operator. It takes the following form

strcpy(string1,string2);

Strcpy function assigns the contents of string2 to string1. string2 may be a character array
variable or a string constant.

strcpy(Name,”Robert”);

In the above example Robert is assigned to the string called name.

Other string functions

strlwr () function:

This function converts all characters in a string from uppercase to lowercase.

syntax strlwr(string);

For example:

strlwr(“EXFORSYS”) converts to Exforsys

strrev() function: This function reverses the characters in a string.

Syntax strrev(string);

43
For ex strrev(“program”) reverses the characters in a string into “margrop”.

strupr() function:

This function converts all characters in a string from lower case to uppercase.

Syntax strupr(string);
For example strupr(“exforsys”) will convert the string to EXFORSYS.

Strncpy : This function copies only the left most n characters of the source string to the target
string variable. This is a three parameter function and is invokes as follows:

Strncpy(s1,s2,5);

This statement copies the first 5 characters of the source string s2 into the target string s1.

Strncmp: A variation of the function strcpy is the function strncpy. This function has three
parameters as follows

Strncmp(s1,s2,n);

It compares the left most n characters of s1 and s2 and return.

 0 if they are equal


 Negative number, if s1 sub-string is less than s2; and
 Positive number, otherwise.
Strncat: This is another concatenation function that three parameters as shown below,

Strncat(s1,s2,n);

This call will concatenate the left most n characters of s2 to the end of s1.

Strstr: It is a two parameter function that can be used to locate a sub string in a string. This takes
the forms;

Strstr(s1,s2);
44
Strstr(s1,”ABC”);

The function strstr searches the string s1 to see whether the string s2 is contained in s1. If yes,
the function returns the position of the first occurrence of the sub-string; otherwise it returns a
null pointer. t

Ex:

If(strstr(s1,s2)==null)

Printf(“substring is not found”);

Else

Print(“s2 is a substring of s1”);

Strchr & strrchr : We also have functions to determine the existence of a character in a
string. Consider the following function call:

Strchr(s1, ‘m’);

It will locate the first occurrence of the character ‘m’ in string s1.

Similarly the following function call will locate the last occurrence of the character ‘m’ in the
string s1.

Strrchr(s1,’m’);

/* Example program to use string functions*/


#include < stdio.h >
#include < string.h >
void main()
{
char s1[20],s2[20],s3[20];
int x,l1,l2,l3;

45
printf(“Enter the strings”);
scanf(“%s%s”,s1,s2);
x=strcmp(s1,s2);
if(x!=0)
{printf(“\nStrings are not equal\n”);
strcat(s1,s2);
}
else
printf(“\nStrings are equal”);
strcpy(s3,s1);
l1=strlen(s1);
l2=strlen(s2);
l3=strlen(s3);
printf(“\ns1=%s\t length=%d characters\n”,s1,l1);
printf(“\ns2=%s\t length=%d characters\n”,s2,l2);
printf(“\ns3=%s\t length=%d characters\n”,s3,l3);
}

UNIT IV

USER DEFINED FUNCTION:

Function prototype (declaration):

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

Syntax of function prototype


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

In the above example, int add (int a, int b); is a function prototype which provides following
information to the compiler:

1. name of the function is add()


2. return type of the function is int.

46
3. two arguments of type int are passed to function.

Function prototype are not needed if user-definition function is written before main() function.

Function call

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

Syntax of function call


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

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

Function definition

Function definition contains programming codes to perform specific task.

Syntax of function definition


return_type function_name(type(1) argument(1),..,type(n) argument(n))
{
//body of function
}

Function definition has two major components:

1. Function declaratory

Function declaratory is the first line of function definition. When a function is invoked from
calling function, control of the program is transferred to function declaratory or called function.

Syntax of function declaratory


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

Syntax of function declaration and declaratory are almost same except, there is no semicolon at
the end of declaratory and function declaratory is followed by function body.

In above example, int add(int a,int b) in line 12 is a function declaratory.

2. Function body

Function declaratory is followed by body of function which is composed of statements.

47
Passing arguments to functions

In programming, argument/parameter is a piece of data(constant or variable) passed from a


program to the function. In above example two variable, num1 and num2 are passed to function
during function call and these arguments are accepted by arguments a and b in function
definition.

Arguments that are passed in function call and arguments that are accepted in function definition
should have same data type. For example:

If argument num1 was of int type and num2 was of float type then, argument variable should be
of type int and b should be of type float, i.e., type of argument during function call and function
definition should be same.

A function can be called with or without an argument.

Return Statement

Return statement is used for returning a value from function definition to calling function.

Syntax of return statement


return (expression);
OR
return;

For example:

return;
return a;
return (a+b);

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

Types of User-defined Functions in C Programming

For better understanding of arguments and return in functions, user-defined functions can be
categorized as:

1. Function with no arguments and no return value


2. Function with no arguments and return value
3. Function with arguments but no return value
4. Function with arguments and return value.

Function with no arguments and no return value:

#include <stdio.h>
void prime();
int main(){
prime();
return 0;
}
void prime(){
int num,i,flag=0;
printf("Enter positive integer enter to check:\n");
scanf("%d",&num);
for(i=2;i<=num/2;++i){
if(num%i==0){
flag=1;
}
}
if (flag= =1)
49
printf("%d is not prime",num);
else
printf("%d is prime",num);
}

Function with no arguments and return value

#include <stdio.h>
int input();
int main(){
int num,i,flag;
num=input();
for(i=2,flag=i;i<=num/2;++i,flag=i){
if(num%i==0){
printf("%d is not prime",num);
++flag;
break;
}
}
if(flag==i)
printf("%d is prime",num);
return 0;
}
int input()
{ int n;
printf("Enter positive enter to check:\n");
scanf("%d",&n);
return n; }

Function with arguments and no return value

#include <stdio.h>
void check_display(int n);
int main(){
int num;
printf("Enter positive enter to check:\n");
scanf("%d",&num);
check_display(num);
return 0;
}
void check_display(int n){
int i,flag;
for(i=2,flag=i;i<=n/2;++i,flag=i){
if(n%i==0){
printf("%d is not prime",n);
50
++flag;
break;
}
}
if(flag==i)
printf("%d is prime",n);
}

Function with argument and a return value

#include <stdio.h>
int check(int n);
int main(){
int num,num_check=0;
printf("Enter positive enter to check:\n");
scanf("%d",&num);
num_check=check(num);
if(num_check==1)
printf("%d in not prime",num);
else
printf("%d is prime",num);
return 0;
}
int check(int n){
int i;
for(i=2;i<=n/2;++i){
if(n%i==0)
return 1;
}
return 0; }

Nesting Functions

A function calling different functions inside, It is called as Nesting functions.

Example program:

#include <stdio.h>

//Nesting of functions
//calling function inside another function
//calling fact inside print_fact_table function
51
void print_fact_table(int);
int fact(int);

void main(){
print_fact_table(5);
}

void print_fact_table(int n){


int i;
for (i=1;i<=n;i++)
printf("%d factorial is %d\n",i,fact(i));
}

int fact(int n){


if (n == 1)
return 1;
else
return n * fact(n-1);
}

RECURSION

When a called functions in turn calls another function a process of “ chaining “


occurs. Recursion is a special case of this process , where a function calls itself .

Eg:

Main()

printf(“ this is the example for recursion”);

main();

PASSING ARRAY & STRING TO FUNCTION

To pass an array to called function it is sufficient to maintain the name of the


array without any subscript and the size of the array as arguments for example
52
Sum(x,n);

Will pass all elements contained in the array x of the size n.

Eg:

Void main()

void add();

int a[10],i,n

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

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

add(a,n);
}

void add( a,n)

int t,sum=0;

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

sum=sum+a[t];

printf(“%d”,sum);

53
}

THE SCOPE, VISIBILITY AND LIFETIME OF VARIABLES

The scope of variable refers to visibility or accessibility of a variable. The life time of a
variable refers to the existences of a variable in memory.

1. automatic
2. external
3. static
4. register.
Automatic variables

Automatic variables are declared inside a function. They are created as soon as a function
starts execution , and used within in the function. At end of the execution of the program, it
is destroyed.

Eg:

Main()

int age;

--

--

External variables

External variables are active throughout the program execution. They are also known as
global variables. External variables can be accessed by any function in the program. External
variables are declared outside a function.

54
Eg

#include<stdio.h>

int m;

void main()

m=100;

---

--

fn1()

m=m+100; }

Static Variables

The value of the static variables persists until the end of the program. Static
variable will not loss the storage location or their values when the control leaves the
function or blocks where in they are defined. The initial value assigned to a static must be a
constant or an expression Involving constants.

Eg:

void main()

int I;

void fn();

for (I=0;I<10;I++)
55
fn();

void fn()

static int I=99;

I++;

Printf(“%d”,I);

Register Variables

Register variables are placed in one of the machine registers , instead of using
memory. Accessing the register is very fast compared to memory so frequently used
variables are placed in register. This will increase the execution speed.

Syntax:

Register datatype variablename;

Eg:

Register int k;

56
UNIT V
STRUCTURES AND UNIONS
INTRODUCTION

Arrays are used to store large set of data and manipulate them but the disadvantage is
that all the elements stored in an array are to be of the same data type. If we need to use a
collection of different data type items it is not possible using an array.

When we require using a collection of different data items of different data types we can
use a structure. Structure is a method of packing data of different types. A structure is a
convenient method of handling a group of related data items of different data types.

DEFINING A STRUCTURE

The general format of a structure definition as follows

57
struct tag_name
{
data type member1;
data type member2;


}

Example:
struct lib_books
{
char title[20];
char author[15];
int pages;
float price;
};

the keyword struct declares a structure to holds the details of four fields namely title, author
pages and price. These are members of the structures. Each member may belong to different or
same data type. The tag name can be used to define objects that have the tag names structure.
The structure we just declared is not a variable by itself but a template for the structure.

Note: Array vs structures

1. An array is a collection of same data elements of same type. Structure can have
elements of different types.
2. An array is derived data type whereas a structure is a programmer-defined one.

DECLARING STRUCTURE VARIABLES

58
We can declare structure variables using the tag name any where in the program. It includes the
following elements

 The keyword struct


 The structure tag name
 List of variable names separated by commas
 A terminating semicolon
For example the statement,

struct lib_books book1,book2,book3;

declares book1,book2,book3 as variables of type struct lib_books each declaration has four
elements of the structure lib_books. The complete structure declaration might look like this

struct lib_books
{
char title[20];
char author[15];
int pages;
float price;
};
struct lib_books, book1, book2, book3;

Structures do not occupy any memory until it is associated with the structure variable such as
book1. The template is terminated with a semicolon. While the entire declaration is considered as
a statement, each member is declared independently for its name and type in a separate statement
inside the template. The tag name such as lib_books can be used to declare structure variables of
its data type later in the program.

We can also combine both template declaration and variables declaration in one statement,
the declaration
struct lib_books
{
59
char title[20];
char author[15];
int pages;
float price;
} book1,book2,book3;
is valid. The use of tag name is optional for example
struct
{



}
book1, book2, book3 declares book1,book2,book3 as structure variables representing 3 books
but does not include a tag name for use in the declaration.
A structure is usually defines before main along with macro definitions. In such cases the
structure assumes global status and all the functions can access the structure.

ACCESSING STRUCTURE MEMBERS

As mentioned earlier the members themselves are not variables they should be linked to
structure variables in order to make them meaningful members. The link between a member and
a variable is established using the member operator ‘.’ This is known as dot operator or period
operator.

For example

Book1.price
Is the variable representing the price of book1 and can be treated like any other ordinary
variable. We can use scanf statement to assign values like

60
scanf(“%s”,book1.file);
scanf(“%d”,& book1.pages);
Or we can assign variables to the members of book1
strcpy(book1.title,”basic”);
strcpy(book1.author,”Balagurusamy”);
book1.pages=250;
book1.price=28.50;

/* Example program for using a structure*/


#include <stdio.h>
void main()
{
int id_no;
char name[20];
char address[20];
char combination[3];
int age;
}newstudent;
printf(“Enter the student information”);
printf(“Now Enter the student id_no”);
scanf(“%d”,&newstudent.id_no);
printf(“Enter the name of the student”);
scanf(“%s”,&newstudent.name);
printf(“Enter the address of the student”);
scanf(“%s”,&newstudent.address);
printf(“Enter the cmbination of the student”);
scanf(“%d”,&newstudent.combination);
printf(“Enter the age of the student”);
scanf(“%d”,&newstudent.age);
printf(“Student informationn”);

61
printf(“student id_number=%dn”,newstudent.id_no);
printf(“student name=%sn”,newstudent.name);
printf(“student Address=%sn”,newstudent.address);
printf(“students combination=%sn”,newstudent.combination);
printf(“Age of student=%dn”,newstudent.age);
}

STRUCTURE INITIALIZATION

Like any other data type, a structure variable can be initialized at compile time.
Example:
Struct student
{
int id_no;
char name[20];
char address[20];
char combination[3];
int age;
}newstudent={12345, “kapildev” ,“ Pes college”, “Cse”, 19};

this initializes the id_no field to 12345, the name field to “kapildev”, the address field to “pes
college” the field combination to “cse” and the age field to 19. There is one to one
correspondence between the members and their initializing values.

Another method is to initialize a structure variable outside the function as shown below

Struct st_record

{ int weight;

Float height;

} student1={50,120.7}

62
Main()

struct st_record student2={60,124.4};

------

------

C language does not permit the initialization of individual structure members within the
template. This initialization must be done in the declaration of the actual variables.

Rules for initializing structures


 We cannot to initialize individual members inside the structure template
 The order of values enclosed in braces must match the order of members in the structure
the remaining blank. The uninitialized members should be only at the end of the list
 It is permitted to have a partial initialization. We can initialize only the first few members
and leave the remaining blank. The uninitialized members should be only at the end of
the list.
 The uninitialized members will be assigned default values as follows
 Zero for integer and floating point members
 ‘\0’ for characters and strings.

COPYING AND COMPARING STRUCTURE VARIABLES

Two variables of the same structure type can be compared the same way as ordinary
variables. If person 1 and person2 belong to the same structure, when the following
operations are valid.

Person1=person2

Person2 = person1
63
The following statements are invalid as c does not any logical operations on structure variables

Person1==person2

Person1!=person2

Operations on individual members

Eg:

Struct personal

char name[20];

int day;

float salary;

};

main()

struct personal p;

scanf(“%s %d%f”,p.name,&p.day,&p.salary);

printf(“%s %d%f”,p.name,p.day,p.salary);

Operations on individual members:

The individual members are identified using the member operator, the dot.

Eg:

64
Struct personal

char name[20];

int day;

float salary;

};

main()

struct personal p;

scanf(“%s %d%f”,p.name,&p.day,&p.salary);

printf(“%s %d%f”,p.name,p.day,p.salary);

UNIONS
Union is another compound data type like structure. Union is used to minimize memory
utilization. In structure each member has the separate storage location. but in union all the
members share the common place of memory. so a union can handle only one member
at a time.

The general form is:

union tagname

datatype member1;

datatype member2;

..

65
...

datatype member N;

};

Where

union is the keyword.

tagname is any user defined data types.

For Ex:

union item
{
int m;
float p;
char c;
}

code;

This declares a variable code of type union item. The union contains three members each
with a different data type. However we can use only one of them at a time. This is because if
only one location is allocated for union variable irrespective of size. The compiler allocates a
piece of storage that is large enough to access a union member we can use the same syntax that
we use to access structure members. That is

code.m
code.p
code.c

are all valid member variables. During accessing we should make sure that we are
accessing the member whose value is currently stored.
For example a statement such as
code.m=456;
code.p=456.78;
printf(“%d”,code.m);

In effect a union creates a storage location that can be used by one of its members at a
time. When a different number is assigned a new value the new value super cedes the previous
66
members value. Unions may be used in all places where a structure is allowed. The notation for
accessing a union member that is nested inside a structure remains the same as for the nested
structure.

GLOSSARY

2 MARKS:

1. Define Constant.

Constants in C refer to fixed values that do not change during the execution of
program. Types of constants are

a. Numeric Constants
i. Integer Constants
ii. Real Constants
b. Character Constants
i. Single Character Constants
ii. String Constants

2. What is an expression?
Expression is a combination of variables, constants and operators arranged as per
the syntax of the language.

Expressions are evaluated using an assignment statement of the form:

variable = expression;

67
Ex: x= a * b – c;

3. Write the syntax for If……..Else.


The if….else statement is an extension of the simple if statement. The general
form is:

If (test expression)

True-block statement(s)

else

{
4. Define Dynamic Arrays.
In C it is possible to allocate memory to arrays at run time. This feature is known
as dynamic memory allocation and the arrays created at run time are called dynamic
arrays. Dynamic arrays are created using what are known as pointer variable and memory
management functions malloc, calloc and realloc.

5. Name string handling functions.


i. strcat() – concatenates two strings.
ii. strcmp() – compares two strings
iii. strcpy() – copies one string over another
iv. strlen() – finds the length of a string

6. What is nesting of functions?


C permits nesting of functions freely. main can call function1, which calls
functions2, which calls function3, ……… and so on. There is in principle no limit as to
how deeply functions can be nested.

7. Write the difference between arrays and structures.


Arrays can be used to represent a group of data items that belongs to the same
data type, such as int or float.

68
A constructed data type is known as structures, a mechanism for packing data of
different types. A structure is a convenient tool for handling a group of logically related
data items.

8. What will be output for the following code?


# include <stdio.h>

main()

{ int x=5, *p;

p=&x;

printf(“%d”,++*p);

Output: 6

9. What is the purpose of fseek function? Write its syntax.


fseek function is used to move the file position to a desired location within the
file. Syntax: fseek(file_ptr, offset, position);

file_ptr is a pointer to the file concerned, offset is a number or variable of type


long, and position is an integer number.

10. Write different forms of macro substitutions.


There are different forms of macro substitutions. The most common forms are
i. Simple macro substitution

ii. Argumented macro substitution.

iii. Nested macro substitution.

11. How to read a character?


Reading a single character can be done by using the function getchar or scanf
function. The getchar takes the following form:

variable_name = getchar();

69
variable_name is a valid C name that has been declared as char type.

12. Define Arrays.


An array is a fixed-size sequenced collection of elements of the same data type. It
is simply a grouping of like-type data. In its simplest form, an array can be used to
represent a list of numbers, or a list of names.

13. Give the syntax of IF statement.


Syntax: if (test expression)

Entry

Test
expressio
False
nn

True

Ex: if (blank balance is zero)

Borrow money

14. Define Recursion.


When a called function in turn calls another function a process of ‘chaining’
occurs. Recursion is a special case of this process, where a function calls itself.

Eg: main()

printf(“hello”);

main();

70
}

15. How to pass arrays to functions?


To pass a one-dimensional an array to a called function, it is sufficient to list the
name of the array, without any subscripts, and the size of the array as arguments.
Example: largest(a,n)

16. Define structure.


A constructed data type is known as structures, a mechanism for packing data of
different types. A structure is a convenient tool for handling a group of logically related
data items.

General Format of a structure definition is:

Struct tag_name

data_type member1;

data_type member2;

----- ------

----- ------

17. Give the purpose of pointer.


a. Pointers are efficient in handling arrays and data tables.
b. It can be used to return multiple values form function via function arguments.
c. It permits references to functions and thereby facilitating passing of functions as
arguments to other functions.

18. Define File.


A file is a place on the disk where a group of related data is stored. A number of
functions that have the ability to perform basic file functions. They are

i. naming a file.

71
ii. opening a file.

iii. reading data from a file.

iv. writing data to a file


v. closing a file

19. What is meant by preprocessor?


The preprocessor is a program that processes the source code before it passes
through the compiler. It operates under the control of what is known as preprocessor
command lines or directives.

20. Define Identifiers.


Identifiers refer to the names of variables, functions and arrays. These are user-
defined names and consist of a sequence of letters and digits, with a letters as a first
character.

21. Name any two keywords in C.


i. break
ii. case
iii. if
iv. for
v. goto
vi. else
vii. int
viii. struct
ix. void

22. What is meant by a loop?


A sequence of statements is executed until some conditions for termination of the
loop are satisfied. A program loop therefore consists of two segments, one known as the
body of the loop and the other known as the control statement.

23. How to declare a function?


function type function name (paramenter list)

72
Local variable declaration;

Executable statement1;

Executable statement2;

…………..

Return statement;

24. What is meant by a Union?


Unions are a concept borrowed from structures and therefore follow the same
syntax as structures. Although a union may contain many members of different types, it
can handle only one member at a time.

25. Give the purpose of a compiler.


Compiler is a translator that translates source code into machine code for a
specific computer.

Comprehensive program that includes all optional codes and then directs the
compiler to skip over certain parts of source code when they are not required.

26. Define variable.


A variable is a data name that may be used to store a data value. A variable may
take different values at different times during execution.

27. What do you mean by symbolic constant?


Assignment of constants to a symbolic name to overcome the problems such as
modifiability and understandability is called symbolic constant.

A symbolic constant is defined as

#define symbolic name value of constant

Example: #define PI 3.14159

73
28. Write any two differences between while and do-while.
While statement Do-while statement

It is an entry-controlled loop statement It is an exit-controlled loop statement

The test-condition is evaluated and if The program proceeds to evaluate the


the condition is true, then the body of body of the loop first. At the end of the
the loop is executed. loop, the test-condition is the while
statement is evaluated.

29. Write the o/p for the following code.


# include <stdio.h>

# include <string.h>

main ()

char S1[] = “Hello,.world”;

printf(“%15.10s”,S1);

Output: Hello,.wor

30. Write the difference between structure and union.


The major difference between structure and union are in terms of storage.
Structures - each member has its own storage location.

Union – all the members use the same location.

31. Describe pointer.


A pointer is a derived data type. Pointer contains memory addresses as their
values. Pointers can be used to access and manipulate data stored in the memory.

32. What is the purpose of close() function.


close() function is used to closes a file which has been opened for use.
74
33. Explain the differences between the printf() and fprintf() function.
printf() – the use of printf function for printing captions and numerical results.

fprintf() – fprintf() can handle a group of mixed data simultaneously. They work on files

fprintf(fp, “control string”, list);

34. What are the data types supported in C?


C support five fundamental data types

i. integer(int)

ii. Character (char)

iii. Floating point(float)

iv. double-precision floating point (double)

v. void

35. How to declare a storage class?


A variety of storage class specifiers that can be used to declare explicitly the
scope and lifetime of variables.

There are four storage class specifiers

a. auto
b. register
c. static
d. extern

Example: auto int count;

register char ch;

36. Give the syntax of WHILE statement.


while (test condition)

75
{

body of the loop;

37. How to read strings from terminal?


The familiar input function scanf can be used with %s format specification to
read in a string of characters. It terminates its input on the first white space it finds.

scanf(“%s” , name)

We can also specify the field width using the form %ws in the scanf statement for
reading a specified number of characters from the input string.

scanf(“%ws” , name)

38. Name any two operations on files.


a. naming a file
b. opening a file
c. reading data from a file
d. writing data to a file
e. closing a file

40. Define the term function.

A function is a self contained block of code that performs a particular task.


Once a function has been designed and packed. It can be treated as a black box that
takes some data from the main program and returns a value.

41. How structure variable is declared?


Structure variable is defined anywhere in the program by using the tag-name. For
example:

book bank book1,book2;

defines the book1 and book2 are variables of type struct bookbank.

Syntax:

76
struct tagname varname1, varname2, ..varname N;

42. What is an identifier?


Identifiers refer to the names of variables, functions and arrays. These are
user-defined names and consist of a sequence of letters and digits, with a letter as a first
character. Both lowercase and uppercase letters are permitted.

43. What is type conversion in C?

C permits mixing of constants and variables of different types in an expression. C


automatically converts any intermediate values to the proper type so that the expression
can be evaluated without losing any significance. This automatic type conversion is
known as implicit type conversion during evaluation it adheres to very strict rules and
type conversion. If the operands are of different types the lower type is automatically
converted to the higher type before the operation proceeds. The result is of higher type.

44. What is the purpose of break statement?


 Exit from a loop can be accomplished by using the break statement or the goto
statement.
 These statements can also be used within while, do or for loops.
 When a break statement is encountered inside a loop, the loop is immediately exited and
the program continues with the statement immediately following the loop.
 When the loops are nested the break would only exit from the loop containing it. i.e the
break will exit only a single loop.
45. Distinguish between getc and getchar.

getchar() function: The getchar function can be used to read a character from the
standard input device. It has the following form.
Variable name = getchar();

Variable name is a valid ‘C’ variable, that has been declared already and that possess
the type char.

getc() function

77
This is used to accept a single character from the standard input to a character
variable. It general syntax is

Character variable=getc();

Where character variable is the valid ‘c’ variable of the type of char data type.

Ex:

Char c;

C=getc();

46. What is a structure? Differentiate a structure from an array.

Structure is a method of packing data of different types. A structure is a convenient


method of handling a group of related data items of different data types. Array vs structures:
1.An array is a collection of same data elements of same type. Structure can have elements of
different types.

2. An array is derived data type whereas a structure is a programmer-defined one.

78
MAHENDRA ARTS & SCIENCE COLLEGE, KALIPPATTI (AUTONOMOUS)

DEPARTMENT OF COMPUTER SCIENCE & APPLICATIONS

Question Bank

UNIT-I

2 Marks

1. Define character set.


2. What is meant by tokens?
3. What is keywords?
4. Define identifier.
5. What is constant and list out it?
6. State about variable.
7. What is data type?
8. What is meant by symbolic constant?
9. What are the operators used in c?
10. Define C program structure.

5 Marks

79
1. Write short note on importance of C language
2. Write about structure of C programming language
3. Note down about the constants and its types?
4. What is variable? And write short note on variable declaration.

10 Marks

1. What is data types and discuss about the various types in C?


2. Discuss about the operator and its types.
3. Explain about constants and it types.
UNIT-II

2 Marks

1. Define operator and list out the operators.


2. Write the usage of printf( ) function with syntax
3. Give the usage of scanf( ) function with syntax.
4. List out the control statements
5. Write syntax for if...then.. else statement
6. Write the general form for For-loop statement.
7. List the use of GOTO statement.
8. Write features of loop statement.

5 Marks

1. Give short note on switch statement


2. Write about GOTO statement with example?
3. Discuss about Switch case with example
4. Write about looping statements

10 Marks

80
1. Write about input and output operations.
2. Write note on decision making and branching
3. Write a C program to read an array of 10 numbers and print the prime numbers?
4. Explain looping statements in c?
5. What are the difference between while and do statements?

UNIT – III

2 Marks

1. Define array.
2. What are the types of array?
3. What is dynamic array?
4. What is strlen() function?
5. What are the string functions in c?
6. What is mean by getchar()?
7. Define putchar()

5 Marks

1. Write a program to find the length of the string?


2. Write a program to read 10 numbers using array.
3. Write a program to find sum of 10 numbers using array.
4. Write a program to sort names in alphabetical order.

10 Marks

81
1. Write a C program to find the largest and smallest number in array?
2. Discuss about array and write its type with examples
3. Write about string handling functions
4. Write a program using string function

UNIT – IV

2 Marks

1. What is function?
2. What is the need for user defined function?
3. List out the elements of user defined function.
4. Write short note on function
5. Write few advantage of using function
6. Define recursion.
7. What is external variable?

5 MARKS

1. Write about function declaration


2. Describe about function with arguments and return values
3. Discuss about function with arguments and no return values
4. Write a program of a simple function to add two integers
Explain about nesting function

82
10 MARKS

1. What is function? And write elements of user defined functions


2. Discuss about types of functions
3. Discuss completely about structure, declaring and initializing structure variable with
proper example?
4. Describe about arrays within a structure?

UNIT V

1. What is structure?
2. Write format for structure
3. How to declare structure variable? Give example
4. Write a few rules for initializing structure
5. What is union?
6. Write a format for union
7. What is bit field?

5. Marks

1. Write about structure and its declaration with example


2. Discuss about arrays within structure
3. Describe about structure within structure
4. State about unions

10 Marks

83
1. Write about the structure and function
2. Give complete notes about union with example

84

You might also like