C Programming Notes
C Programming Notes
Introduction to C:
C is a general purpose language and was invented and first implemented by
Dennis Ritchie on a DEC PDP-11 that used the Unix operating system. It was
developed in AT&T Bell Labs in the year 1972. C Language was developed from
the language B. The hierarchy of the languages is as shown below:
ALGOL 60
(International Committee -1960)
CPL
(Cambridge & Univ. Of London-1963)
BCPL
DEVELOPMENT OF C (Martin Richards-cambridge-1967)
B
(Ken Thompson,Bell Labs.1970)
C
(Dennis Ritchie,bell Labs.1972)
Features of C Language:
a. It is relatively low level Language. Also know as middle level language.
b. C is a Structural Language.
c. It is Modular: As C supports functions, each from can be divided into
modules and sub modules thereby helping in achieving the modularity.
d. C is Procedural Language.
e. C language is Portable is nature: It can be used across various platforms, it
is known as portable in nature.
f. C language supports various data type usage.
g. C language is easy to use
h. It makes use of recursion.
i. Even though C is not strongly typed language, it supports type checking.
j. It provides fundamental control flow constructions as decision control,
looping etc.
C Character Set:
a. Alphabets -- A B...... Y Z and a b……y z
b. Digits -- 0,1,2,3,4,5,6,7,8,9
c. Special symbols -- ~ ` ! @ # % ^ & * ( ) _ - + = | \ { } [ ] : ; " ' < > , . ? /
d. White Spaces – tabs, spaces enter
C Tokens
Token is the smallest unit of a C program. It can be categorized into different
types as shown below:
C Tokens
a. Keywords:
The keywords are the reserved words whose meaning is already defined by
the C language. There are total 32 keywords in a C language. These are
used by the compiler as an aid to compile the program. These are always
written in lower case. The following is the list of valid keywords in C
language.
auto int double struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
b. Identifiers:
An identifier is used to name any variable, function or a program in C.
Usually the ideal length of an identifier is 31 characters for TC. So as to
write a valid identifier the following rules must be considered:
It contains only alphabets, numbers and underscore.
An Identifier should not start with digit.
White spaces are not allowed in an identifier.
Upper case and lower case alphabets are considered to be different.
Special symbols are not allowed except underscore.
c. Constants:
Constants are the ones whose value remains unchanged throughout the
program. The constants can be categorized into two major categories as:
Integer Constants:
These contain the integer value without the decimal point. It can be
either positive or negative. The allowed range for defining integer
constants is: -32768 to 32767
Real Constants:
These are also known as the floating point constants. They can be
written using two methods as:
i. Fractional Method
ii. Exponential Method
Character Constants:
These contain only single character as the value and the value is
always enclosed in a single quotes.
String Constants:
These contain single or than one character or value enclosed in
double quotes. String constant always ends with the null character.
Defining the Constants:
The constants can be defined using any one of the following two methods:
i. Symbolic Constant: In this type the constants are defined after the
preprocessor directives and they make use of #define.
Example: #define pi 3.14
ii. Using const Keyword: In this type we define constant by making use of
the const keyword and declare it inside a function.
Syntax: const data_type variable_name = value;
Example: const float pi = 3.14;
d. Operators:
Operator is the one which performs action on the operands to give the
result. C language supports different operators as:
Arithmetic Operators Ternary/Conditional
Logical Operators Operators
Relational Operators Bitwise Operators
Assignment Operators Special Operators
Unary Operators
These are described in the following section:
1. Arithmetic Operators:
These are the binary operators. They can be classified as:
AND (&&) This operation returns true value only if both the
given conditions are true.
A B A&&B
0 0 0
0 1 0
1 0 0
1 1 1
OR (||) This operator returns true value if any one of the
operand is true.
A B A||B
0 0 0
0 1 1
1 0 1
1 1 1
NOT (!) This operator changes the true value to false and vice
a versa.
3. Relational Operators:
These operators are used for the purpose of comparison. These can
be classified as:
< Less than. x<y (x is less than y)
<= Less than equal to. x<=y (x is less than or equal to y)
> Greater than. x>y (x is greater than y)
>= Greater than equal to. x>=y (x is greater than or equal to y)
== Equal to. x==y (x is equal to y)
!= Not equal to. x!=y (x is not equal to y)
4. Assignment Operator:
This operator is used to assign a given value to the given variable. It
is denoted by = sign.
Example: x=5; This says that value 5 is assigned to the variable x.
5. Unary Operators:
These operators operate on the single operand. These can be
categorized as:
a. Increment Operator (++):
This operator is used to increment the value by 1.
Pre Increment It increments the value first and
++a considers the incremented value for
further calculation.
Post Increment It considers the value first for
a++ calculation and the increments it.
b. Decrement Operator (--):
This operator is used to decrement the value by 1.
Pre decrement It decrements the value first and
--a considers the decremented value for
further calculation.
Post decrement It considers the value first for
a-- calculation and the decrements it.
6. Ternary Operator:
The ternary operator is also known as the conditional operator. It
operates on three operands. This is denoted by (?:)
Syntax: Condition ? Part A : Part B;
If the given condition is true, then the part A is executed or else part
B is executed.
7. Bitwise Operators:
These operators operate at the bit level and are mostly used by the
compilers. These can be classified as:
Bitwise AND (&) This operation performs AND operation for
bit by bit. This operation returns true value
only if both the given conditions are true.
A B A&B
0 0 0
0 1 0
1 0 0
1 1 1
Bitwise OR (|) This operator returns true value if any one of
the operand is true.
A B A|B
0 0 0
0 1 1
1 0 1
1 1 1
Bitwise X OR (^) This operator returns false if both the
operands have same value or else it returns
true.
A B A^B
0 0 0
0 1 1
1 0 1
1 1 0
Bitwise Shift Operators
Left Shift Bit Pattern of the data can be shifted by specified
number of Positions to Left. When Data is Shifted Left ,
(<<) leading zero’s are filled with zero.
Syntax: Variable<<number of bits;
Original Number 0000 0000 0011 1100
8. Special Operators:
C language supports special operators for different purpose.
comma operator Comma operator can be used
to link the related expressions
together. They are evaluated
left to right. These are mostly
used in for loops and multiple
variable declaration.
sizeof operator This is a compile time operator
and returns the total number of
bytes the particular operand
occupies.
b. Compiling a Program:
The source program statements must be translated into the object program
which is then executed. The file generated is known as .obj file. The
translation is done only when all the instructions are syntactically correct.
c. Executing a Program:
Once the compilation is done, the file is loaded in the main memory and
executed. The result of this process is given in .exe file.
C SOURCE CODE
C PREPROCESSOR
STAGES IN C COMPILER
LINKER
EXECUTABLE CODE
LOADER
Structure of a C Program:
The C language is procedural in nature. So it defines its own structure. The
execution of the program starts from the main() function and each of the program
has one main function. The C program consists of variables, input statements,
processing statements, comments, output statements, user defined fuctions and
various other structures. The figure shows the structure of a C Program and the
later part shows the description of each of the element:
Comments if any
Preprocessors Directive
Global Declarations
void main()
{
Local Declarations
STATEMENTS
Input
Processing
Output
}
The Structure is as explained below:
a. Comments:
The comments are the documentary part in a C program and they are not
being executed by the compiler. The comments are for users and
programmers reference. The comments can be given by two different ways:
i. Single line comments: These are given by // symbol.
Example: //This is a Single Line Comment.
ii. Multiline comments: These are given in between / * */
Example: /* This is a Multi Line Comment
and not compiled by compiler*/
b. Preprocessor Directive
The preprocessor directive includes the header files in which all the built in
functions are defined. The header files ends with the .h extension. It tells
the compiler to see the syntax of the functions and their definition in the
header files. The header files must be included using the #include directive.
The header files are always enclosed in the pair of < > brackets.
Example: #include<stdio.h> This is standard input/output header file which
defines different functions such as printf(), scanf() etc.
c. Global Declarations
This part declares the variables which can be accessed throughout the
program and their scope is in complete program.
d. main() function
The main() function is the starting point of the execution of program. Each
program must have one main() function. The void return type says that the
function is not returning any of the value. main() function can be divided
into various parts as:
i. Local Declarations
In this section all the variables that are used in the function are
declared.
ii. Statements
The statements in the C program can be:
Input Statement: These are used to take the input from the
user.
Processing Statements: These are the statements in which the
actual calculations are being done.
Output Statement: This statement is used to display the output
of the given program to the user.
Output:
Enter two numbers 4 5
Addition is 9
Variable:
Variable is the one whose value changes. The variable must be declared by using
data type and a valid identifier. The variables must be declared for the following
reasons:
Declaration:
data_type variable_name;
Example: int a,b,c;
where a,b,c are the three variables which stores the integer type of the data.
Initialization:
data_type variable_name = value;
Data Types:
The data types are used to specify which type of data is to be stored and how
much amount of the memory is to be allocated. The C language data types can be
classified into different types as:
Format Specifier:
These are the elements in C language that specifies the compiler about the type
of the value to be stored in the declared variable. These are defined based on the
data type of the variable.
%d Used for Integer data types %o Octal numbers
%f Used for Floating point data types %x Hexadecimal numbers
%c Used for Character data types
%s Used for strings
%u Used for storing the address.
Example:
scanf(“%d%d”,&a,&b);
This statements says that the values are of integer type and are to be stored at
the address of variable a and b respectively.
Expressions
An expression is a sequence of operators and operands that reduces to a single
value. The value can be of any type. An operator is a language specific syntactical
token that requires the action to be taken. Operand are the one on which an
action is performed. Different types of expressions are:
Type of Expression Categories Example
Primary 1. Identifier name
2. Constant constant value pi
3. Parenthetical (2+2)
Unary 1. Prefix increment ++a
2. Prefix decrement --a
3. size in bytes sizeof(int)
4. minus/negation -2
Binary 1. Multiplicative 2*2 or2/2
2. Additive 2+2 or 6-4
Assignment 1. Simple Assignment x=2
2. Compound Assignment x+=2 x=x+2
Postfix 1. Function any function call
2. Postfix Increment a++
3. Postfix Decrement a--
Type Conversion:
double
float
long int
Promotion Hierarchy
unsigned int
int
short
char
b. Explicit Conversion
Many times there may arise a situation where we want to force a type
conversion in a way that is different from automatic conversion.
This is known as explicit type conversion.
The general form is: (type) Expression.
Statements
The statement causes an action to be performed by the program. It translates
directly into one or more executable computer instructions.
The following are the different types of statements:
Expression When we give semicolon to expression, they become
statements. Example: x=a+b;
Compound It is unit of code consisting of zero or more statements. It
is also known as block.
Example
{
a=5;
b=5;
c=a+b;
}
Labeled These consist of goto statements.
Selection These are the branching statements.
Example: if, if-else
Iterative These are the looping statements.
Jump These are the break, continue statements.
Decision Making
Selection or decision making allows us to choose between two or more
alternatives. It can be of different types:
1. Two way Selection
2. Multi way Selection
The selection is done based on the logical data. The logical and relational
operators are mostly used for the process of selection.
Simple if
The simple if statement is used to check the condition. If the give condition is true
or the condition gives non zero value, the block under if statement is executed.
Syntax:
if (condition)
{
Block of statements;
}
if else
The if else structure overcomes the disadvantage of simple if i.e. Even if the given
condition is true, simple if checks the rest of the conditions also.
The if-else structure checks the condition and based on the result of the
condition, it evaluates either of the block.
Syntax:
if(condition)
{
Block of statements if the condition is TRUE;
}
else
{
Block of statement if the condition is FALSE;
}
Nested if-else:
This structure is needed when the user needs to check for more than one
condition. This is the complex structure of the if-else block.
Syntax:
if(condition 1)
{
if(condition 2)
{
Block of Statements when both the conditions are TRUE;
}
else
{
Block of Statements when only condition 1 is TRUE;
}
}
else
{
if(condition 3)
{
Block of Statements when the condition1 is FALSE and 3 is TRUE;
}
else
{
Block of Statements when both the conditions are FALSE;
}
}
Null else:
Sometimes in the programming structure, we have the situation where the else
part is not present at that time the else part is written with only semicolon or it is
skipped. This is known as null else. The structure of the program becomes similar
to the simple if.
Dangling else:
This the erroneous condition in which the else part of the particular if statement
is misplaced. It is also known as misplaced else. It is always created when there is
no matching else for if, in such case, else is placed with the most nearest if
condition in a program.
else if ladder:
This construct is a multi way selection where we give the user with all the possible
options and finally a default else construct is given. It is mostly used when the
selection variable does not have integral value or else the same variable is being
tested in a given expression.
Syntax:
if(condition 1)
statement1;
else if(condition 2)
statement 2;
else if(condition 3)
statement 3;
else if(condition 4)
statement 4;
.
else if(condition n)
statement n;
else
default statement ;
Switch Statement:
The switch statement is also a multi way selection statement. It is used only when
the selection variable has integral value. It consists of four different keywords as:
a. switch
The switch indicates the starting of the switch statement. The selection
takes place based on the value of the selection variable present in the
switch.
b. case
This is used to define different blocks based on the possibilities the
selection variable can have.
c. break
This is the mandatory statement after every case definition. This indicates
that the case is executed and it comes out of the switch case without
checking the further cases. It results to force termination.
d. default
The default statement is similar to the last else in the else if ladder. This
statement is executed only if all the cases are checked and none of the
value is matched. The default is optional statement.
Syntax:
switch(variable_name)
{
case 1: Statement 1;
break;
case 2: Statement 2;
break;
.
.
case n: Statement n;
break;
default: statement;
}
Flowchart:
Continue Statement:
The continue statement works somewhat like the break statement. Instead of
forcing termination, however, continue forces the next iteration of the loop to
take place, skipping any code in between.
Repetition Statements: Looping
The loops are basically used when the user wants the same activity to be
performed again and again. Loops can be classified as:
1. Event Controlled and Counter Controlled Loops
a. Counter-controlled loops
A loop controlled by a counter variable, generally where the number
of times the loop will execute is known ahead of time.
Generally used with for loops
Can generally infer number of repetitions from code.
Examples:
– read 5 numbers
– print 7 items
– sort n items
b. Event-controlled loops
The loops where termination depends on an event rather than
executing a fixed number of times.
Generally used with while, do-while loops.
Can’t infer number of repetitions from program.
Examples:
– read until input ends
– read until a number encountered
– search through data until item found
2. Pre test and Post test Condition Loops
These are categorized based on the time the condition is being checked.
Pretest Loops
A logical condition is checked before each repetition to determine if the
loop should terminate or not.
If the condition is false, the loop is never executed.
– while loop
– for loop
Posttest Loops
A logical condition is checked after each repetition for termination.
In this the loop is executed atleast once even if the condition is false.
– do-while loop
1. while loop
Explanation:
This is the pretest loop in which the condition is checked prior to
entering the loop. It repeats a statement or group of statements while a
given condition is true
Syntax:
initialization statement;
while(condition)
{
Block of statement if condition is TRUE;
increment/decrement;
}
Flowchart:
2. for loop
Explanation:
This is also a pretest loop in which the condition is checked before
entering the loop. In thhis case all the three statements as initialization,
loop condition and update is placed in a single line separated by
semicolons.
We may have variations in foor loop where we have two conditions, which
can be separated by comma.
Syntax:
3. do while loop
Explanation:
The do while loop is also known as the exit controlled or post test loop
as this loop tests the condition only after the loop is executed. Even if the
loop condition is false, the body of the loop is executed once.
Syntax:
initiaalization statement;
do
{
Block of statement;
increment/decrement;
}while(condition);
Flowchart:
Infinite Loops:
This is the condition when the loop starts its execution, but the loop
termination condition is never met. This happens due to various reasons as:
you forget to increase the counter or the user never enters terminating
data item etc.
Example: Print the numbers from 1 to 10 using all loops.
while loop for loop do while loop
#include<stdio.h> #include<stdio.h> #include<stdio.h>
void main() void main() void main()
{ { {
int i=1; int i; int i=1;
while(i<=10) for(i=1;i<=10;i++) do
{ { {
printf(“\n%d”,i); printf(“\n%d”,i); printf(“\n%d”,i);
i++; i++;
} } }while(i<=10);
} } }
exit():
This function is defined in the stdlib.h header file and it is used to exit from the
program. This functions returns a non zero number and hence also written as
exit(0) or exit(1).
Functions in C
C language supports the use of the function. It is also used such that we can have
structural way of programming. As the program is divided into different modules
and submodules, this is also known as the modular programming approach.
The C language functions can be divided into two broad categories as:
1. Built in Functions
The built in functions are the ones which are already defined by the
language. There definition is present in the library of the C compiler by the
developers. For Example: printf(), scanf() etc.
These can also be classified as:
Memory management functions: malloc(), realloc(), calloc(), free()
String Manipulation Functions: strcpy(), strcmp(), strupr(), etc.
Buffer Manipulation Functions: memcpy(), memmove(), etc.
Character Manipulation Functions: islower(), isupper() etc.
Error Handling Functions: perror(), strerror(), etc.
Each of the user defined function must have three different parts as:
1. Function Declaration
2. Function Call
3. Function Definition.
Preprocessors Directive
Global Declarations
Function Declaration
void main()
{
Local Declarations
Input Statements
Function Call();
Processing Statements;
Output Statements;
}
} Function Definition()
Body of Function;
Function Declaration:
As the variables are declared before using, the user defined functions must also
be declared before using them. The function declaration syntax is:
return_type function_name(parameters/arguments if any);
Where, the return_type specifies the type of the value the function is going to
return. Function name is any name that satisfies the rules of identifier.
arguments/parameters are the values the function accept from the calling
function.
Function Call/Invocation of Function:
Once declared, the function must be called from some of the function. The syntax
of the function call depends on the type of value the function is reurning.
Syntax:
If function is returning any value:
some_variable=function_name(parameters if any);
If the function is not returning any value then the syntax is:
function_name(parameters if any);
Function Definition:
The function definition specifies the body of the function in which the tasks
performed by the function are defined.
Syntax:
return_type Function_name(parameters if any)
{
Body of Function;
}
Types of Function:
Based on the return type and the parameters the function can be categorized into
four different categories.
1. Without Return Type, Without Arguments
2. Without Return Type, With Arguments
3. With Return Type, Without Arguments
4. With Return Type, With Arguments
Whenever the function is without the return type, the return type of the
function is given as void or else it depends on the type of the data it is going
to return.
Output:
Enter two numbers 4 5
Addition is 9
#include<stdio.h>
void add(int a, int b); // Function without return type with parameters
void main()
{
int x,y;
printf(“Enter two numbers”);
scanf(“%d%d”,&x,&y);
add(x,y); // Function Call
}
void add(int a, int b) // Function Definition
{
int c;
c=a+b;
printf(“\n Addition is %d”,c);
}
Output:
Enter two numbers 4 5
Addition is 9
#include<stdio.h>
int add(); // Function with return type without parameters
void main()
{
int ans;
ans=add(); // Function Call
printf(“\n Addition is %d”,ans);
}
int add() // Function Definition
{
int a, b, c;
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b);
c=a+b;
return(c);
}
Output:
Enter two numbers 4 5
Addition is 9
With Return Type, With Arguments:
This type of function takes the values as the parameters or arguments from the
calling function and also return the value to the calling function.
Output:
Enter two numbers 4 5
Addition is 9
Passing Parameters in C
The C language provides two different ways of passing the arguments or
parameters. These are as described:
Call by Value Call By Reference
The copy of actual parameter is Instead of sending the copy, the
passed to the function address is passed as the
New memory area is created parameter
which can be used only within Changes in the function are
the function, changes in the reflected in the calling function
function are not reflected also.
Example: Example:
#include<stdio.h> #include<stdio.h>
void swap(int num1,int num2); void swap(int *num1,int *num2);
void main() void main()
{ {
int x,y; int x,y;
printf("\nEnter two numbers : "); printf("\nEnter two numbers : ");
scanf("%d%d",&x,&y); scanf("%d%d",&x,&y);
printf("\nBS x=%d y=%d",x,y); printf("\nBS x=%d y=%d",x,y);
swap(x, y); // Pass By Value swap(&x,&y); // Pass By Reference
printf("\nAS x=%d y=%d",x,y); printf("\nAS x=%d y=%d",x,y);
} }
--------------------------------------- ---------------------------------------
void swap(int num1,int num2) void swap(int *num1,int *num2)
{ {
int temp; int temp;
temp = num1; temp = *num1;
num1 = num2; *num1 = *num2;
num2 = temp; *num2 = temp;
printf("\nAS in function x=%d printf("\nAS in function x=%d
y=%d",num1,num2); y=%d",*num1,*num2);
} }
Output: Output:
Disadvantages:
It is hard to think the logic of a recursive function.
It is also difficult to debug the code containing recursion.
It may also lead to stack overflow.
void main()
{
int num,add;
printf("Enter a positive integer:\n");
scanf("%d",&num);
add=sum(num);
printf("sum=%d",add);
}
int sum(int n)
{
if(n==0)
return n;
else
return n+sum(n-1); /*self call to function sum() */
}
=5+4+3+2+1+0
=5+4+3+2+1
=5+4+3+3
=5+4+6
=5+10
=15
Local Variables
Variables that are declared inside a function or block are called local variables.
They can be used only by statements that are inside that function or block of
code. Local variables are not known to functions outside their own. Following is
the example using local variables. Here all the variables a, b and c are local to
main() function.
#include<stdio.h>
void main( )
{
int a, b, c; // Local Variables
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“\n Addition is %d”,c);
}
Output:
Enter two numbers 4 5
Addition is 9
Global Variables:
Global variables are defined outside of a function, usually on top of the program.
The global variables will hold their value throughout the lifetime of your program
and they can be accessed inside any of the functions defined for the program. A
global variable can be accessed by any function. That is, a global variable is
available for use throughout your entire program after its declaration.
#include<stdio.h>
int c; // Global Declaration
void main( )
{
int a, b; // Local Variables
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“\n Addition is %d”,c);
}
Output:
Enter two numbers 4 5
Addition is 9
Here, even though c is not defined by the main() function, it can be accessed by it
as the scope of variable c is global.
Storage Classes:
A storage class is an attribute that tells us where the variable would be stored,
what will be the initial value of the variable if no value is assigned to that variable,
life time of the variable and scope of the variable.
The C language provides four storage classes as:
1. Automatic Storage Class
2. Extern Storage Class
3. Static Storage Class
4. Register Storage Class
#include <stdio.h>
void Check();
void main()
{
Check();
Check();
Check();
}
void Check()
{
static int c=0;
printf("%d\t",c);
c=c+2;
}
Output: 0 2 4
Representation:
Initialization of 1D Array:
The array elements can be initialized in two different ways:
Method 1:
int a[5]={1,2,3,4,5};
Here, the five elements are being initialized. These can be represented as:
index: a[0] a[1] a[2] a[3] a[4]
1 2 3 4 5 Array Elements
Address: 1000 2000 4000 6000 7000
Where, the type may be any valid type supported by C. The rule for giving the
array name is same as the ordinary variable. The row size and column size should
be an individual constant.
Example: int a[3][3];
Representation:
Initialization:
The 2 D array can be initialized by two different methods:
Method 1:
int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};
1 2 3
4 5 6
7 8 9
Similar to 1D array, if only few elements are specified, then the rest are initialized
to 0.
Method 2:
In this each element is initialized individually by specifying the index.
int a[2][2];
a[0][0] = 1;
a[0][1] = 2;
a[0][2] = 3;
a[1][0] = 4;
a[1][1] = 5;
a[1][2] = 6;
a[2][0] = 7;
a[2][1] = 8;
a[2][2] = 9;
Accessing the 2D Array elements:
The 2D array elements can be accessed by making use of the nested for loops.
The outer loop is for the row elements and the inner loop for column elements.
The elements are accessed row wise i.e. for a particular row all the column
elements are taken and then the next row is considered.
Example: Program that calculates sum of all elements of 2D Array
void main()
{
int a[3][3], i, j, sum=0;
/*Accepts input from the user and stores it in 2-D array*/
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
scanf(“%d”,&a*i+*j+);
}
}
Here, the first set of nested loops are used to take input from the user whereas
the next ones are used to calculate the sum of elements.
Basic Concepts:
In order to make use of the string handling functions, the header file string.h has
to be included compulsorily.
Strings can be of two different types as:
1. Fixed Size Strings
2. Variable Size Strings
These are further classified as the length controlled and delimeted strings.
Declaration
The string can be declared by making use of the following syntax:
char string_name[size];
Initialization
The strings can be initialized by making use of the following syntax:
char a*10+ =”Hello hi ”;
Reading Strings
The input to the strings can be given by the user. This is taken by making use of
any of the three different ways:
1. scanf():
This is the standard input function that is used to receive the value from
user. The format specifier for the string is %s. The scanf() function
terminates as it finds the white space.
2. getchar()
This function is used to receive the single character of the string. The syntax
is as shown:
char ch,str[10];
ch=getchar(str);
3. gets()
This the input function used for the strings. It is not formatted input
statement. This function accepts the blank spaces as well as an input. It
terminates only when enter is pressed or EOF occurs.
Syntax: gets(string_name);
Writing Strings
In order to output the values of string,the following three output functions are
used:
1. printf()
This is the standard output function that is used to display the output on
the screen. This function is the formatted output statement.
2. putchar()
This is used to display the single character on the screen. The syntax is as
shown:
putchar(character_variable);
3. puts()
This function is used to display the given string as the output. This is not the
formatted output statement. The syntax is as shown below:
Syntax: puts(string_name);