CPDS Unit 1
CPDS Unit 1
History of C Language
➢ The base or father of programming languages is 'ALGOL.' It was first
introduced in 1960.
➢ 'ALGOL' was used on a large basis in European countries. 'ALGOL'
introduced the concept of structured programming to the developer
community.
➢ In 1967, a new computer programming language was announced called
as 'BCPL' which stands for Basic Combined Programming Language. BCPL
was designed and developed by Martin Richards, especially for writing
system software. This was the era of programming languages.
➢ in 1970 a new programming language called 'B' was introduced by Ken
Thompson that contained multiple features of 'BCPL.' This programming
language was created using UNIX operating system at AT&T and Bell
Laboratories. Both the 'BCPL' and 'B' were system programming
languages.
As every language has some basic geometrical rules and elements, similarly
C language has some elements and rules for building a program which has
some meaning.
Character Set: In Real world to communicate with people we use language like
Hindi English Urdu extra which is constructed and Defined by some characters,
words extra. Similarly in C programming language we have various characters
to communicate with the computer in order to produce a meaningful program
and can produce an output.
Lowercase a-z
Uppercase A-Z
Digits 0-9
Keywords:
They are 32 Keywords in C language whose meaning has already being defined.
32 keywords in C language
union const
Data types:
Each variable in C has an associated data type. Each data type requires
different amounts of memory and has some specific operations which can be
performed over it. Let us briefly describe them one by one:
Following are the examples of some very common data types used in C:
• char: The most basic data type in C. It stores a single character and requires
a single byte of memory in almost all compilers.
• int: As the name suggests, an int variable is used to store an integer.
• float: It is used to store decimal numbers (numbers with floating point
value) with single precision.
• double: It is used to store decimal numbers (numbers with floating point
value) with double precision.
Different data types also have different ranges upto which they can store
numbers. These ranges may vary from compiler to compiler.
int a;
float b;
char c;
Here, a, b, c are variables. The int, float, char are the data types.
We can also provide values while declaring the variables as given below:
int a;
int _ab;
int a30;
int 2;
int a b;
int long;
Types of Variables in C
1. local variable
2. global variable
Local Variable
A variable that is declared inside the function or block is called a local variable.
void function1()
{
int x=10;//local variable
}
Global Variable
Documentation Section
This section consists of comment lines which include the name of programmer,
the author and other details like time and date of writing the program.
Documentation section helps anyone to get an overview of the program.
/*This is
multi line
comment
*/
Link Section
The link section consists of the header files of the functions that are used in the
program. It provides instructions to the compiler to link functions from the
system library.
The link section consists of header files while contains function prototype of
Standard Library functions which can be used in program. Header file also
consists of macro declaration. Example:
#include <stdio.h>
In the above code, stdio.h is a header file which is included using the
preprocessing directive #include. Learn more about header files in C programming.
Definition Section
All the symbolic constants are written in definition section. Macros are known
as symbolic constants.
#define PI 3.14
In above code, the PI is a constant whole value is 3.14
The global variables that can be used anywhere in the program are declared in
global declaration section. This section also declares the user defined functions.
int a=10;
The main () function section is the most important section of any C program.
The compiler start executing C program from main() function.
The main() function is mandatory in C programming. It has two parts:
Declaration Part – All the variables that are later used in the executable
part are declared in this part.
Execuitable Part – This part contains the statements that are to be executed by
the compiler
main()
-----------
-----------
Subprogram Section
The subprogram section contains all the user defined functions that are used to
perform a specific task. These user defined functions are called in the main()
function.
C - Operators
An operator is a symbol that tells the compiler to perform specific mathematical or
logical functions. C language is rich in built-in operators and provides the following
types of operators −
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language.
Assume variable A holds 10 and variable B holds 20 then −
Show Examples
Output
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1
return 0;
}
Output
++a = 11
--b = 99
++c = 11.500000
--d = 99.500000
Relational Operators
The following table shows all the relational operators supported by C. Assume
variable A holds 10 and variable B holds 20 then −
Show Examples
== Checks if the values of two operands are equal or not. If yes, then the (A == B)
condition becomes true. is not
true.
!= Checks if the values of two operands are equal or not. If the values are not (A != B)
equal, then the condition becomes true. is true.
> Checks if the value of left operand is greater than the value of right (A > B)
operand. If yes, then the condition becomes true. is not
true.
< Checks if the value of left operand is less than the value of right operand. If (A < B)
yes, then the condition becomes true. is true.
>= Checks if the value of left operand is greater than or equal to the value of (A >= B)
right operand. If yes, then the condition becomes true. is not
true.
<= Checks if the value of left operand is less than or equal to the value of right (A <= B)
operand. If yes, then the condition becomes true. is true.
return 0;
}
Output
5 == 5 is 1
5 == 10 is 0
5 > 5 is 0
5 > 10 is 0
5 < 5 is 0
5 < 10 is 1
5 != 5 is 0
5 != 10 is 1
5 >= 5 is 1
5 >= 10 is 0
5 <= 5 is 1
5 <= 10 is 1
Logical Operators
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then −
Show Examples
! Called Logical NOT Operator. It is used to reverse the logical state of its !(A &&
operand. If a condition is true, then Logical NOT operator will make it false. B) is
true.
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;
return 0;
}
Output
(a == b) && (c > b) is 1
(a == b) && (c < b) is 0
(a == b) || (c < b) is 1
(a != b) || (c < b) is 0
!(a != b) is 1
!(a == b) is 0
Assignment Operators
The following table lists the assignment operators supported by the C language −
Show Examples
= Simple assignment operator. Assigns values from right side operands to C=A+B
left side operand will assig
the value
of A + B
to C
+= Add AND assignment operator. It adds the right operand to the left C += A is
operand and assign the result to the left operand. equivalen
to C = C
A
-= Subtract AND assignment operator. It subtracts the right operand from the C -= A is
left operand and assigns the result to the left operand. equivalen
to C = C
A
*= Multiply AND assignment operator. It multiplies the right operand with the C *= A is
left operand and assigns the result to the left operand. equivalen
to C = C
A
/= Divide AND assignment operator. It divides the left operand with the right C /= A is
operand and assigns the result to the left operand. equivalen
to C = C
A
%= Modulus AND assignment operator. It takes modulus using two operands C %= A i
and assigns the result to the left operand. equivalen
to C = C
%A
c = a; // c is 5
printf("c = %d\n", c);
c += a; // c is 10
printf("c = %d\n", c);
c -= a; // c is 5
printf("c = %d\n", c);
c *= a; // c is 25
printf("c = %d\n", c);
c /= a; // c is 5
printf("c = %d\n", c);
c %= a; // c = 0
printf("c = %d\n", c);
return 0;
}
Output
c = 5
c = 10
c = 5
c = 25
c = 5
c = 0
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for
&, |, and ^ is as follows −
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
& Binary AND Operator copies a bit to the result if it exists in both (A & B) = 12,
operands. 0000 1100
^ Binary XOR Operator copies the bit if it is set in one operand but not (A ^ B) = 49, i
both. 0011 0001
~ Binary One's Complement Operator is unary and has the effect of (~A ) = ~(60),
'flipping' bits. 0111101
<< Binary Left Shift Operator. The left operands value is moved left by A << 2 = 240
the number of bits specified by the right operand. 1111 0000
>> Binary Right Shift Operator. The left operands value is moved right by
A >> 2 = 15 i.
the number of bits specified by the right operand.
0000 1111
For example,
As we can observe from the above result that bits of both the variables are
compared one by one. If the bit of both the variables is 1 then the output would be
1, otherwise 0.
#include <stdio.h>
int main()
{
int a=6, b=14; // variable declarations
printf("The output of the Bitwise AND operator a&b is %d",a&b);
return 0;
}
In the above code, we have created two variables, i.e., 'a' and 'b'. The values of
'a' and 'b' are 6 and 14 respectively. The binary value of 'a' and 'b' are 0110 and
1110, respectively. When we apply the AND operator between these two variables,
Bitwise OR operator
The bitwise OR operator is represented by a single vertical sign (|). Two
integer operands are written on both sides of the (|) symbol. If the bit value of any
of the operand is 1, then the output would be 1, otherwise 0.
For example,
As we can observe from the above result that the bits of both the operands are
compared one by one; if the value of either bit is 1, then the output would be 1
otherwise 0.
#include <stdio.h>
int main()
{
int a=23,b=10; // variable declarations
printf("The output of the Bitwise OR operator a|b is %d",a|b);
return 0;
}
For example,
As we can observe from the above result that the bits of both the operands are
compared one by one; if the corresponding bit value of any of the operand is 1, then
the output would be 1 otherwise 0.
Let's understand the bitwise exclusive OR operator through a program.
#include <stdio.h>
int main()
{
int a=12,b=10; // variable declarations
printf("The output of the Bitwise exclusive OR operator a^b is %d",a^b);
return 0;
}
For example,
As we can observe from the above result that if the bit is 1, then it gets changed to
0 else 1.
#include <stdio.h>
int main()
{
int a=8; // variable declarations
printf("The output of the Bitwise complement operator ~a is %d",~a);
return 0;
}
o Left-shift operator
o Right-shift operator
Left-shift operator
Operand << n
Where,
In the case of Left-shift operator, 'n' bits will be shifted on the left-side. The 'n' bits
on the left side will be popped out, and 'n' bits on the right-side are filled with 0.
For example,
#include <stdio.h>
int main()
{
int a=5; // variable initialization
printf(": %d ", a<<2);
return 0; The value of a<<2 is
}
Right-shift operator
Operand >> n;
Where,
In the case of the right-shift operator, 'n' bits will be shifted on the right-side. The
'n' bits on the right-side will be popped out, and 'n' bits on the left-side are filled
with 0.
For example,
#include <stdio.h>
int main()
{
int a=7; // variable initialization
printf("The value of a>>2 is : %d ", a>>2);
return 0;
}
Output: The value of a>>2 is : 1
C Format Specifier
The Format specifier is a string used in the formatted input and output functions.
The format string determines the format of the input and output. The format string
always starts with a '%' character.
Format Description
specifier
%d or %i It is used to print the signed integer value where signed integer means that
variable can hold both positive and negative values.
%u It is used to print the unsigned integer value where the unsigned integer me
the variable can hold only positive value.
%o It is used to print the octal unsigned integer where octal integer value alway
with a 0 value.
%X It is used to print the hexadecimal unsigned integer, but %X prints the alpha
characters in uppercase such as A, B, C, etc.
%g It is used to print the decimal floating-point values, and it uses the fixed pre
i.e., the value after the decimal in input would be exactly the same as the va
the output.
Example
#include <stdio.h>
main() {
char ch = 'B';
printf("%d\n", x);
printf("%i\n", y);
float f = 12.67;
int a = 67;
printf("%s\n", str);
printf("%20.5s\n", str); //shift to the right 20 characters including the string, and print string
up to 5 character
printf("%-20.5s\n", str); //left align and print string up to 5 character
Output
B
45
90
12.670000
1.267000e+001
103
43
Hello World
Hello World
Hello World
Hello
Hello
C programming language provides many built-in functions to read any given input and to
display data on screen when there is a need to output the result.
The standard input-output header file, named stdio.h contains the definition of the
functions printf() and scanf(), which are used to display output on screen and to take input from
user respectively.
#include<stdio.h>
void main()
{
// defining a variable
int i;
/*
displaying message on the screen
asking the user to input a value
*/
printf("Please enter a value...");
/*
reading the value entered by the user
*/
scanf("%d", &i);
/*
displaying the number as output
*/
printf( "\nYou entered: %d", i);
}
When you will compile the above code, it will ask you to enter a value. When you will enter
the value, it will display the value you have entered on screen.
You must be wondering what is the purpose of %d inside the scanf() or printf() functions. It is
known as format string and this informs the scanf() function, what type of input to expect and
in printf() it is used to give a heads up to the compiler, what type of output to expect.
We can also limit the number of digits or characters that can be input or output, by adding a
number with the format string specifier, like "%1d" or "%3s", the first one means a single
numeric digit and the second one means 3 characters, hence if you try to input 42,
while scanf() has "%1d", it will take only 4 as input. Same is the case for output.
In C Language, computer monitor, printer etc output devices are treated as files and the
same process is followed to write output to these devices as would have been followed to
write the output to a file.
NOTE : printf() function returns the number of characters printed by it, and scanf() returns the
number of characters read by it.
#include <stdio.h>
void main( )
{
int c;
printf("Enter a character");
/*
Take a character as input and
store it in variable c
*/
c = getchar();
/*
in variable c
*/
putchar(c);
When you will compile the above code, it will ask you to enter a value. When you will enter
the value, it will display the value you have entered.
The gets() function reads a line from stdin(standard input) into the buffer pointed
to str pointer, until either a terminating newline or EOF (end of file) occurs. The puts() function
writes the string str and a trailing newline to stdout.
str → This is the pointer to an array of char where the C string is stored.
#include<stdio.h>
int main()
{
/* character array of length 100 */
char str[100];
printf("Enter a string");
gets( str );
puts( str );
return 0;
}
When you will compile the above code, it will ask you to enter a string. When you will enter
the string, it will display the value you have entered.
Escape Sequence in C
An escape sequence in C language is a sequence of characters,It is composed
of two or more characters starting with backslash \. For example: \n represents
new line.
\a Alarm or Beep
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Tab (Horizontal)
\v Vertical Tab
\\ Backslash
\? Question Mark
\0 Null
Example
#include<stdio.h>
int main()
{
int number=50;
Output:
You
are
learning
'c' language
"Do you know C language"
1 if statement
2 if...else statement
3 nested if statements
You can use one if or else if statement inside another if or else if statement(s).
4 switch statement
A switch statement allows a variable to be tested for equality against a list of values
5 nested switch statements
You can use one switch statement inside another switch statement(s).
o If statement
o If-else statement
o If else-if ladder
o Nested if
If Statement
if(expression)
{
//code to be executed
}
Flowchart of if statement in C
Output
If-else Statement
if(expression)
{
//code to be executed if condition is true
}
else
{
//code to be executed if condition is false
}
#include<stdio.h>
int main()
{
int number=0;
printf("enter a number:");
scanf("%d",&number);
if(number%2==0)
{
printf("%d is even number",number);
}
else
{
printf("%d is odd number",number);
}
return 0;
}
Output
enter a number:4
4 is even number
enter a number:5
5 is odd number
//Program to check whether a person is eligible to vote or not.
#include <stdio.h>
int main()
{
int age;
printf("Enter your age?");
scanf("%d",&age);
if(age>=18)
{
printf("You are eligible to vote...");
}
else
{
printf("Sorry ... you can't vote");
}
} Output
Enter your age?18
You are eligible to vote...
Enter your age?13
Sorry ... you can't vote
if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Output
enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
//Program to calculate the grade of the student according to the specified
marks.
#include <stdio.h>
int main()
{
int marks;
printf("Enter your marks?");
scanf("%d",&marks);
if(marks > 85 && marks <= 100)
{
printf("Congrats ! you scored grade A ...");
}
else if (marks > 60 && marks <= 85)
{
printf("You scored grade B + ...");
}
else if (marks > 40 && marks <= 60)
{
printf("You scored grade B ...");
}
else if (marks > 30 && marks <= 40)
{
printf("You scored grade C ...");
}
else
{
printf("Sorry you are fail ...");
}
}
Output:
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
3) The case value can be used only inside the switch statement.
Let's try to understand it by the examples. We are assuming that there are
following variables.
int x,y,z;
char a,b;
float f;
#include<stdio.h>
int main()
{
int number=0;
printf("enter a number:");
scanf("%d",&number);
switch(number){
case 10: printf("number is equals to 10");
break;
case 50:
printf("number is equal to 50");
break;
case 100:
printf("number is equal to 100");
break;
default:
printf("number is not equal to 10, 50 or 100");
}
return 0;
}
Output
enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
#include <stdio.h>
int main()
{
int x = 10, y = 5;
switch(x>y && x+y>0)
{
case 1:
printf("hi");
break;
case 0:
printf("bye");
break;
default:
printf(" Hello bye ");
}
}
Output
hi
C Switch statement is fall-through
Let's try to understand the fall through state of switch statement by the
example given below.
#include<stdio.h>
int main()
{
int number=0;
printf("enter a number:");
scanf("%d",&number);
switch(number){
case 10:
printf("number is equal to 10\n");
case 50:
printf("number is equal to 50\n");
case 100:
printf("number is equal to 100\n");
default:
printf("number is not equal to 10, 50 or 100");
}
return 0;
}
Output
enter a number:10
number is equal to 10
number is equal to 50
number is equal to 100
number is not equal to 10, 50 or 100
#include <stdio.h>
int main ()
{
int i = 10;
int j = 20;
switch(i)
{
case 10:
printf("the value of i evaluated in outer switch: %d\n",i);
case 20:
switch(j)
{
case 20:
printf("The value of j evaluated in nested switch: %d\n",j);
}
}
printf("Exact value of i is : %d\n", i );
printf("Exact value of j is : %d\n", j );
return 0;
}
Output
LOOPS IN C
1.for loop
2.while loop
3.do...while loop
1.for loop:
The for loop in C language is used to iterate the statements or a part of the
program several times.
This process goes on until the test expression is false. When the test expression
is false, the loop terminates.
for loop Flowchart
int main() {
int i;
for (i = 1; i < 11; ++i)
{
printf("%d ", i);
}
return 0;
}
Output
1 2 3 4 5 6 7 8 9 10
1. i is initialized to 1.
2. The test expression i < 11 is evaluated. Since 1 less than 11 is true, the body
of for loop is executed. This will print the 1 (value of i) on the screen.
3. The update statement ++i is executed. Now, the value of i will be 2. Again, the
test expression is evaluated to true, and the body of for loop is executed. This
will print 2 (value of i) on the screen.
4. Again, the update statement ++i is executed and the test expression i < 11 is
evaluated. This process goes on until i becomes 11.
5. When i becomes 11, i < 11 will be false, and the for loop terminates.
Output
Syntax
Example:
#include <stdio.h>
int main()
{
int n;// variable declaration
printf("Enter the value of n :");
// Displaying the n tables.
for(int i=1;i<=n;i++) // outer loop
{
for(int j=1;j<=10;j++) // inner loop
{
printf("%d\t",(i*j)); // printing the value.
}
printf("\n");
}
Output:
EXAMPLE -2
#include <stdio.h>
int main()
{
for (int i=0; i<2; i++)
{
for (int j=0; j<4; j++)
{
printf("%d, %d\n",i ,j);
}
}
return 0;
}
Output:
0, 0
0, 1
0, 2
0, 3
1, 0
1, 1
1, 2
1, 3
2.while loop in C
while(condition){
//code to be executed
}
Flowchart of while loop in C
Example:
#include<stdio.h>
int main()
{
int i=1;
while(i<=10){
printf("%d \n",i);
i++;
}
return 0;
}
Output:
Example:
#include<stdio.h>
int main()
{
int i=1,number=0,b=9;
printf("Enter a number: ");
scanf("%d",&number);
while(i<=10){
printf("%d \n",(number*i));
i++;
}
return 0;
}
Output:
The do while loop is a post tested loop. Using the do-while loop, we can
repeat the execution of several parts of the statements. The do-while loop is
mainly used in the case where we need to execute the loop at least once. The
do-while loop is mostly used in menu-driven programs where the termination
condition depends upon the end user.
do{
//code to be executed
}while(condition);
Example
#include <stdio.h>
int main () {
/* do loop execution */
do {
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );
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
Arrays
o Each element of an array is of same data type and carries the same size,
i.e.,
int = 2 bytes.
Advantages of an Array
2) Ease of traversing: By using the for loop, we can retrieve the elements of an
array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of
code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of an Array
1) Fixed Size: Whatever size, we define at the time of declaration of the
array, we can't exceed the limit. So, it doesn't grow the size dynamically
like LinkedList which we will learn later.
Array types:
There are mainly three types of the arrays:
One Dimensional (1D) Array
Multidimensional Array
Declaration of an Array
1.data_type array_name[array_size];
2. int marks[5];
Here, int is the data_type, marks are the array_name, and 5 is the array_size.
Initialization of an Array
The simplest way to initialize an array is by using the index of each element. We
can initialize each element of the array by using the index.
//int marks[5];
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
Example:
#include<stdio.h>
int main()
{
int i=0;
int marks[5];//declaration of array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++)
{
printf("%d \n",marks[i]);
}//end of for loop
return 0;
}
Output:
80
60
70
85
7570 E
1. int marks[5]={20,30,40,50,60};
2. int marks[]={20,30,40,50,60};
Example:
#include<stdio.h>
int main(){
int i=0;
int marks[5]={20,30,40,50,60};//declaration and initialization of array
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}
return 0;
}
Output :20 30 40 50 60
Example:
#include<stdio.h>
int main()
{
int marks[5],i;
printf("\n ENTER MARKS:");
for(i=0;i<5;i++)
{
scanf("%d",&marks[i]);
}
printf("\n ENTERED MARKS:");
for(i=0;i<5;i++)
{
printf("%d \n",marks[i]);
}
return 0;
}
Output:
ENTER MARKS:90
63
72
45
54
ENTERED MARKS:90
63
72
45
54
Two Dimensional Array
The two-dimensional array can be defined as an array of arrays. The 2D
array is organized as matrices which can be represented as the collection of
rows and columns.
1. data_type array_name[rows][columns];
2. int x [3][3];
Here, the first 3 is the number of rows, and next 3 is the number of columns.
Example:
#include<stdio.h>
int main(){
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++)
{
for(j=0;j<3;j++)
{
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}//end of j
}//end of i
return 0;
}
Output:
arr[0] [0] = 1
arr[0] [1] = 2
arr[0] [2] = 3
arr[1] [0] = 2
arr[1] [1] = 3
arr[1] [2] = 4
arr[2] [0] = 3
arr[2] [1] = 4
arr[2] [2] = 5
arr[3] [0] = 4
arr[3] [1] = 5
arr[3] [2] = 6
Example:
#include <stdio.h>
void main ()
{
int arr[3][3],i,j;
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
printf("Enter a[%d][%d]: ",i,j);
scanf("%d",&arr[i][j]);
}
}
printf("\n printing the elements ....\n");
for(i=0;i<3;i++)
{
printf("\n");
for (j=0;j<3;j++)
{
printf("%d\t",arr[i][j]);
}
}
}
Output:
Enter a[0][0]: 10
Enter a[0][1]: 20
Enter a[0][2]: 30
Enter a[1][0]: 40
Enter a[1][1]: 50
Enter a[1][2]: 60
Enter a[2][0]: 70
Enter a[2][1]: 80
Enter a[2][2]: 90
10 20 30
40 50 60
70 80 90
Matrix addition
#include <stdio.h>
int main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
return 0;
}
Output:
Enter the number of rows and columns of matrix
2
2
Enter the elements of first matrix
1
2
3
4
Enter the elements of second matrix
1
2
3
3
1. By char array
2. By string literal
char ch[10]={'b', 'h', 'a', 'v', 'm', 'a', 'n', 'y', 'u', 'n', '\0'};
0 1 2 3 4 5 6 7 8
9 10
b h a v m a n y u n \0
While declaring string, size is not mandatory. So we can write the above code as
given below:
char ch[]={'b', 'h', 'a', 'v', 'm', 'a', 'n', 'y', 'u', 'n', '\0'};
For example:
char ch[]="bhavmanyun";
In the above case, ‘\0’ will be appended at the end of the string by the compiler.
o In character Array We need to add the null character '\0' at the end of
the array by ourself
o In string literal we don’t need to add null character the compiler itself
appended at the end of the string.
Example:
#include<stdio.h>
#include <string.h>
int main()
{
char ch[11]={'b', 'h', 'a', 'v', 'm', 'a', 'n', 'y', 'u', 'n', '\0'};
char ch2[11]="bhavmanyun";
printf("Char Array Value is: %s\n", ch);
printf("String Literal Value is: %s\n", ch2);
return 0;
}
Output :
Traversing String
➢ Traversing the string is one of the most important aspects in any of the
programming languages.
➢ We may need to manipulate a very large text which can be done by
traversing the text.
➢ Traversing string is somewhat different from the traversing an integer
array.
➢ We need to know the length of the array to traverse an integer array,
whereas we may use the null character in the case of string to identify
the end the string and terminate the loop.
#include<stdio.h>
void main ()
{
char s[11] = "Bhavmanyun";
int i = 0;
int count = 0;
while(i<11)
{
if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
{
count ++;
}
i++;
}
printf("The number of vowels %d",count);
}
Let's see the same example of counting the number of vowels by using the
null character.
#include<stdio.h>
void main ()
{
char s[11] = "Bhavmanyun";
int i = 0;
int count = 0;
while(s[i] !=NULL)
{
if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
{
count ++;
}
i++;
}
printf("The number of vowels %d",count);
getch();
}
Output:The number of vowels 3 of vowels
Till now, we have used scanf to accept the input from the user.
However, it can also be used in the case of strings but with a different scenario.
Consider the below code which stores the string while space is encountered.
#include<stdio.h>
void main ()
{
char s[20];
printf("Enter the string?");
scanf("%s",s);
printf("You entered %s",s);
}
Output:
➢ It is clear from the output that, the above code will not work for space
separated strings.
➢ To make this code working for the space separated strings, the minor
changed required in the scanf function, i.e., instead of writing
scanf("%s",s), we must write: scanf("%[^\n]s",s) which instructs the
compiler to store the string s while the new line (\n) is encountered.
Let's consider the following example to store the space-separated strings.
#include<stdio.h>
void main ()
{
char s[20];
printf("Enter the string?");
scanf("%[^\n]s",s);
printf("You entered %s",s);
}
Output:
➢ Here we must also notice that we do not need to use address of (&)
operator in scanf to store a string
➢ Since string s is an array of characters and the name of the array, i.e., s
indicates the base address of the string (character array) therefore we
need not use & with it.
The gets() and puts() are declared in the header file stdio.h. Both the
functions are involved in the input/output operations of the strings.
gets() function
➢ The gets() function enables the user to enter some characters followed
by the enter key.
➢ All the characters entered by the user get stored in a character array.
➢ The null character is added to the array to make it a string.
➢ The gets() allows the user to enter the space-separated strings. It returns
the string entered by the user.
Example:
//Reading string using gets()
#include<stdio.h>
void main ()
{
char s[30];
printf("Enter the string? ");
gets(s);
printf("You entered %s",s);
}
Output:
Enter the string? cse
You entered cse
C puts() function
Let's see an example to read a string using gets() and print it on the console
using puts().
#include<stdio.h>
#include <string.h>
int main()
{
char name[50];
printf("Enter your name: ");
gets(name); //reads string from user
printf("Your name is: ");
puts(name); //displays string
return 0;
}
Output:
Enter your name: anand
Your name is: anand
C String Functions
No Function Description
.
#include<stdio.h>
#include <string.h>
int main()
{
char ch[20]={'s', 'i', 'd', 'd', 'a', 'r', 't', 'h', 'a', 't', '\0'};
printf("Length of string is: %d",strlen(ch));
return 0;
}
Output:
#include<stdio.h>
#include <string.h>
int main()
{
char ch[20]={'s', 'i', 'd', 'd', 'a', 'r', 't', 'h', 'a', '\0'};
char ch2[20];
strcpy(ch2,ch);
printf("Value of second string is: %s",ch2);
return 0;
}
Output:
#include<stdio.h>
#include <string.h>
int main()
{
char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
char ch2[10]={'c', '\0'};
strcat(ch,ch2);
printf("Value of first string is: %s",ch);
return 0;
}
Here, we are using gets() function which reads string from the console.
#include<stdio.h>
#include <string.h>
int main()
{
char str1[20],str2[20];
printf("Enter 1st string: ");
gets(str1);//reads string from console
printf("Enter 2nd string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;
}
Output:
#include<stdio.h>
#include <string.h>
int main()
{
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nReverse String is: %s",strrev(str));
return 0;
}
Output:
#include<stdio.h>
#include <string.h>
int main()
{
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nLower String is: %s",strlwr(str));
return 0;
}
Output:
Enter string:ANT
Lower String is: ant
String Uppercase: strupr()
#include<stdio.h>
#include <string.h>
int main()
{
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nUpper String is: %s",strupr(str));
return 0;
}
Output:
Enter string:ant
String is:ant
Lower String is: ANT