Programming in C
Programming in C
Lakshmi.S, M.C.A.,M.Phil.,
Assistant Professor, Department of Computer Science, Sri Adi
Chunchanagiri Women’s College, Cumbum.
Theni(D.t).
I
ABOUT THE BOOK
This book is intended for anyone who is learning programming for the
first time, regardless of age or institution. The material has been taught
successfully to students preparing for students at college level.
Chapter 1 gives an overview of Programming in c, Chapter 2
describes Keywords, Constants, Variables Chapter 3 explains Data types
Chapter 4 shows Operators And Expressions Chapter 5 explains
Managing Input/output Functions Chapter 6 introduces Decision Making
and Branching Chapter 7 deals Looping Chapter8 tackle the Array
Chapter 9 give the important questions.
The presentation is based on the experience that many people
have difficulty in learning programming. To try and overcome this,
we use an approach which provides clear examples, detailed
explanations of very basic concepts and numerous interesting
problems.But do not stop there.
The only way to learn programming well is to write programs
to solve new problems. The end of the chapter I give important
questions. This one very helpful for students at the examination time.
CONTENT
1. Introduction…........................................................................................1
History of C......................................................................................................1
Importance of C................................................................................................2
Uses and Features of C.....................................................................................3
Structure of C program.....................................................................................4
Executing a C program.....................................................................................9
3. Data types.............................................................................................27
Basic Data Type.............................................................................................28
Type Casting..................................................................................................33
7. Looping...............................................................................................85
While 86
Do – While.....................................................................................................88
For Loop.........................................................................................................90
Nested Loop....................................................................................................94
8. Array....................................................................................................95
One Dimensional Array..................................................................................95
Two Dimensional Array.................................................................................98
Multi Dimensional Array.............................................................................100
Working with Strings & Standard Functions…………..101
History of C Language
1
C99 1999 Standardization Committee
Database systems
Graphics packages
Word processors
Spreadsheets
Operating system development
Compilers and Assemblers
Network drivers
Interpreters
Features of C language
Documentation section
Link section
Definition section
Global declaration section
Main() Function section
{
Declaration part Executable part
}
Subprogram section
Function 1
(User defined function)
Function 2
------------------
---
-----------------
---
Function n
Formula
The formula to compute the area of a circle is
πr2 where π is PI = 3.1416 (approx.) and r is the radius of the circle.
Lets write the C code to compute the area of the circle.
/**
*file: circle.c
*author : sri
*date : 2018-01-01
*description : program to find the area of a circle using the
radius r
*/
#include<stdio.h>
#define PI = 3.1416
float area(float r);
int main(void)
{
float r= 10;
printf(“Area :%.2f”,area®);
return 0;
}
float area(float r)
{
return PI * r * r;
}
314.16
Documentation:
This section contains a multi line comment describing the
code.
/**
*file: circle.c
*author : sri
*date : 2018-01-01
*description : program to find the area of a circle using the
radius r
*/
In C, we can create single line comment using two forward slash
// and we can create multi line comment using /*
*/
Comments are ignored by the compiler and is used to write notes
and document code.
Link :
This section includes header file.
#include<stdio.h>
We are including the stdio.h input/output header file from the C library.
Definition :
This section contains constant.
#define PI = 3.1416
In the above code we have created a constant PI and assigned
3.1416 to it.
The #define is a preprocessor compiler directive which is used to create
constants. We generally use uppercase letters to create constants. The
#define is not a statement and must not end with a ; semicolon.
Global declaration :
This section contains function declaration.
int main(void)
{
float r= 10;
printf(“Area :%.2f”,area);
return 0;
}
Subprograms :
This section contains a subprogram, an area() function that is
called from the main() function.
float area(float r)
{
return PI * r * r;
}
filename.c
where
Example
#include<stdio.h>
main()
{
}
Store the program as Sample.C
filename.obj
where
filename - name of the source program obj
- file extension
Example - Sample.obj
filename.exe
where
filename – name of the source program exe –
file extension
Example – Sample.exe
Run the executable program using run option in TURBO C editor
to get the result for the program.
Flow Chart of the Program Execution Process:
C Tokens.
Character Set :
Its a set of characters that can be used to create values, variables,
expressions etc.
Following are the characters that we can use in C programming language.
Token
The smallest individual unit in a program is known as
token.
Following are the tokens used in C programming language:
Keywords
Identifiers
Constants
Strings
Special Symbols
Operators
Keyword
Keywords are the words belonging to C-language. They have
standard predefined meaning. The users have no right to change its
meaning. Keywords should be written in lower case, and hence must not
be used as normal identifier name.
Variables in C
Where,
Data-type - valid data type such as int,char etc.
Variable list - list of variables separated by comma
1. int a;
2. float b;
3. char c;
1. int a;
2. int _ab;
3. int a30;
1. int 2;
2. int a b;
3. int long;
Types of Variables in C
1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable
1. Local Variable:
A variable that is declared inside the function or block is called local
variable. it must be declared at the start of the block.
1. void function1() 2.
{
3. Int x=10; //local variable 4. }
2. Global variable :
A variable that is declared outside the function or block is called
global variable. Any function can change the value of the global variable.
It is available to all the functions.It must be declared at the start of the
block.
1. Static Variable :
4. Automatic Variable :
void main()
{
int x=10;//local variable (also automatic)
auto int y=20;//automatic variable
}
6. External Variable :
We can share a variable in multiple C source files by using external
variable. To declare a external variable, you need to use extern
keyword.
Myfile.h
Identifier Variable
Example: Example:
//avariable // int variable
int studytonight; int a;
//or, a function //float variable
int studytonight() Float a;
{
}
}
Constant :
A value that will never change throughout the execution of the
program is called a constant.
There are three types of constants:
(i) Numeric constant
(ii) Character constant
(iii) String constant
Numeric Constant:
A numeric constant is a constant made up of digits and some
special characters. There are two types of numeric constants. They are
(i) Integer or fixed point constant
(ii) Real or floating point constant
(i) Integer Constant:
Integer constant is a constant made up of digits without decimal
point. This can have values from -32768 to +32767.
Rules:
(i) An integer constant is formed with digits 0 to 9.
(ii) The constant can be preceded by + or – sign.
(iii) No special characters are allowed anywhere in the
constant.
There are three types of integer constants. They are
(i) Decimal integer constant
(ii) Octal integer constant
(iii) Hexadecimal integer constant
Decimal Integer Constant:
A decimal integer constant is made up of digits 0
to 9 in any combination. The first digit should not be zero.
Example:
1. The following are some valid decimal integer
constants:
10 -10 -5420 5743
2. The following are invalid decimal integer constants:
Example:
1. The following are some valid hexadecimal integer
constants:
OX532 OX1F ox1f
2. The following are invalid decimal integer constants:
Exponent form:
Exponent form is used to represent very large and very
small real constants. The general form is
mantissa e or E exponent
Rules:
(i) The mantissa and exponent can have a positive or
negative sign.
(ii) Exponent should not have a decimal point.
(iii) Exponent must have atleast one digit.
Example:
1. The following are some valid real constants in
exponent form:
(a) 0.000002571 can be expressed as .2571e-5
(b) 3.14 can be expressed as .314E1
2. The following are invalid real constants in exponent form:
Character constant:
There are two types of character constants. They are
(i) Direct
(ii) Escape Sequence
(i) Direct:
A direct character constant consists of a single character
enclosed with single quotation marks. This gives the integer
value of the enclosed character. This value is known as ASCII
value.
Example:
Co Value
‘A’ 65
‘0’ 48
‘%’ 37
‘a’ 97
Escape Sequence :
An escape sequence consists of more than one character within
single quotation marks. The first character These are special backslash
character constants.
Character Constant Description
'\0' null
'\b' Backspace
'\\' Backslash
Example: The following code will print "Hello World" and will move the
cursor to the next line because of the new line character '\n'.
printf(“Hello World \n”);
String constant
A string constant is a sequence of character enclosed with double
quotation marks.This can be form with digits, alphabets and special
characters.
Example
“NAGARCOIL” “13TH-MARCH” “12345” “23.567”
Here, color is a variable and yellow, green, black and white are the
enumeration constants having value 0, 1, 2 and 3 respectively.
3. Data Types
C data types are defined as the data storage format that a variable can
store a data to perform a specific operation.
Data types are used to define a variable before to use in a program.
Size of variable, constant and array are determined by data types.
There are four data types in C language. They are,
#include <stdio.h>
#include <limits.h> int
main()
{
int a;
char b;
float c;
double d;
printf("Storage size for int data type:%d \n",sizeof(a));
printf("Storage size for char data type:%d \n",sizeof(b));
printf("Storage size for float data type:%d \n",sizeof(c));
printf("Storage size for double data type:%d\n",sizeof(d)); return 0;
}
OUTPUT :
Storage size for int data type : 4 Storage
size for char data type : 1 Storage size for
float data type : 4 Storage size for double
data type : 8
Example :
#include<stdio.h>
int main()
{
num MONTH {Jan =0, Feb, Mar }; enum
MONTH month=Mar; if(month = = 0 )
printf(“value of Jan”); else
if(month = =1)
printf(“Month is Feb”);
if(month = = 2)
printf(“Month is Mar”);
}
e
Output :
Month is Mar
unsigned 1 1 to 255
char
Type casting :
x = (float) 7/5;
printf(“%f”,x);
Output :
1.400000
int x; for(x=97;x<=122;x+
+)
{
Printf(“%c”,x); /* implicit casting from int to char
thanks to %c */
}
Explicit Type Conversion :
The type conversion performed by the programmer by posing the
data type of the expression of specific type is known as explicit
type conversion. The explicit type conversion is also known as
type casting.
(data_type)expression;
where,
example,
int x; for(x=97;x<=122;x+
+)
int to char */
int x=7,y=5;
float z;
int x=7,y=5;
float z;
4. Operators
The symbols which are used to perform logical and
mathematical operations in a C program are called C
operators.
Operand1 op operand2
Where,
Operand1,operand2 - valid constants or variables op
- binary operator
- Subtraction y=x-2
* Multiplication Z= 2*3
/ Division X=10/3=3 or 3.33
% (modulo Remainder after X= 7%2 = 1
operator) integer division
Operator Description
% remainder of division
Relational operators
The following table shows all relation operators supported by C.
Operator Description
Logical operators
C language supports following 3 logical operators. Suppose a = 1 and b =
0,
|| Logical OR (a || b) is true
Bitwise operators
Bitwise operators perform manipulations of data at bit level. These
operators also perform shifting of bits from right to left. Bitwise
operators are not applied to float or double(These are data
types, we will learn about them in the next tutorial).
Operator Description
| Bitwise OR
^ Bitwise exclusive OR
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
The bitwise shift operator, shifts the bit value. The left operand
specifies the value to be shifted and the right operand specifies the number
of positions that the bits in the value have to be shifted. Both operands
have the same precedence.
Example :
a=0001000
b=2
a<<b=0100000
a>>b=0000010
Assignment Operators
Assignment operators supported by C language are as follows.
1. Ternary Operator
2. ? : Operator
Explanation:
Special operator
Arithmetic expression :
Arithmetic expressions are formed by connecting constants or
variables by arithmetic operators.
General form is :
Example :
x+z, a+z-x, (x-y)/z, x+y/z, (x+y)/(Z+A)
There are three types of arithmetic expressions They are:
i. Integer expression
ii. Real expression
iii. Mixed mode expression
(i) Integer Expression
If the dat type of the variable on the left hand side of the expression
and the datatype of the variables on the right hand side of the expression
are of int type, then that expression is called integer expression
The general Form is:
int var1 = int var2 arithmetic operator int var3 arithmetic operator
Where
int - data type
var1,var2,var3 ---- - variables
arithmetic operator - +,-,*,/,%
The resultant value of the expression is of integer type.
Example
int a;
int b=10,c=20;
a=b+c The value of a is 30.
Float var1 = float var2 arithmetic operator float var3 arithmetic operator
Where
int - data type
var1,var2,var3 ---- - variables
arithmetic operator - +,-,*,/,%
The resultant value of the expression is of real type.
Example
int a;
int b=15.5,c=19.5;
a=b+c The value of a is 35.0
Where
int - data type
var1,var2,var3 ---- - variables
arithmetic operator - +,-,*,/,%
The resultant value of the expression is of real type.
Example
int a,h;
float c,d;
d=a+h-c;
Relational expression:
Relational expressions are formed by connecting constants or
variables or arithmetic expressions by relational operators.
General form is:
Expression Expression
(datatype) variable;
Where
1 Highest ( ) Function L ? R
precedence [ ] call Left to
? Right
: :
.
2 Unary ! Logical R ? L
~ negation Right ->
+ (NOT) Left
- Bitwise
++ 1’s
- - compleme
& nt
* Unary
Size of plus
Unary
minus
Pre or
post
increment
Pre or
post
decrement
Address
Indirectio
n
Size of
operant in
bytes
%w d
The percentage sign (%) indicates that a conversion specification
follows. w is an integer number that specifies the field width of the
number to be read and d, known as data type character, the number to be
read is in integer mode.
Consider the following example:
scanf(“%2d %5d”,&num1, &num2); Data
line:
52 31456
The value 52 is assigned to num1 and 31456 to num2. Suppose the input
data is as follows:
31456 52
The num1 will assign 31 (because %2d) and num2 will be assigned 456
(unread part of 31456). The value 50 that is unread will be assigned to
the first variable in the next scanf call. This kind of error may be
eliminated if we use the field specification without the field width. That is
the statement:
31456 52
correctly and assign 31456 to num1 and 52 to num2.
An input field may be skipped by specifying * in the place of field
width.
For example:
scanf(“%d %*d %d”,&a, &b);
will assign data
Code Meaning
%s Read a string
printf(“%d”,6789);
6 7 8 9
printf(“%6d”,6789);
6 7 8 9
printf(“%2d”,6789);
6 7 8 9
printf(“%-6d”,6789);
6 7 8 9
printf(“%06d”,6789);
0 0 6 7 8 9
Format Output
printf(“%7.4f”,y);
5 6 . 4 5 6 7
printf(“%7.2f”,y);
5 6 . 4 6
printf(“%-7.2f”,y); 5 6 . 4 6
5 6 . 4 5 6 7
printf(“%f”,y);
5 . 6 4 E + 0 1
printf(“%10.2e”,y);
printf(“%e”,y);
5 . 6 4 5 6 7 0 E + 0 1
Code Meaning
%s Print a string
Flag Meaning
i. getchar()
ii. gets()
(i) getchar()
Reading a single character can be done using the function
getchar(). This can also be done with the help of the scanf function.
The getchar takes the following form:
variable_name = getchar();
example:
char ch;
ch = getchar();
will assign “g” to the variable ch when we press the key g on the
keyboard.
The getchar function may be called successively to read the characters in a
line of text. For example, the following program segment reads characters
from keyboard one after the another until the return key is pressed
----------
----------
----------
char ch;
ch=’ ‘;
while(ch!= ‘\n’)
{
ch = getchar();
}
----------
----------
----------
(ii) gets()
This function is used to read a string of characters until a
new line character ‘\n’ is entered (return key).The general form is:
gets(variable-name);
where
variable name - valid C variable
Rules
Example
char name[15];
gets(name);
if the input string is - SRI UMAIYAL
The whole string will be read into the memory and is shown below
S R I U M A I Y A L \0
puts(variablename);
where
Example
char name[4];
gets(name); // give the input as Rani. puts(name);
The output is Rani.
68
DECISION MAKING AND BRANCHING
6. Control Statements
Control statements enable us to specify the flow of
program control; ie, the order in which the instructions in a program must
be executed. They make it possible to make decisions, to perform tasks
repeatedly or to jump from one section of code to another. In other words
in some situations we may have to change the order of execution of
statements based on certain conditions , or repeat a group of statements
until certain specified conditions are met. For these situation C provides
decision making statements also know as control statements.
C language supports the following statements known
as control or decision making statements.
1. if statement
2. switch statement
3. Conditional operator statement
4. goto statement
CONDITIONAL STATEMENTS
IF Statement
The if statement is used to control the flow of execution of
statements.
Syntax :
if(test expression)
69
Example:
if(bank balance is zero)
Borrow money
The if statement may be implemented in different forms depending
on the complexity of conditions to be tested.
1. Simple if statement
2. if…..else statement
3. Nested if…..else statement
4. elseif ladder
SIMPLE IF Statement
Simple if statement is used to execute or skip one statement
or group of statements for a particular condition.
70
If(test exprn)
{
statement-block;
}
statement-x;
71
72
if(test expression)
{
True-block statement(s);
}
else
{
False-block statement(s);
If the test expression is true, then the true block statements are executed
and the control is transferred to statement-x; if the value is false, the false
block statement will be executed and the control is transferred to
statement-x.
72
Example:
………
……… if(code
==1) boy = boy
+ 1; if(code ==
2) girl =girl + 1;
………
………
NESTING OF IF…..ELSE STATEMENTS
When a series of decisions are involved, we may have to use more
than one if….else
statements, in nested form as follows.
If(test condition 1)
{
if(test condition 2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
73
When this statement is executed, the computer first evaluates value of test
condition1. If it is false control will be the transferred to statement-3. If it is
true test condition2 is evaluated. If it is true statement-1 is executed and control
is transferred to statement-x else statement-2 is executed and control is
transferred to statement-x.
Program
/*Selecting the largest of three values*/ void
main()
{
float A, B, C;
printf(“Enter three values \n”);
scanf(“%f %f %f ”,&A, &B, &C);
printf(“\nLargest value is:”);
if(A > B)
{
if(A > C)
printf(“%f \n”,A);
else
printf(“%f \n”,C);
}
else
{
if(C > B)
printf(“%f \n”,C);
else
printf(“%f \n”,B);
}
}
OUTPUT
Enter three values:
5 8 24
Largest value is 2
ELSE….IF LADDER
else……if ladder statement is used to take multiway decision.This
statement is formed by joining if…..else statements in which each
else contains another if…..else.
The general form is
OUTPUT
Enter customer no. and units consumed 101 150
Customer no=101 charges = 75.00
SWITCH STATEMENT
Switch statement is an extension of if..else statement. It permits
any number of branches. When this statement is executed the
computer, first evaluates the value of the expression in the keyword
switch. This value is successively compared with the case label1,
label2 … labeln.
Rules:
The expression should be placed in parentheses.
The value of the expression should be an integer.
The body of the switch statement should be enclosed within {}
brackets.
Case label should terminate with a colon.
Break statement is a must and causes immediate exit from switch
statement.if it is not included the statements below the matched
case will be executed.
Example
………
………
index = marks / 10;
switch(index)
{
case 10:
case 9:
case 8:
grade = “Honours”;
break;
case 7:
case 6:
grade = “first division”;
break;
case 5:
grade = “second division”;
break;
case 4:
grade = “third division”;
break;
default:
grade = “first division”; break; }
printf(“%s \n”,grade);
THE ?: OPERATOR
The C language has an unusual operator, useful for making
two-way decisions. This operator is a combination of ? and : and
takes three operands. It is of the form:
flag = 1;
can be written as:
flag = (x < 0)? 0 : 1;
gotolabel;
label : statements;
Rules
Note: A label can be anywhere in the program, either before or after the
goto label;statement.
Example of goto label statement: void
main()
{
double x, y;
read:
scanf(“%f”,&x);
if(x < 0)
goto read; y
= sqrt(x);
printf(“%f %f \n”,x, y);
goto read;
}
Break statement
Break statement is used to exit from a loop while the test condition
is true. This statement can be used within a for, while, do-while or switch
statement.
The general form is
break;
When the break statement is executed inside a loop,the execution of the
loop is terminated and the program continues with the statement following
the loop.
Example
While(condition)
{
…….
…….
If(condition)
{
……..
…….
break;
}
………
}
Next statement
Continue statement
The statements after the keyword continue will be skipped and the
control is transferred to the beginning of the loop.The general form is
continue;
Example
for(i=1;a<=100;++i)
{
scanf(“%f”, &a);
if(a<0)
{
prints(“Error”);
continue;
}
………………
………………
Statements;
…………..
…………..
}
During execution if the value of a negative, the statements below the
keyword continue is skipped and the control is transferred to the beginning
of the loop.
7. Looping statements
The versatility of the computer lies in its ability to perform a set of
instructions repeatedly. This involves repeating some portion of the
program either a specified number of times or until a particular condition
is being satisfied. This repetitive operation is done through a loop control
instruction.
There are three methods by way of which we can repeat a part of a
program. They are:
while statement
do-while statement
for statement
printf(“Factorial is %ld”,fact);
}
do
{
statement(s);
} while(test condition);
{
int i=0;
int j=2;
do
{
printf(“%d”,j);
j =j+2;
i=i+1;
} while (i<10);
}
OUTPUT
2 4 6 8 10 12 14 16 18 20
Where
Control variable - to control the loop
Test condition - to check the control variable.
according to this the loop is executed or not.
Increment/decrement - to change the value of the
control variable.
When the for statement is executed the value of the control variable
is initialized and tested with the test condition. if the value of the test
condition is true, the body of the loop will be executed and the control
variable is incremented or decremented. When the test condition becomes
false the control is transferred to the next statement. The body of the loop
is executed repeatedly as long as the test value is true.
Here, an inner for loop is written inside the outer for loop. For every
value of i, j takes the value from 1 to i and then value of i is incremented
and next iteration of outer loop starts ranging j value from 1 to i.
8. Arrays in C
An array is defined as a group of related data items stored in a
single variable name.
Example where arrays are used,
Example :
data-type array-name[subscript]
Here int is the data type, arr is the name of the array and 10 is the
size of array. It means array arr can only contain 10 elements of int type.
Index of an array starts from 0 to size-1 i.e first element of arr
array will be stored at arr[0] address and the last element will occupy
arr[9].
Rules
i) The subscript is always an integer
ii) The subscript value cannot be negative
iii) The subscript must be given within square brackets
after the array name.
iv) If there are more than one subscript each should be
given in separate square brackets.
v) Subscripts can be integer variables or
expressions that give integers.
Array initialization
After an array is declared it must be initialized. Otherwise, it will
contain garbage value(any random value). An array can be initialized at
either compile time or at runtime.
The process of assigning initial values to 1-D arrays during
declaration is called array initialliation.The general form is
Where
Static - keyword
Data-type - type of data found in the array. e.g
int,float etc.
Array-name - valid C variable name
Size - Number of contiguous locations in
the memory to be reserved.
List of values - initial values to be given to the
array.This value should be separated
by Commas.
Example
i) Static int age[2]={10,20};
age[0]= 10;
age[1]= 20;
age[0]=10;
age[1]=20;
age[2]=0;
age[3]=0;
……………..
………………
int a[10];
Reading
for(i=0;i<10;i++)
{
scanf(“%d”, &a[i]);
}
…………….
…………….
for(i=0;i<10;i++)
{
Writing
Printf(“%d”, a[i]);
}
…………..
……………
Two dimensional Arrays
C language supports multidimensional arrays also. The simplest
form of a multidimensional array is the two-dimensional array. Both
the row's and column's index begins from 0. In other words an array
with two subscripts is known as two dimensional array. The general
form is
array-name[subscript1] [subscript2]
Where
int arr[10][20];
arr is an integer array containing 10 rows and 20 columns.
Rules
i) Array name should be a valid C-variable.
ii) Array name should be unique.
iii) The elements in the array should be of same type.
That is if an array is declared as integer, it cannot
contain elements that are not integer.
vi) The size of the array is got by multiplying the row size
and column size.
Example:
int mark[3][2]
mark is a two dimensional array with 3 rows and 2 columns. It has a
total of 6 (3 x 2) locations.
(a)1
0 mark[0][0] mark[0][1]
1 mark[1][0] mark[1][1]
2 mark[2][0] mark[2][1]
Where
si – size of the ith dimension.
Example:
int mark[2][3][4];
This declares mark as a three dimensional integer array containing 24 (2 x
3 x 4) elements of integer type.
Strings:
char variablename[size];
Where
char – datatype
size – maximum number of characters in the string including
‘\0’.
Example:
char city[10];
Where
static - keyword or storage class
char - data type variable
name - valid C variable
size - maximum number of characters plus
one.
string - valid string
Example:
C U M
B U M \0
Reading strings
scanf function :
format conversion ”%s” can be used in scanf for reading
strings not containing white spaces The general form is:
scanf("%s", variablename)
Where
Example
char name[15];
scanf(“%s”, name);
Input is : Sri Umaiyal
The string Sri only read into memory,because of the
blankspace after the word Sri. Here, the input string is treated as two
strings namely Sri and Umaiyal.
getchar function
This is a predefined function in C language which is available in
stdio.h header file. Using this function we can read a single character
from keyboard and store in character variable. When we want to read a
number of character form keyboard the store all the data in a character
array.
The general form is:
char variablename;
variablename=getch();
Note: getchar function has no any parameters.
gets
S r i U M A I Y A L \0
Writing strings
printf function
printf("%s", variablename)
Where
putchar
puts
Where puts(variable);
1. strlen() :
This function is used to find out the number of characters in the
given string. The syntax is
n = strlen(string);
Where
n - integer variable which receives the
length of the string.
Example:
strlen(“COLLEGE”) = 7
2. strcpy() :
strcpy(string1, string2);
Where
string1, string2 - valid strings.
Example:
string2 = “COLLEGE”;
strcpy(string1, string2);
The output is
string1 = “COLLEGE”
3. strcat() :
This function is used to join two strings. The syntax
is
strcat(string1, string2);
Where
Example:
string1 = “ARTS” string2 =
“COLLEGE”;
strcat(string1, string2);
The output is
string1 = “ARTSCOLLEGE”
string2 = “COLLEGE”
4. strcmp() :
This function is used to compare two strings. The syntax
is
strcmp(string1, string2);
Where
string1, string2 - valid strings.
If the two strings are equal the value of the function will be
zero. If string1 is greater tan string2, the value will be positive else
negative.
Example:
string1 = “LION”
string2 = “TIGER”;
strcmp(string1, string2);
The output is
-1 (i.e. string2 is greater than string1)
5. strrev() :
This function is used to reverse a string. The syntax
is
n = strrev(string);
Where
n - string variable to hold the reversed string. string
- valid string variable which contains the
string to be reversed.
Example:
n = strrev(“COLLEGE”);
The output is
n = “EGELLOC”
2 MARKS:
10 MARKS
1. Explain the C Tokens in detail?
2. Explain the constants and variables with relevant
example?
3. Write a C program to calculate the roots of an equation ?
4. Discuss the operator in C in detail?
5. Explain about Formatted Input and Formatted Output with
example?
6. Explain the various forms of If statement witj suitanle example?
7. Write a program to solve the quadratic equation?
8. Explain about C data types.
9. When we use getc, putc, undef, ifdef, goto?Explain it? 10.Write a
C program to sort an array of integers in
ascending order.