Gopi b.com CA c Notes Final
Gopi b.com CA c Notes Final
OVERVIEW OF C:
History of C:
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
Facts about C
The language was formalized in 1988 by the American National Standard Institute
(ANSI).
Today C is the most widely used and popular System Programming Language.
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
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.
Preprocessor Commands
Functions
Variables
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;
}
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.
Lets look at how to save the source code in a file, and how to compile and run it. Following are
the simple steps:
3. Open a command prompt and go to the directory where you saved the file.
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.
$ 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:
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:
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
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
\b Backspace
\f Form feed
\n New line
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\? Question mark
\0 Null character
String constants
String constants are the constants which are enclosed in a pair of double-quote marks. For
example:
Enumeration constants
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
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
b) character
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.
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.
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.
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.
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...
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;
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 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;
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:
, < > . _ ( ) ; $ : % [ ] # ?
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;
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
do If static while
Besides these keywords, there are some additional keywords supported by Turbo C.
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.
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
Assignment Operators
Relational Operators
Logical Operators
13
Conditional Operators
Bitwise Operators
Special Operators
Arithmetic Operators
Operator Meaning of Operator
* Multiplication
/ Division
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.
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:
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:
= 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.
16
Operator Meaning of Operator Example
Logical Operators
Logical operators are used to combine expressions containing relation operators. In C, there are 3
logical operators:
Meaning of
Operator Example
Operator
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.
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
Other Operators
Comma Operator
Comma operators are used to link related expressions together. For example:
int a,c=5,d;
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
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.
If the test condition is true, expression1 is returned and if false expression2 is returned.
Output
19
Enter l if the year is leap year otherwise enter n: l
Number of days in February = 29
UNIT II
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;
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
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;
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.
#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
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;
}
Flow chart:
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.
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.
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.
for loop
while loop
do...while loop
WHILE LOOP:
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.
#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.
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).
#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
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)
} } from }
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:
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:
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:
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:
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];
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.
int age[5]={2,4,34,3,4};
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.
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:
An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and
column index of the array. For example:
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
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.
In many applications it is required to process text by reading an entire line of text from the
terminal.
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.
char ch;
ch = getchar ( );
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:
gets (line);
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.
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:
Putchar(name[i];
39
Putchar(‘\n’);
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.
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.
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:
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
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”);
strlwr () function:
syntax strlwr(string);
For example:
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);
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)
Else
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’);
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
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.
In the above example, int add (int a, int b); is a function prototype which provides following
information to the compiler:
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).
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
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 declaration and declaratory are almost same except, there is no semicolon at
the end of declaratory and function declaratory is followed by function body.
2. Function body
47
Passing arguments to functions
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.
Return Statement
Return statement is used for returning a value from function definition to calling function.
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.
For better understanding of arguments and return in functions, user-defined functions can be
categorized as:
#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);
}
#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; }
#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);
}
#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
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);
}
RECURSION
Eg:
Main()
main();
Eg:
Void main()
void add();
int a[10],i,n
for(I=1;I<=n;I++)
scanf(“%d”,&a[I]);
add(a,n);
}
int t,sum=0;
for(t=1;t<=n;t++)
sum=sum+a[t];
printf(“%d”,sum);
53
}
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()
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:
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
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.
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.
58
We can declare structure variables using the tag name any where in the program. It includes the
following elements
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.
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;
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()
------
------
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.
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
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);
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.
union tagname
datatype member1;
datatype member2;
..
65
...
datatype member N;
};
Where
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.
variable = expression;
67
Ex: x= a * b – c;
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.
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.
main()
p=&x;
printf(“%d”,++*p);
Output: 6
variable_name = getchar();
69
variable_name is a valid C name that has been declared as char type.
Entry
Test
expressio
False
nn
True
Borrow money
Eg: main()
printf(“hello”);
main();
70
}
Struct tag_name
data_type member1;
data_type member2;
----- ------
----- ------
i. naming a file.
71
ii. opening a file.
72
Local variable declaration;
Executable statement1;
Executable statement2;
…………..
Return statement;
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.
73
28. Write any two differences between while and do-while.
While statement Do-while statement
# include <string.h>
main ()
printf(“%15.10s”,S1);
Output: Hello,.wor
fprintf() – fprintf() can handle a group of mixed data simultaneously. They work on files
i. integer(int)
v. void
a. auto
b. register
c. static
d. extern
75
{
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)
defines the book1 and book2 are variables of type struct bookbank.
Syntax:
76
struct tagname varname1, varname2, ..varname N;
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();
78
MAHENDRA ARTS & SCIENCE COLLEGE, KALIPPATTI (AUTONOMOUS)
Question Bank
UNIT-I
2 Marks
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
2 Marks
5 Marks
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
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
82
10 MARKS
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
10 Marks
83
1. Write about the structure and function
2. Give complete notes about union with example
84