CP Final
CP Final
1. Draw a flowchart to find the area of a triangle when its three sides are given
Algorithm
Step1:Read a,b,c
step2:calculate s=(a+b+c)/2
Step3:Calculate Area=[s*(s-a)*(s-b)*(s-c)]^0.5
Step4:print Area
Flowchart
Program
#include <stdio.h>
#include <math.h>
void main()
{
int s, a, b, c, area;
printf("Enter the values of a, b and c \n");
scanf("%d %d %d", &a, &b, &c);
/* compute s */
s = (a + b + c) / 2;
area = sqrt(s * (s - a) * (s - b) * (s - c));
printf("Area of a triangle = %d \n", area);
}
Program
#include <stdio.h>
int main()
{
int n, reversedNumber = 0, remainder;
while(n != 0)
{
remainder = n%10;
reversedNumber = reversedNumber*10 + remainder;
n /= 10;
}
return 0;
}
return 0;
}
4. write an algorithm and flowchart to generate all numbers which are divisible by 3 but not by 7
Algorithm:
Step1:Read n,i=1
Step2 check the condition i%3=0 and i%7!=0.If the condition is true then goto step3,if the condition
is false then goto step4.Repeat this step until the i value is less than or equal to n.
Step3:Print i and increse the i value by 1
step4:increase the i value by 1
5. write an algorithm and flowchart to find the sum of even and odd numbers between 1 to 100
Algorithm
Step1:Read num
Step2:odd=0,even=0,i=1
Step3:Repeat step three until i<=num
if(i%2)=0 then add i value to even sum and increase the i value by 1
else add i value to odd sum and increase the i value by 1
Step4:Print even,odd
Program
#include <stdio.h>
void main()
{
int i, num, odd_sum = 0, even_sum = 0;
printf("Enter the value of num\n");
scanf("%d", &num);
for (i = 1; i <= num; i++)
{
if (i % 2 == 0)
even_sum = even_sum + i;
else
odd_sum = odd_sum + i;
}
printf("Sum of all odd numbers = %d\n", odd_sum);
printf("Sum of all even numbers = %d\n", even_sum);
}
6. write an algorith and flowchart to find the prime numbers between two numbers
Program
#include <stdio.h>
int main()
{
int low, high, i, flag;
printf("Enter two numbers(intervals): ");
scanf("%d %d", &low, &high);
if (flag == 0)
printf("%d ", low);
++low;
}
return 0;
}
7. write an algorithm and flowchart to interchange two numbers without using third number
Algorithm
Step1:Start
Step2: Input a,b
Step3: Calculate a=a+b,b=a-b,a=a-b
ster4: print a,b
step5:End
Flowchart:
8.write an algorithm and flowchart to find the given number is palindrome or not(121,212,313 etc..
are the palindrome numbers)
step1:Read n
Step2:new=0, a=n
Step3: Repeat Step 3 until n>0
r=n%10
new=new*10+r
n=n/10
step 4 : if(a==new)
print 'it is a palindrome'
else
print 'it is not a palindrome'
Program
#include <stdio.h>
int main()
{
int n, reversedInteger = 0, remainder, originalInteger;
originalInteger = n;
return 0;
}
9.Write an algorithm and flowchat to find the largest number of 3 numbers
Algorithm
Step 1: Start
Step 2: Declare variables a,b and c.
Step 3: Read variables a,b and c.
Step 4: If a>b
If a>c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b>c
Display b is the largest number.
Else
Display c is the greatest number.
Step 5: Stop
Flowchart
step 5. fact=fact*i
step 6. i=i+1
step 7. Print fact
step 8. Stop
Flowchart
11.Write an algorithm and flowchart to convert fahrenheit temperature into celsius
Algorithm
1. Start
2. Input Temperature in Fahrenheit in F variable.
3. Calculate Centigrade C = (F-32) x 5 / 9
4. Show temperature in centigrade
5. Stop
Flowchart
12. Write an algorithm and flowchar to generate first 50 numbers in fibonacci sequence.The
fibonacci series is 0,1,1,2,3,5,8.....
Algorithm:
Step 1: Start
Step 2:Declare variables i, n,a,b , show
Step 3:Initialize the variables, a=0, b=1, and show =0
Step4:Enter the number of terms of Fibonacci series to be printed
Step5:Print First two terms of series
Step6:Repeat step 6 until i<=n
-> show=a+b
-> a=b
-> b=show
-> increase value of i each time by 1
-> print the value of show
Step7:End
Flowchart:
Program
#include <stdio.h>
int main()
{
int i, n, t1 = 0, t2 = 1, nextTerm;
1. C is a General Purpose Programming Language This means C can be used to write a variety of
applications. It is often referred to as a “system programming language.”
2. C is a structured programming language, which means as a programmer, you are required to
divide a problem into a several different modules or functions.
3. C is renowned for its simplicity and is easy to use because of its structured approach. It has a vast
collection of keywords, operators, built-in functions and data types which make it efficient and
powerful.
4. C is portable, which means a C program runs in different environments. C compilers are
available for all operating systems and hardware platforms. Additionally, you can easily write
code on one system and port it to another.
5. C is modular, which means C programs can be divided into small modules, which are much
easier to understand.
6. C is easily available. The C software is easy to access and can be easily installed on your
computer. The installation of C hardly takes a few minutes.
7. C is easy to debug. The C compiler detects syntax errors quickly and easily and displays the
errors along with the line numbers of the code and the error message.
Applications of C:-
Because of its portability and efficiency, C is used to develop the system as well as application software.
Some of the system and application software listed below are:
1. Operating Systems(System software)
2. Interpreters and Compilers(System software)
3. Editors(System software)
4. DBMS(Application software)
5. Spread sheets(Application software)
6. Graphics packages(Application software)
7. Word Processors(Application software)
C Tokens:-
The basic and the smallest units of a C program are called C tokens.
1. Keywords
1 Developed by: Thilak Reddy
2. Identifiers
3. Constants
4. Strings
5. Operators
Keywords and Identifiers:-
Every word in a C program is either a keyword or identifier. All keywords are basically the sequences of
characters that have one or more fixed meanings and these meanings in any circumstances can’t be
changed. All C keywords must be written in lower letters.
Keywords supported by ANSI(American National Standards institute) C are:
auto break case char const continue default do double else enum
extern float for goto if int long register return short signed
sizeof static struct switch typedef union unsigned
viod volatile while
Identifiers:-
Identifiers are the names given to the program elements such as variables, arrays and functions.
Basically, identifiers are the sequences of alphabets and digits. The rules that govern the formation of
identifier names are:
1. The first character must be an alphabet or an underscore.
2. All succeeding characters must be either letters or digits
3. Uppercase and lowercase identifiers are different
4. No special character or punctuation symbols are allowed except the underscore.
5. No two successive underscores are allowed.
6. Keywords should not be used as identifiers.
Constants
The quantity which does not change during the execution of a program is known as constant. There are
two types of constants.
C constants
Numeric constants
Non-numeric Constants
Double:-
Double is a keyword used to indicate a double precision floating point number. The precision
associated with the accuracy of the data. It is used to whenever more accuracy is required in representing
the floating point numbers. A double is normal float value, but the number of significant digits that are
stored after the decimal point is double that of the float.
The float usually stores a maximum of 6 digits after the decimal point but double stores 16 significant
digits after the decimal point.
Modifiers in C language:
The amount of memory space to be allocated for a variable is derived by modifiers.
Modifiers are prefixed with basic data types to modify (either increase or decrease) the amount
of storage space allocated to a variable.
There are 4 modifiers available in C language. They are,
1. short
2. long
3. signed
4. unsigned
1. Short
In general int data type occupies different memory spaces for a different operating system; to
allocate fixed memory space short keyword can be used. short int occupies 2 bytes of memory
space in every operating system.
2. Long
Type conversion
It is used to modify a variable from one date type to another data type. New data type should be
mentioned before the variable name or value in brackets which to be typecast.
Example
6 Developed by: Thilak Reddy
#include<stdio.h>
int main()
{
double x = 1.2;
// Explicit conversion from double to int
int sum = (int)x + 1;
printf("sum = %d", sum);
}
Format Specifiers in C
In C programming we need lots of format specifier to work with various data types. Format specifiers
defines the type of data to be printed on standard output. Whether to print formatted output or to take
formatted input we need format specifiers. Format specifiers are also called as format string.
Formatted Input:
C provides a function called scanf() to read the numeric,character,and string type of data. It is included
in the header file <stdio.h>.
scanf() syntax:
scanf(“control string”,address_list);
control string
It is a sequence of one or more character groups. Each character group is a combination of the % symbol
and one of the conversion character. control string specifies the type of the values which are to be
supplied to the variables.
8 Developed by: Thilak Reddy
address_list:
It specifies the address of memory locations where the values of input variables should be stores.
Integer Input:
%d character group is used to input integer data through the standard input device.
Example1:
scanf(“%d”,&number);
input for the above statement is 38 ,then 38 is stored in the memory location represented by number.
Example2:
scanf(“%3d”,&number);
this is the specific way for accepting data through the field specification. The field specification means
the number of columns reserved for the number to be input(or output).Above example reads 3 digit
number or less than 3 digit number (3 is the field,d is the type conversion character).data should not
exceed the field width. If the input data number is 2345 and filed width is 3 only. Then 234 only stored
in the memory location remaining numbers will truncate.
Floating point input:
Floating -point numbers can be input using %f specification.
Example1: scanf(“%f %f”,&num1,&num2);
If the values to be supplied to num1,num2 are 356.90 and 669 respectively. Then, 356.90 and 669.0 are
stored respectively.
Example2: scanf(“%5f”,&num);
If the number to be entered is 2.34.This number contains only 4 characters including the decimal point.
But the specified field width is 5. so leading space replaced by a blank space. If the input is 23.456 then
23.45 is stored in the memory. Because number contains 6 characters.
Character input
In accepting a character constant, using scanf() function the character group %c is used.
Example1: scanf(“%c”,&symbol);
If the input character is A, then the value 65 is stored in the memory. Because the ASCII value of A=65.
Example2: scanf(“%10c”,name); or scanf(“%s”,name);
if the input is sequence of characters then you have to specify the number of characters present in the
name in the control string. Or you can use %s for character group. But in this case you have to declare
the variable as one dimensional array(char name[10]).
Mixed Mode Input:
preprocessor statements
global declarations
main()
{
declarations;
statements;
}
11 Developed by: Thilak Reddy
User defined functions
Preprocessor statements:-
These statements begin with # symbol and also called as preprocessor directives. These
statements direct the C preprocessor to include header files and also symbolic constants into a C
program.
Examples:-
#include<stdio.h> - For the standard input / output functions
#include “Test.h” - for the inclusion of header file Test.
#define NULL 0 - for defining symbolic constant, NULL=0
Global declarations:-
Variables or functions whose existence is known in the main() function and other user defined
functions, are called the global variables or functions and their declarations are called global
declarations.
This declarations should be made before main().
Braces:-
Every C program uses a pair of curly braces ({, }). The left brace indicates the beginning of the
main() function. The right brace indicates the end of the main() function. The braces can also be used to
indicate the beginning and end of use-defined functions.
Declarations:-
The declaration is a part of the C program where all the variables, arrays, functions etc.. used in
the C program are declared and may be initialized with their basic data types.
Statements:-
These are instructions to the computer to perform some specific operations. They may be I/O
statements, arithmetic statements, control statements and other statements. They also include comments.
The comments are explanatory notes on some instructions. The comment statements are not compiled
and executed.
Example:
#include<stdio.h>
void main()
{
printf("hello computer\n");
}
Exercise
1. write a c program to display your name, address and city in different lines
2. write a c program to exchange the values of two variables
3. Write a c program to accept 3 numbers and compute their sum and average
4. Write a c program to accept the temperature in Fahrenheit and convert into celsius
5. Write a c program to accept the principle amount, rate of interest and number of year and compute the
simple interest
6. write a c program to find the value of y in the following equation y=x2+3x+1
Operators in C programming:-
1. Arithmetic Operators
2. Increment and Decrement Operators
3. Assignment Operators
4. Relational Operators
5. Logical Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators
a. Shift Operators
b. Comma Operator
c. Sizeof Operator
d. Ternary Operator
1. Arithmetic Operators:-
An arithmetic operator performs mathematical operations such as addition,
subtraction and multiplication on numerical values (constants and variables).
* multiplication
/ division
#include <stdio.h>
int main()
1|P a g e C Operators Developed by :Thilak Reddy
{
int a = 9,b = 4, c;
c = a+b;
c = a-b;
c = a*b;
c=a/b;
c=a%b;
return 0;
Output:-
a+b = 13
a-b = 5
a*b = 36
a/b = 2
#include <stdio.h>
int main()
return 0;
Output
++a = 11
--b = 99
++c = 11.500000
++d = 99.500000
Here, the operators ++ and -- are used as prefix. These two operators can
also be used as postfix like a++ and a--.
#include <stdio.h>
int main()
int var=5;
printf("%d\n",var++);
printf("%d",++var);
return 0;
}
Output
5
7
3. C Assignment Operators:-
= a=b a=b
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b
#include <stdio.h>
int main()
int a = 5, c;
c += a; // c = c+a
c -= a; // c = c-a
c *= a; // c = c*a
c /= a; // c = c/a
c %= a; // c = c%a
return 0;
Output
c=5
c = 10
c=5
c = 25
c=5
c=0
4. C Relational Operators:-
A relational operator checks the relationship between two operands. If the relation is
true, it returns 1; if the relation is false, it returns value 0.
== Equal to 5 == 3 returns 0
#include <stdio.h>
int main()
int a = 5, b = 5, c = 10;
return 0;
Output
5 == 5 = 1
5 == 10 = 0
5>5=0
5 > 10 = 0
5<5=0
5 != 5 = 0
5 != 10 = 1
5 >= 5 = 1
5 >= 10 = 0
5 <= 5 = 1
5 <= 10 = 1
5. C Logical Operators:-
#include <stdio.h>
int main()
return 0;
Output
(a = b) || (c < b) equals to 1
(a != b) || (c < b) equals to 0
!(a != b) equals to 1
!(a == b) equals to 0
6. Bitwise Operators
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
The output of bitwise AND is 1 if the corresponding bits of all operands is 1. If either
bit of an operand is 0, the result of corresponding bit is evaluated to 0.
Let us suppose the bitwise AND operation of two integers 12 and 25.
00001100
& 00011001
________
#include <stdio.h>
int main()
return 0;
Output
Output = 8
9|P a g e C Operators Developed by :Thilak Reddy
Bitwise OR operator |
00001100
| 00011001
________
#include <stdio.h>
int main()
return 0;
Output
Output = 29
The result of bitwise XOR operator is 1 if the corresponding bits of two operands are
opposite. It is denoted by ^.
00001100
| 00011001
________
#include <stdio.h>
int main()
return 0;
Output
Output = 21
~ 00100011
________
For any integer n, bitwise complement of n will be -(n+1). To understand this, you
should have the knowledge of 2's complement.
2's Complement
For example:
#include <stdio.h>
int main()
printf("complement=%d\n",~35);
printf("complement=%d\n",~-12);
return 0;
Output
complement=-36
complement=11
Right shift operator shifts all bits towards right by certain number of specified bits. It
is denoted by >>.
212>>8 = 00000000
Left shift operator shifts all bits towards left by certain number of specified bits. It is
denoted by <<.
#include <stdio.h>
int main()
int num=212, i;
printf("\n");
return 0;
Output:
Right Shift by 2: 53
Comma Operator
Comma operators are used to link related expressions together. For example:
The sizeof is an unary operator which returns the size of data (constant, variables,
array, structure etc).
#include <stdio.h>
int main()
int a, e[10];
float b;
double c;
char d;
return 0;
Output
#include <stdio.h>
int main(){
char February;
int days;
printf("If this year is leap year, enter 1. If not enter any integer: ");
scanf("%c",&February);
return 0;
Output
do...while loop
The do..while loop is similar to the while loop with one important difference. The body
of do...while loop is executed once, before checking the test expression. Hence, the do...while
loop is executed at least once.
do...while loop Syntax
do
{
// codes
}
while (testExpression);
The code block (loop body) inside the braces is executed once. Then, the test expression is
evaluated. If the test expression is true, the loop body is executed again. This process goes
on until the test expression is evaluated to 0 (false).
When the test expression is false (nonzero), the do...while loop is terminated.
# include <stdio.h>
int main()
{
int i;
double number, sum = 0.0;
Continue Statement
The continue statement skips some statements inside the loop. The continue statement is used
with decision making statement such as if...else.
# include <stdio.h>
void main()
{
int i;
double number, sum = 0.0;
for(i=1; i <= 10; ++i)
{
printf("Enter a n%d: ",i);
scanf("%lf",&number);
Output
Enter a n1: 1.1
Enter a n2: 2.2
Enter a n3: 5.5
Enter a n4: 4.4
Enter a n5: -3.4
Enter a n6: -45.5
Enter a n7: 34.5
Enter a n8: -4.2
Enter a n9: -1000
Enter a n10: 12
Sum = 59.70
In the program, when the user enters positive number, the sum is calculated using sum +=
number; statement.
When the user enters negative number, the continue statement is executed and skips the
negative number from calculation.
Example:-
#include<stdio.h>
#include<conio.h>
void main()
{
int number=0;
clrscr();
printf("enter a number:");
scanf("%d",&number);
if(number%2==0){
printf("%d is even number",number);
}
getch();
}
Output
enter a number:4
1|Page Developed by: Thilak Reddy
4 is even number
If-else Statement
The if-else statement in C language is used to execute the code if condition is true or
false. The syntax of if-else statement is given below:
if(expression){
//code to be executed if condition is true
}
else{
//code to be executed if condition is false
}
Flowchart of if-else statement in C
Let's see the simple example of even and odd number using if-else statement in C language.
Example:-
#include<stdio.h>
#include<conio.h>
void main(){
int number=0;
clrscr();
printf("enter a number:");
scanf("%d",&number);
if(number%2==0){
printf("%d is even number",number);
}
else{
printf("%d is odd number",number);
}
getch();
}
2|Page Developed by: Thilak Reddy
Output
Enter a number: 4
4 is even number
Enter a number: 5
5 is odd number
If else-if ladder Statement
The if else-if statement is used to execute one code from multiple conditions. The syntax of
if else-if statement is given below:
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
}
Flowchart of else-if ladder statement in C
C Switch Statement
The switch statement in C language is used to execute the code from multiple
conditions. It is like if else-if ladder statement.
The syntax of switch statement in c language is given below:
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;
}
Rules for switch statement in C language
The switch expression must be of integer or character type.
The case value must be integer or character constant.
The case value can be used only inside the switch statement.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int number=0;
clrscr();
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;
5|Page Developed by: Thilak Reddy
case 100:
printf("number is equal to 100");
break;
default:
printf("number is not equal to 10, 50 or 100");
}
getch();
}
Output
enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
Output
enter a number:10
enter a number:50
number is equal to 50
number is equals to 100
number is not equal to 10, 50 or 100
Goto statement:
The goto statement is used to alter the normal sequence of a C program.
Syntax:
Goto label;
…. ….. ……..
………………
Label;
Statement;
The label is an identifier. When goto statement is encountered, control of the program
jumps to label: and starts executing the code.
Goto label;
…. ….. ……..
………………
Label;
…. ….. ……..
………………
Example:
// Program to calculate the sum and average of maximum of 5 numbers
// If user enters negative number, the sum and average of previously entered // positive
number is displayed
# include <stdio.h>
int main()
{
const int maxInput = 5;
int i;
double number, average, sum=0.0;
for(i=1; i<=maxInput; ++i)
{
printf("%d. Enter a number: ", i);
scanf("%lf",&number);
An array can be defined as ordered list of same type of data elements. These
elements may be data type int, float, char or double. All these elements are stored in
consecutive memory location.
An array is described by a single name or identifier. And each element in an array
is referenced by subscript (an index) enclosed in a pair of square brackets. This
subscript indicates the position of an individual data item in an array. The index must be
positive integer.
Classification of array
Array are classified into two types:
1. One dimensional arrays
2. Multi dimensional array
Declaration of an array
An array must be declared before it appears in a c program. This is done using an
appropriate data type. At the same time the size of an array must be specified .This allow
the compiler to decide on how much memory has to be reserved for the given array.
Syntax of an array
data_type arrayname[size];
data type : any basic data type or a user defined data type
size: number of elements of type data_type. And the size must be an integer constant
specified within a pair of square brackets.
Example:-
#include <stdio.h>
void main()
{
int number[10];
printf("The total size of array is : %d\n",sizeof(number));
}
The total size of a one-dimensional array of 10 integers is 40 bytes. Because the size of
an integer data is 4 bytes.
static constant variable that allows you to define a constant value inside a class
body.
Example
#include<stdio.h>
void main()
{
int age[5]={2,4,34,3,4};
printf("age %d",age[3]);
}
int age[5]={2,4,34,3,4};
int age[]={2,4,34,3,4};
In this case, the compiler determines the size of array by calculating the number of
elements of an array.
printf("%d\n",marks[i]);
#include <stdio.h>
int main(){
int i,n,sum=0;
printf("Enter number of students: ");
scanf("%d",&n);
int marks[n];
for(i=0;i<n;++i){
printf("Enter marks of student%d: ",i+1);
scanf("%d",&marks[i]);
sum+=marks[i];
}
printf("Sum= %d",sum);
return 0;
}
Output
#include <stdio.h>
int main(){
#include <stdio.h>
void main()
{
int i, j, a, n, number[30];
printf("Enter the value of N \n");
scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; ++i)
scanf("%d", &number[i]);
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (number[i] > number[j])
{
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
printf("The numbers arranged in ascending order are given below \n");
for (i = 0; i < n; ++i)
printf("%d\n", number[i]);
}
4. Write a C program to accept two integer arays and find the sum of the
corresponding elements of these two arrays.
#include<stdio.h>
void main()
{
int i , n;
#include<stdio.h>
void main()
{
int i , even , odd , n;
printf("Enter the size of Array\n");
scanf("%d" , &n);
int num[n];
even = 0;
odd = 0;
printf(" Enter Array elements\n");
for(i=0 ; i<n ; i++)
{
scanf("%d" , &num[i]);
}
2. Multidimensional Arrays:-
This multi dimensional arrays are classified into two dimensional, three dimensional
and so on n-dimensional array. The dimensionality of an array is determined by the
number of subscript present in the given array. If there is one subscript, then it is called a
one dimensional array. If there are two subscript, it is called a two-dimensional array and
so on. The dimensionality is determined by the number of pairs of square brackets placed
after the array name
Example
1. array1[] (one dimensional array)
2. array2[][] ( Two dimensional array)
3. array3[][][] (Three dimensional array)
Two dimensional array
Syntax
Example
int marks[5][3];
This first example specifies that the marks is two dimensional array of 5 rows and 3
columns. Row may represent students and the columns represent tests.
This indicates that for each row (Students number) element, the colums elements(tests)
are rapidly processed. This type of arrangement is known as row majoring or row major
order. And the column major order is one where for each column, the row elements are
rapidly processed.
Like initialization to a one dimensional array elements, the two dimensional array
elements can also be initialized at the time of declaration.
Syntax
Datatype arrayname[size1][size2]={e1,e2,e3,..en};
Example
Int matrix[3][3]={1,2,3,4,5,6,7,8,9};
If the number of elements to be assigned are less than the total number of elements that
a two dimensional array has contained, then all the remaining elements of an array are
assigned to zeros
1. The number of sets of initial value must be equal to the number of rows in the
arrayname.
2. One to one mapping is preserved. That is the first set of initial values is assigned to the
first row element and the second set of initial value is assigned to the second row
elements and so on
3.If the number of initial values in each initializing set is less than the number of the
corresponding row elements, then all the elements of that row are automatically assigned
to zeros.
4. If the number of initial value in each initializing set exceeds the number of the
corresponding row elements then there will be a compilation error.
#include <stdio.h>
int main(){
float a[2][2], b[2][2], c[2][2];
int i,j;
printf("Enter the elements of 1st matrix\n");
/* Reading two dimensional Array with the help of two for loop. If there was
an array of 'n' dimension, 'n' numbers of loops are needed for inserting data
to array.*/
for(i=0;i<2;++i)
for(j=0;j<2;++j){
printf("Enter a%d%d: ",i+1,j+1);
scanf("%f",&a[i][j]);
}
printf("Enter the elements of 2nd matrix\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j){
printf("Enter b%d%d: ",i+1,j+1);
scanf("%f",&b[i][j]);
}
for(i=0;i<2;++i)
for(j=0;j<2;++j){
/* Writing the elements of multidimensional array using loop. */
c[i][j]=a[i][j]+b[i][j]; /* Sum of corresponding elements of two arrays.
*/
}
printf("\nSum Of Matrix:");
for(i=0;i<2;++i)
for(j=0;j<2;++j){
printf("%.1f\t",c[i][j]);
if(j==1) /* To display matrix sum in order. */
printf("\n");
}
return 0;
}
Ouput
Sum Of Matrix:
2.2 0.5
-0.9 25.0
for(i=0;i<r;++i)
for(j=0;j<c;++j)
{
printf("Enter element a%d%d: ",i+1,j+1);
scanf("%d",&a[i][j]);
}
for(i=0;i<r;++i)
for(j=0;j<c;++j)
sum[i][j]=a[i][j]+b[i][j];
Output:
8 -11
17 6
5 5
/* If colum of first matrix in not equal to row of second matrix, asking user
to enter the size of matrix again. */
while (c1!=r2)
{
printf("Error! column of first matrix not equal to row of second.\n\n");
printf("Enter rows and column for first matrix: ");
scanf("%d%d", &r1, &c1);
printf("Enter rows and column for second matrix: ");
scanf("%d%d",&r2, &c2);
}
Output
Output Matrix:
24 29
6 25
Sorting techniques
1. Selection sort
2. Bubble sort
3. Insertion sort
If there are n elements to be sorted then, the process mentioned above should be
repeated n-1times to get required result. But, for better performance, in second step,
comparison starts from second element because after first step, the required number is
automatically placed at the first (i.e, In case of sorting in ascending order, smallest
element will be at first and in case of sorting in descending order, largest element will be
at first.). Similarly, in third step, comparison starts from third element and so on.
#include <stdio.h>
int main()
{
int i,n,j,temp;
printf("Enter the number of elements to be sorted: ");
scanf("%d",&n);
int data[n];
for(i=0;i<n;++i)
{
printf("%d. Enter element: ",i+1);
scanf("%d",&data[i]);
}
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
{
if(data[i]>data[j])
/* To sort in descending order, change > to <. */
{
temp=data[i];
data[i]=data[j];
data[j]=temp;
}
}
printf("In ascending order: ");
for(i=0;i<n;++i)
printf("%d ",data[i]);
return 0;
}
Output
Selection sort algorithm is easy to use but, there are other sorting algorithm which
perform better than selection sort. Specially, selection sort shouldn't be used to sort
large number of elements if the performance matters in that program.
Bubble sort algorithm starts by comparing the first two elements of an array and
swapping if necessary, i.e., if you want to sort the elements of array in ascending order
and if the first element is greater than second then, you need to swap the elements but,
if the first element is smaller than second, you mustn't swap the element. Then, again
second and third elements are compared and swapped if it is necessary and this process
go on until last and second last element is compared and swapped. This completes the
first step of bubble sort.
If there are n elements to be sorted then, the process mentioned above should be
repeated n-1times to get required result.
Output
Insertion Sort:-
Insertion sort is a simple sorting algorithm that builds the final sorted array (or list)
one item at a time. It is much less efficient on large lists than more advanced algorithms
such as quicksort, heapsort, or merge sort. However, insertion sort provides several
advantages:
1. Step 1: The second element of an array is compared with the elements that appears
before it (only first element in this case). If the second element is smaller than first
element, second element is inserted in the position of first element. After first step, first
two elements of an array will be sorted.
2. Step 2: The third element of an array is compared with the elements that appears
before it (first and second element). If third element is smaller than first element, it is
inserted in the position of first element. If third element is larger than first element but,
smaller than second element, it is inserted in the position of second element. If third
element is larger than both the elements, it is kept in the position as it is. After second
step, first three elements of an array will be sorted.
3. Step 3: Similary, the fourth element of an array is compared with the elements that
appears before it (first, second and third element) and the same procedure is applied and
that element is inserted in the proper position. After third step, first four elements of an
array will be sorted.
If there are n elements to be sorted. Then, this procedure is repeated n-1 times to get
sorted list of array.
Searching in C
Linear Search:-
In Linear Search the list is searched sequentially and the position is returned if the
key element to be searched is available in the list, otherwise -1 is returned. The search in
Linear Search starts at the beginning of an array and move to the end, testing for a
match at each item.
All the elements preceding the search element are traversed before the search
element is traversed. i.e. if the element to be searched is in position 10, all elements
form 1-9 are checked before 10.
Algorithm : Linear search implementation
Linear Search ( Array A, Value x)
Step 1: Set i to 1
Binary Search:-
Binary search is a fast search algorithm with run-time complexity of Ο(log n). This
search algorithm works on the principle of divide and conquer. For this algorithm to work
properly the data collection should be in sorted form.
Binary search search a particular item by comparing the middle most item of the
collection. If match occurs then index of item is returned. If middle item is greater than
item then item is searched in sub-array to the right of the middle item otherwise item is
search in sub-array to the left of the middle item. This process continues on sub-array as
well until the size of sub array reduces to zero.
First, we shall determine the half of the array by using this formula −
Now we compare the value stored at location 4, with the value being searched i.e. 31.
We find that value at location 4 is 27, which is not a match. Because value is greater
than 27 and we have a sorted array so we also know that target value must be in upper
portion of the array.
We change our low to mid + 1 and find the new mid value again.
low = mid + 1
mid = low + (high - low) / 2
Our new mid is 7 now. We compare the value stored at location 7 with our target value
31.
The value stored at location 7 is not a match, rather it is less that what we are looking
for. So the value must be in lower part from this location.
We compare the value stored ad location 5 with our target value. We find that it is a
match.
Binary search halves the searchable items and thus reduces the count of comparisons to
be made to very less numbers.
first = 0;
last = n - 1;
middle = (first+last)/2;
return 0;
}
Function Definition
A function is a block of code that performs a specific task. Suppose you are
defining a function which computes the square of a given number. Then we have to
write a set of instructions to do this job.
User-defined functions
As mentioned earlier, C language allows programmer to define functions. Such
functions created by the user are called user-defined functions.
Depending upon the complexity and requirement of the program, you can create as
many user-defined functions as you want.
Calculating Factorial
#include<stdio.h>
void main()
{
int n, f;
int fact(int x); /* Function Prototype declaration */
int fact(int x)
{
int i,r=1;
for(i=1;i<=x;i++)
r=r*i;
return(r); // return statement
Function prototype
A function prototype is simply the declaration of a function that specifies function's
name, parameters and return type. It doesn't contain function body.
A function prototype gives information to the compiler that the function may later be
used in the program.
In the above example, int addNumbers(int a, int b); is the function prototype which
provides following information to the compiler:
2|Page
Calling a function
Control of the program is transferred to the user-defined function by calling it.
In the above example, function call is made using fact(n);statement from inside the
main().
Function definition
Function definition contains the block of code to perform a specific task.
When a function is called, the control of the program is transferred to the function
definition. And, the compiler starts executing the codes inside the body of a function.
Arguments and parameters are the variable used in a program and a function. Variable
used in the function cal are called arguments. These are written within the
parentheses followed by the name of the function. Variables used in the function
definition are called parameters.
In programming, argument refers to the variable passed to the function. In the above
example, one variable n is passed during function call.
The parameter x accepts the passed arguments in the function definition. These
argument is called formal parameters of the function.
The type of arguments passed to a function and the formal parameters must match,
otherwise the compiler throws error.
If n is of char type, x also should be of char type. If n is of float type, variable b also
should be of float type.
Return statement
The return statement terminates the execution of a function and returns a value to the
calling function. The program control is transferred to the calling function after return
statement.
In the above example, the value of variable r is returned to the variable f in the
main() function.
3|Page
Function with no arguments and a return value
fact();/* No arguments */
}
int fact()
{
int i,r=1,x;
printf("Enter a number");
scanf("%d",&x);
for(i=1;i<=x;i++)
{
r=r*i;
}
printf("Factorial of a given number is %d",r); // No return statement
}
The empty parentheses in fact(); statement inside the main() function indicates that
no argument is passed to the function
The return type of the function is void. Hence, no value is returned from the function.
The fact() function takes input from the user, Calculating the factorial of a given
number and displays it on the screen.
Example #2: No arguments passed but a return value
#include<stdio.h>
main()
{
int f;
f=fact();/* No arguments */
printf("Factorial of a given number is %d",f);
4|Page
}
int fact()
{
int i,r=1,x;
printf("Enter a number");
scanf("%d",&x);
for(i=1;i<=x;i++)
{
r=r*i;
}
return(r); // return statement
}
The empty parentheses in f = fact(); statement indicates that no argument is passed
to the function. And, the value returned from the function is assigned to f.
Example #3: Argument passed but no return value
#include<stdio.h>
main()
{
int f,n;
printf("Enter a number");
scanf("%d",&n);
f=fact(n);//Passing arguments
}
fact(int x)
{
int i,r=1;
for(i=1;i<=x;i++)
{
r=r*i;
}
printf("Factorial of a given number is %d",r)//No retrun statemet;
+
+++}
5|Page
The integer value entered by the user is passed to fact() function.
Here, the fact() function calculate the factorial of a given number and displays the
appropriate message.
int fact(int x)
{
int i,r=1;
for(i=1;i<=x;i++)
r=r*i;
return(r); // return statement
6|Page
The input from the user is passed to fact() function.
The fact() function calculate the factorial of a given number.The return value is
assigned to variable f.
In the above programs arguments are passed to the functions and their values are
copied in the corresponding function. This is sort of information interchange between a
calling function and a called function. This process of transmitting the values from one
function to other is known as parameter passing. There are two methods of
parameters passing.
1. Call by value
2. Call by reference
1. Call by value
When the values of the arguments are passed from a calling function to a called
function, the values are copied into the called function. If any changes are made to the
values in the called function, there will not be any change in the original values within
the calling function.
Example
#include<stdio.h>
void interchange(int number1,int number2)
{
int temp;
temp = number1;
number1 = number2;
number2 = temp;
}
int main() {
int num1=50,num2=70;
interchange(num1,num2);
printf("\nNumber 1 : %d",num1);
7|Page
printf("\nNumber 2 : %d",num2);
return(0);
}
Output :
Number 1 : 50
Number 2 : 70
Explanation
1. While Passing Parameters using call by value , xerox copy of original parameter is
created and passed to the called function.
2. Any update made inside method will not affect the original value of variable in calling
function.
3. In the above example num1 and num2 are the original values and xerox copy of these values
is passed to the function and these values are copied into number1,number2 variable of sum
function respectively.
4. As their scope is limited to only function so they cannot alter the values inside main
function.
8|Page
2. Call by reference
In this method, the actual values are not passed, instead their addresses are passed to
a calling function. Here, no values are copied as the memory locations themselves are
referenced. If any modification is made to the values in the called function, then the
original values will get changed within the calling function.
Example
#include<stdio.h>
int temp;
temp = *num1;
*num1 = *num2;
*num2 = temp;
int main() {
int num1=50,num2=70;
interchange(&num1,&num2);
printf("\nNumber 1 : %d",num1);
printf("\nNumber 2 : %d",num2);
return(0);
Output :
Number 1 : 70
Number 2 : 50
Explanation
1. While passing parameter using call by address scheme , we are passing the actual address
of the variable to the called function.
2. Any updates made inside the called function will modify the original copy since we are
directly modifying the content of the exact memory location.
9|Page
C Standard Library Functions
C Standard library functions or simply C Library functions are inbuilt functions in C
programming. Function prototype and data definitions of these functions are written in
their respective header file. For example: If you want to use printf() function, the
header file <stdio.h> should be included.
#include <stdio.h>
int main()
{
/* If you write printf() statement without including header file, this program will show
error. */
printf("Catch me if you can.");
}
There is at least one function in any C program, i.e., the main() function (which is also
a library function). This program is called at program starts.
There are many library functions available in C programming to help the programmer
to write a good efficient program.
Suppose, you want to find the square root of a number. You can write your own piece
of code to find square root but, this process is time consuming and the code you have
written may not be the most efficient process to find square root. But, in C
programming you can find the square root by just using sqrt() function which is
defined under header file "math.h"
#include <stdio.h>
#include <math.h>
int main(){
float num,root;
printf("Enter a number to find square root.");
scanf("%f",&num);
root=sqrt(num); /* Computes the square root of num and stores in root. */
printf("Square root of %.2f=%.2f",num,root);
return 0;
}
List of Standard Library Functions Under Different Header Files in C
Programming
10 | P a g e
b. putchar()outputs a single character to the screen.
2 stdlib.h:Miscellaneous functions
11 | P a g e
a. malloc()provides dynamic memory allocation, covered in future sections
Scope Rules
A scope in any programming is a region of the program where a defined variable can
have its existence and beyond that variable it cannot be accessed. There are three
places where variables can be declared in C programming language −
Storage Classes
There are four storage classes in c. These storage classes are used to define the scope
and the life-time of the variable and/or functions.
12 | P a g e
int k;
k=a+10;
return(k);
//End of the function
}
Output
i=10
j=60
#include<stdio.h>
int num = 75 ;
void display();
void main()
{
//extern int num ;
printf("nNum : %d",num);
display();
}
void display()
{
//extern int num ;
printf("nNum : %d",num);
}
1. Declaration within the function indicates that the function uses external
variable
2. Functions belonging to same source code , does not require declaration
(no need to write extern)
3. If variable is defined outside the source code , then declaration using
13 | P a g e
extern keyword is required
Example 2:
#include<stdio.h>
void main()
int j;
printf ("i=%d",i);
j=value();
printf("j=%d",j);
int value()
int k;
return(k);
Output
i=10
j=20
Register Variable
1. register keyword is used to define local variable.
2. Local variable are stored in register instead of RAM.
3. As variable is stored in register, the Maximum size of variable = Maximum Size of
Register
4. unary operator [&] is not associated with it because Value is not stored in RAM instead it is
stored in Register.
14 | P a g e
5. This is generally used for faster access.
6. Common use is “Counter“
7. It is not applicable for arrays, structures or pointers.
Syntax
{
register int count;
}
Example
#include<stdio.h>
int main()
{
int num1,num2;
register int sum;
return(0);
}
Explanation of program
1. In the above program we have declared two variables num1,num2. These two variables are
stored in RAM.
2. Another variable is declared which is stored in register variable.Register variables are stored
in the register of the microprocessor.Thus memory access will be faster than other variables.
3. If we try to declare more register variables then it can treat variables as Auto storage
variables as memory of microprocessor is fixed and limited.
15 | P a g e
Static Variable
Static variables have a property of preserving their value even after they are out of their scope!
Hence, static variables preserve their previous value in their previous scope and are not initialized
again in the new scope .A static int variable remains in memory while the program is running. A
normal or auto variable is destroyed when a function call where the variable was declared is over.
Syntax:
static data_type var_name = var_value;
#include<stdio.h>
int fun()
{
int count = 0;
count++;
return count;
}
int main()
{
printf("%d ", fun());
printf("%d ", fun());
return 0;
//A normal or auto variable is destroyed when a function call where the variable was declared is
over.
}
Output
11
int main()
{
display();
display();
}
void display()
{
static int c = 0;
printf("%d ",c);
c += 5;
//A static int variable remains in memory while the program is running.
}
Output
0 5
During the first function call, the value of c is equal to 0. Then, it's value is
16 | P a g e
increased by 5.
During the second function call, variable c is not initialized to 0 again. It's
because c is a static variable. So, 5 is displayed on the screen.
Type Qualifiers
The keywords which are used to modify the properties of a variable are called type
qualifiers.There are two types of qualifiers available in C language. They are,
1. constant Keyword
2. volatile Keyword
1. CONST KEYWORD:
Constants are also like normal variables. But, only difference is, their values can’t be
modified by the program once they are defined.
They refer to fixed values. They are also called as literals.
They may be belonging to any of the data type.
Syntax:
const data_type variable_name; (or) const data_type *variable_name;
Please refer C – Constants topic in this tutorial for more details on const keyword.
2. VOLATILE KEYWORD:
When a variable is defined as volatile, the program may not change the value of the
variable explicitly.
But, these variable values might keep on changing without any explicit assignment by
the program. These types of qualifiers are called volatile.
For example, if global variable’s address is passed to clock routine of the operating
system to store the system time, the value in this address keep on changing without
any assignment by the program. These variables are named as volatile variable.
Syntax:
volatile data_type variable_name; (or) volatile data_type *variable_name;
C Programming Recursion
A function that calls itself is known as recursive function. And, this technique is known
as recursion. That is a function which perform a particular task is repeatedly calling
itself. There must be an exclusive stopping statement(terminating condition) in a
recursive function .Otherwise, the function will not be terminated. It enters into an
infinite loop.
Example
#include <stdio.h>
long int multiplyNumbers(int n);
int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
17 | P a g e
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
}
long int multiplyNumbers(int n)
{
if (n >= 1)
return n*multiplyNumbers(n-1);// multiplyNumbers function calls itself
else
return 1;
}
Recursion makes program elegant and cleaner. All algorithms can be defined
recursively which makes it easier to visualize and prove.
If the speed of the program is vital then, you should avoid using recursion. Recursions
use more memory and are generally slow.
C – Preprocessors
The C Preprocessor is not a part of the compiler, but is a separate step in the
compilation process. In simple terms, a C Preprocessor is just a text substitution tool
and it instructs the compiler to do required pre-processing before the actual
compilation. We'll refer to the C Preprocessor as CPP.
All preprocessor commands begin with a hash symbol (#). It must be the first
nonblank character, and for readability, a preprocessor directive should begin in the
first column. The following section lists down all the important preprocessor directives
−
Directive Description
Predefined Macros
ANSI C defines a number of macros. Although each one is available for use in
18 | P a g e
programming, the predefined macros should not be directly modified.
Example
#include <stdio.h>
main() {
Macro Description
__DATE__ The current date as a character literal in "MMM DD YYYY" format.
__TIME__ The current time as a character literal in "HH:MM:SS" format.
__FILE__ This contains the current filename as a string literal.
__LINE__ This contains the current line number as a decimal constant.
19 | P a g e
Strings
Definition
C Strings are nothing but array of characters ended with null character (‘\0’).
This null character indicates the end of the string.
Strings are always enclosed by double quotes. Whereas, character is enclosed by single
quotes in C.
Declaration of strings
Before we actually work with strings, we need to declare them first. Strings are declared in a similar
manner as arrays. Only difference is that, strings are of char type.
Example
char s[5];
Initialization of strings
In C, string can be initialized in a number of different ways. For convenience and ease, both
initialization and declaration are done in the same step.
Example
You can use the scanf() function to read a string like any other data types. But we don't use the
address of operator(&) while passing an array of character(strings) to a scanf() function because the
array name itself returns the starting address of the entire array.
However, the scanf() function only takes the first entered word. The function terminates when it
encounters a white space (or just space).
Example
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
Output
Enter name: Dennis Ritchie
Your name is Dennis.
Output
Enter name: RGUKT IIIT
Name: RGUKT IIIT
Note: This gets() function is dangerous because there is no way for the method to know how much
place has been allocated to that char * in ever situation. Instead of gets() function you can use
fgets() function, which allows you to limit the number of characters read, so the buffer does not
overflow.
Example
#include <stdio.h>
int main()
char name[5];
printf("Name: ");
return 0;
Strings are just char arrays. So, they can be passed to a function in a similar manner as arrays.
Example
#include <stdio.h>
int main()
{
char str[50];
gets(str);
return 0;
puts(str);
Example 1
#include<stdio.h>
#include<string.h>
int main() {
char str[100], temp;
int i, j = 0;
i = 0;
j = strlen(str) - 1;
while (i < j) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
i++;
j--;
}
#include <stdio.h>
#include <string.h>
void main()
int i, j = 0, k = 0, x, len;
scanf("%[^\n]s", str);
str1[k][j]='\0';
k++;
j=0;
else
str1[k][j]=str[i];
j++;
str1[k][j] = '\0';
len = strlen(str1[i]);
temp = str1[i][j];
str1[i][j] = str1[i][x];
str1[i][x] = temp;
Example3
int main()
{
char line[150];
int i, vowels, consonants, digits, spaces;
printf("Vowels: %d",vowels);
printf("\nConsonants: %d",consonants);
printf("\nDigits: %d",digits);
printf("\nWhite spaces: %d", spaces);
return 0;
}
Output
Enter a line of string: adfslkj34 34lkj343 34lk
Vowels: 1
Consonants: 11
Digits: 9
White spaces: 2
Example4
Remove Characters in String Except Alphabets
#include<stdio.h>
int main()
{
char line[150];
int i, j;
printf("Enter a string: ");
gets(line);
Output
Enter a string: [email protected]
Output String: googlegooglecom
Example 5
Find the Frequency of Characters
#include <stdio.h>
int main()
{
char str[1000], ch;
int i, frequency = 0;
printf("Enter a string: ");
gets(str);
printf("Enter a character to find the frequency: ");
scanf("%c",&ch);
for(i = 0; str[i] != '\0'; ++i)
{
if(ch == str[i])
++frequency;
}
return 0;
}
Output
Enter a string: This website is awesome.
Enter a character to find the frequency: e
Frequency of e = 4
C String functions:
String.h header file supports all the string functions in C language. All the string functions are given
below.
Strcat ( )
strcat( ) function in C language concatenates two given strings. It concatenates source string at the
end of destination string. Syntax for strcat( ) function is given below.
Example
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = " Hello RGUKT" ;
char target[ ]= " Students" ;
C – strncat()
strncat( ) function in C language concatenates (appends) portion of one string at the end of another
string.
Example
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = " Hello RGUKT" ;
char target[ ]= " Students" ;
Output
Example:
strcpy ( str1, str2) – It copies contents of str2 into str1.
strcpy ( str2, str1) – It copies contents of str1 into str2.
If destination string length is less than source string, entire source string value won’t be
copied into destination string.
For example, consider destination string length is 20 and source string length is 30. Then,
only 20 characters from source string will be copied into destination string and remaining 10
characters won’t be copied and will be truncated.
Example
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = "Hello students" ;
char target[]= "" ;
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;
strcpy ( target, source ) ;
printf ( "\ntarget string after strcpy( ) = %s", target ) ;
return 0;
}
Output
source string = Hello students
target string =
target string after strcpy( ) = Hello students
C – strncpy() function
strncpy( ) function copies portion of contents of one string into another string.
Example
#include <stdio.h>
#include <string.h>
int main( )
return 0;
Output
target string =
C – strlen() function
strlen( ) function in C gives the length of the given string.
strlen( ) function counts the number of characters in a given string and returns the integer
value.
It stops counting the character when null character is found. Because, null character
indicates the end of the string in C.
Example
#include <stdio.h>
#include <string.h>
int main( )
int len;
char array[20]="RGUKT" ;
len = strlen(array) ;
return 0;
Output
string length = 5
C – strchr() function
strchr( ) function returns pointer to the first occurrence of the character in a given string.
Example
#include <stdio.h>
#include <string.h>
int main ()
char *p;
p = strchr (string,'i');
return 0;
}
Output
Character i is found at position 3
First occurrence of character “i” in “This is a string for testing” is “is is a string for testing”
C – strrchr() function
strrchr( ) function in C returns pointer to the last occurrence of the character in a given string.
Example
#include <stdio.h>
#include <string.h>
int main ()
{
char string[55] ="This is a string for testing";
char *p;
p = strrchr (string,'i');
return 0;
}
Output
strstr( ) function returns pointer to the first occurrence of the string in a given string.
Example
#include <stdio.h>
#include <string.h>
int main ()
char *p;
p = strstr (string,"test");
if(p)
printf("string found\n" );
return 0;
Output
string found
First occurrence of string “test” in “This is a test string for testing” is “test string for testing”
C – strrstr() function
strrstr( ) function returns pointer to the last occurrence of the string in a given string.
Example
#include <stdio.h>
#include <string.h>
int main ()
{
char string[55] ="This is a test string for testing";
char *p;
p = strrstr (string,"test");
if(p)
printf("string found\n" );
return 0;
}
Output
string found
Last occurrence of string “test” in “This is a test string for testing” is “testing”
C – strlwr() function
strlwr( ) function converts a given string into lowercase.
Example
#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = "MODIFY This String To LOwer";
printf("%s\n",strlwr (str));
return 0;
}
Output
modify this string to lower
C – strupr() function
Example
#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = "Modify This String To Upper";
printf("%s\n",strupr(str));
return 0;
}
Output:
Example
#include <stdio.h>
#include <string.h>
int main ()
char *p;
p = strtok (string,",:");
printf ("%s\n",p);
return 0;
Output
C – strset() function
Example
#include<stdio.h>
#include<string.h>
int main()
return 0;
Output
C – strnset() function
Example
#include<stdio.h>
#include<string.h>
int main()
return 0;
Output
Original string is : Test String
Test string after string set : #### String
C – strrev() function
Example
#include<stdio.h>
#include<string.h>
int main()
{
char name[30] = "Hello";
return 0;
}
Output
Introduction to Pointers
Pointers are variables that hold address of another variable of same data type. Pointers are
one of the most distinct and exciting features of C language. It provides power and flexibility to
the language.
Concept of Pointer
Whenever a variable is declared, system will allocate a location to that variable in the
memory, to hold value. This location will have its own address number.
Let us assume that system has allocated memory location 80F for a variable a.
Example:- int a = 10 ;
We can access the value 10 by either using the variable name a or the address 80F. Since the
memory addresses are simply numbers they can be assigned to some other variable. The variable
that holds memory address are called pointer variables. A pointer variable is therefore nothing
but a variable that contains an address, which is a location of another variable. Value of pointer
variable will be stored in another memory location.
Developed by: Thilak Reddy
Pointer variables
In C, there is a special variable that stores just the address of another variable. It is called
Pointer variable or, simply, a pointer.
Declaration of Pointer
Syntax:- data_type* pointer_variable_name;
Example:- int* p;
pc=&c;
printf("Address of pointer pc:%u\n",pc);
printf("Content of pointer pc:%d\n\n",*pc);
c=11;
printf("Address of pointer pc:%u\n",pc);
printf("Content of pointer pc:%d\n\n",*pc);
*pc=2;
printf("Address of c:%u\n",&c);
printf("Value of c:%d\n\n",c);
return 0;
}
Output
Address of c: 2686784
Value of c: 22
Address of c: 2686784
Value of c: 2
Pointers to Pointers
A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a
pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer
contains the address of the second pointer, which points to the location that contains the actual
value as shown below.
A variable that is a pointer to a pointer must be declared as such. This is done by placing
an additional asterisk in front of its name.
When a target value is indirectly pointed to by a pointer to a pointer, accessing that value
requires that the asterisk operator be applied twice
Example
#include <stdio.h>
int main () {
int var;
int *ptr;
int **pptr;
var = 3000;
/* take the address of var */
ptr = &var;
/* take the address of ptr using address of operator & */
pptr = &ptr;
/* take the value using pptr */
printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);
return 0;
}
Output
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000
Compatibility
The rules for assigning one pointer to another are tighter than the rules for numeric types.
For example, you can assign an int value to a double variable without using a type conversion,
but you can‟t do the same for pointers to these two types
Example
/*
* ptr_compatibility.c -- program illustrates concept of pointer
* compatibility
*/
#include <stdio.h>
int main(void)
{
int n = 5;
return 0;
}
Void Pointers
Suppose we have to declare integer pointer,character pointer and float pointer then we
need to declare 3 pointer variables.
Instead of declaring different types of pointer variable it is feasible to declare single
pointer variable which can act as integer pointer,character pointer.
Advantage of void pointers is this allows these functions to be used to allocate memory
of any data type.
Disadvantage of void pointers is void pointers cannot be dereferenced
Example
int main()
{
int a = 10;
void *ptr = &a; // void pointer holds address of int 'a'
printf("%d", *ptr);
return 0;
}
return 0;
}
Output
Address of charArr[0] = 28ff44
Address of charArr[1] = 28ff45
Address of charArr[2] = 28ff46
Address of charArr[3] = 28ff47
The name of the array always points to address of the first element of an array. In the above
example, arr and &arr[0] points to the address of the first element.
&arr[0] is equivalent to arr
Since, the addresses of both are the same, the values of arr and &arr[0] are also the same.
arr[0] is equivalent to *arr (value of an address of the pointer)
Similarly,
&arr[1] is equivalent to (arr + 1) AND, arr[1] is equivalent to *(arr + 1).
&arr[2] is equivalent to (arr + 2) AND, arr[2] is equivalent to *(arr + 2).
&arr[3] is equivalent to (arr + 1) AND, arr[3] is equivalent to *(arr + 3).
.
.
&arr[i] is equivalent to (arr + i) AND, arr[i] is equivalent to *(arr + i).
In C, you can declare an array and can use pointer to alter the data of an array.
Example
#include <stdio.h>
int main()
{
int i, classes[6],sum = 0;
printf("Enter 6 numbers:\n");
for(i = 0; i < 6; ++i)
{
// (classes + i) is equivalent to &classes[i]
scanf("%d",(classes + i));
Developed by: Thilak Reddy
// *(classes + i) is equivalent to classes[i]
sum += *(classes + i);
}
printf("Sum = %d", sum);
return 0;
}
Output
Enter 6 numbers:
2
3
4
5
3
4
Sum = 21
Constant Pointers
A constant pointer is a pointer that cannot change the address its holding. In other words,
we can say that once a constant pointer points to a variable then it cannot point to any other
variable.
Syntax:- <type of pointer> * const <name of pointer>
Example:- int * const ptr;
Example:-
#include<stdio.h>
int main(void)
{
int var1 = 0, var2 = 0;
int *const ptr = &var1;
ptr = &var2;
printf("%d\n", *ptr);
return 0;
}
In the above example :
We declared two variables var1 and var2
A constant pointer „ptr‟ was declared and made to point var1
Next, ptr is made to point var2.
Finally, we try to print the value ptr is pointing to.
So, in a nutshell, we assigned an address to a constant pointer and then tried to change the
address by assigning the address of some other variable to the same constant pointer.
Examples
1 : Printing Address of the Character Array
#include<stdio.h>
int main()
{
int i;
char *arr[4] = {"C","C++","Java","VBA"};
char *(*ptr)[4] = &arr;
for(i=0;i<4;i++)
printf("Address of String %d : %u\n",i+1,(*ptr)[i]);
return 0;
}
Output :
Address of String 1 = 178
Address of String 2 = 180
Address of String 3 = 184
Address of String 4 = 189
Output :
String 1 = C
String 2 = C++
Pointers to Functions
When a pointer is passed as an argument to a function, address of the memory location is
passed instead of the value. This is because, pointer stores the location of the memory, and not
the value.
Example
/* C Program to swap two numbers using pointers and function. */
#include <stdio.h>
void swap(int *n1, int *n2);
int main()
{
int num1 = 5, num2 = 10;
// address of num1 and num2 is passed to the swap function
swap( &num1, &num2);
printf("Number1 = %d\n", num1);
printf("Number2 = %d", num2);
return 0;
}
void swap(int * n1, int * n2)
{
// pointer n1 and n2 points to the address of num1 and num2 respectively
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
Output
Number1 = 10
Number2 = 5
Pointer Arithmetic
A pointer in c is an address, which is a numeric value. Therefore, you can perform
arithmetic operations on a pointer just as you can on a numeric value. There are four arithmetic
operators that can be used on pointers: ++, --, +, and –
Incrementing a Pointer
We prefer using a pointer in our program instead of an array because the variable pointer
can be incremented, unlike the array name which cannot be incremented because it is a constant
pointer. The following program increments the variable pointer to access each succeeding
element of the array −
#include <stdio.h>
Decrementing a Pointer
The same considerations apply to decrementing a pointer, which decreases its value by
the number of bytes of its data type as shown below −
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr;
/* let us have array address in pointer */
ptr = &var[MAX-1];
for ( i = MAX; i > 0; i--) {
printf("Address of var[%d] = %x\n", i-1, ptr );
printf("Value of var[%d] = %d\n", i-1, *ptr );
/* move to the previous location */
ptr--;
}
return 0;
}
Output
Address of var[2] = bfedbcd8
C malloc()
The name malloc stands for "memory allocation".
The function malloc() reserves a block of memory of specified size and return a pointer of type
void which can be casted into pointer of any form.
Syntax of malloc()
ptr = (cast-type*) malloc(byte-size)
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of
memory with size of byte size. If the space is insufficient, allocation fails and returns NULL
pointer.
ptr = (int*) malloc(100 * sizeof(int));
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and
the pointer points to the address of first byte of memory.
C calloc()
The name calloc stands for "contiguous allocation".
The only difference between malloc() and calloc() is that, malloc() allocates single block of
memory whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes
to zero.
Syntax of calloc()
ptr = (cast-type*)calloc(n, element-size);
This statement will allocate contiguous space in memory for an array of n elements. For example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements each of size of
float, i.e, 4 bytes.
C free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on its
own. You must explicitly use free() to release the space.
Write a C program to find sum of n elements entered by user. To perform this program,
allocate memory dynamically using malloc() function.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
ptr = (int*) malloc(num * sizeof(int)); //memory allocated using malloc
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}
C realloc()
If the previously allocated memory is insufficient or more than required, you can change
the previously allocated memory size using realloc().
Syntax of realloc()
ptr = realloc(ptr, newsize);
Here, ptr is reallocated with size of newsize.
Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
Programming Applications
Pointer is used for different purposes. Pointer is low level construct in programming which is
used to perform high level task. Some of the pointer applications are listed below
A. Passing Parameter by Reference
First pointer application is to pass the variables to function using pass by reference scheme.
void interchange(int *num1,int *num2)
{
int temp;
temp = *num1;
*num1 = *num2;
*num2 = *num1;
}
Pointer can be used to simulate passing parameter by reference. Pointer is used to pass
parameter to function. In this scheme we are able to modify value at direct memory location.
Re-commanded Article : Ways of function calling
We can access array using pointer. We can store base address of array in pointer.
ptr = a;
Now we can access each and individual location using pointer.
for(i=0;i<5;i++) {
printf("%d",*(ptr+i));
}
consider above example where we have used malloc() function to allocate memory dynamically.
struct student {
char name[10];
int rollno;
};
Suppose we want to pass the above structure to the function then we can pass structure to the
function using pointer in order to save memory.
Suppose we pass actual structure then we need to allocate (10 + 4 = 14 Bytes(*)) of memory. If
we pass pointer then we will require 4 bytes(*) of memory.
E. Command-line Arguments.
main() function of a C program accepts arguments from command line or from other shell scripts
by following commands. They are,
Structure is commonly referred to as a user-defined data type. C‟s structures allow you to store
multiple variables of any type in one place (the structure). A structure can contain any of C‟s
data types, including arrays and other structures. Each variable within a structure is called a
member of the structure. They can hold any number of variables, and you can make arrays of
structures. This flexibility makes structures ideally useful for creating databases in C.
DECLARATION OF STRUCTURES
To declare a structure you must start with the keyword struct followed by the structure
name or structure tag and within the braces the list of the structure‟s member variables. Note
that the structure declaration does not actually create any variables. Syntax:-
struct structure-tag {
datatype variable1;
datatype variable2;
dataype variable 3;
...
};
Example:-
Consider the student database in which each student has a roll number, name and course and
the marks obtained. Hence to group this data with a structure-tag as student, we can have the
declaration of structure as:
struct student {
int roll_no;
char name[20];
char course[20];
int marks_obtained ;
};
struct student stud1, stud2 ;
The second method is as follows:
Struct student {
int roll_no;
char name[20];
char course[20];
int marks_obtained ;
} stud1, stud2 ;
ACCESSING THE MEMBERS OF A STRUCTURE
Individual structure members can be used like other variables of the same type.
Structure members are accessed using the structure member operator (.), also called the
dot operator, between the structure name and the member name.
Syntax:-
Developed by: Thilak Reddy
structurevariable. member-name;
Example:-
struct coordinate{
int x;
int y;
}first,second;
Thus, to have the structure named first refer to a screen location that has coordinates x=50,
y=100, you could write as,
first.x = 50;
first.y = 100;
To display the screen locations stored in the structure second, you could write,
printf ("%d,%d", second.x, second.y);
The individual members of the structure behave like ordinary date elements and can be
accessed accordingly.
Example:-
/*Program to store and retrieve the values from the student structure*/
#include<stdio.h>
struct student {
int roll_no;
char name[20];
char course[20];
int marks_obtained ;
};
main()
{
student s1 ;
printf (“Enter the student roll number:”);
scanf (“%d”,&s1.roll_no);
printf (“\nEnter the student name: “);
scanf (“%s”,s1.name);
printf (“\nEnter the student course”);
scanf (“%s”,s1.course);
printf (“Enter the student percentage\n”);
scanf (“%d”,&s1.marks_obtained);
printf (“\nData entry is complete”);
printf ( “\nThe data entered is as follows:\n”);
printf (“\nThe student roll no is %d”,s1.roll_no);
printf (“\nThe student name is %s”,s1.name);
printf (“\nThe student course is %s”,s1.course);
printf (“\nThe student percentage is %d”,s1.marks_obtained);
}
OUTPUT
Enter the student roll number: 1234
Developed by: Thilak Reddy
Enter the student name: ARUN
Enter the student course: MCA
Enter the student percentage: 84
Data entry is complete
The data entered is as follows:
The student roll no is 1234
The student name is ARUN
The student course is MCA
The student percentage is 84
INITIALIZING STRUCTURES
Like other C variable types, structures can be initialized when they‟re declared. This procedure is
similar to that for initializing arrays. The structure declaration is followed by an equal sign and a
list of initialization values is separated by commas and enclosed in braces. For example, look at
the following statements for initializing the values of the members of the mysale structure
variable.
Example 9.2
struct sale {
char customer[20];
char item[20];
float amt;
} mysale = { "XYZ Industries", “toolskit", 600.00 };
In a structure that contains structures as members, list the initialization values in order. They are
placed in the structure members in the order in which the members are listed in the structure
definition. Here‟s an example that expands on the previous one:
Example
struct customer {
char firm[20];
char contact[25];
}
struct sale {
struct customer buyer1;
char item [20];
float amt;
} mysale = { { "XYZ Industries", "Tyran Adams"}, "toolskit",600.00};
C is a structured programming language and the basic concept in it is the modularity of the
programs. This concept is supported by the functions in C language. This can be achieved in
primarily two ways: Firstly, to pass them as simple parameter values by passing the structure
name and secondly, through pointers.
Example
Write a program to demonstrate passing a structure to a function.
Structure is used to store the information of One particular object but if we need to store
such 100 objects then Array of Structure is used.
Let‟s consider the example of students and their marks. In this case, to avoid declaring
various data variables, we grouped together all the data concerning the student‟s marks as one
unit and call it student. The problem that arises now is that the data related to students is not
going to be of a single student only. We will be required to store data for a number of students.
To solve this situation one way is to declare a structure and then create sufficient number of
variables of that structure type. But it gets very burden to manage such a large number of data
variables, so a better option is to declare an array.
So, revising the array for a few moments we would refresh the fact that an array is simply a
collection of homogeneous data types. Hence, if we make a declaration as:
int temp[20];
It simply means that temp is an array of twenty elements where each element is of type integer,
indicating homogenous data type.
Example:-
struct student stud[20], we can access the roll_no of this array as
stud[0].roll_no;
stud[1].roll_no;
stud[2].roll_no;
stud[3].roll_no; …
…
…
stud[19].roll_no;
Example:-
Write a program to read and display data for 20 students.
/*Program to read and print the data for 20 students*/
#include <stdio.h>
struct student {
int roll_no;
char name[20];
char course[20];
int marks_obtained ;
};
main( )
{
struct student stud [20];
int i;
printf (“Enter the student data one by one\n”);
for(i=0; i<=19; i++)
{
printf (“Enter the roll number of %d student”,i+1);
scanf (“%d”,&stud[i].roll_no);
printf (“Enter the name of %d student”,i+1);
scanf (“%s”,stud[i].name);
printf (“Enter the course of %d student”,i+1);
scanf (“%d”,stud[i].course);
printf (“Enter the marks obtained of %d student”,i+1);
scanf (“%d”,&stud[i].marks_obtained);
}
printf (“the data entered is as follows\n”);
for (i=0;i<=19;i++)
{
Developed by: Thilak Reddy
printf (“The roll number of %d student is %d\n”,i+1,stud[i].roll_no);
printf (“The name of %d student is %s\n”,i+1,stud[i].name);
printf (“The course of %d student is %s\n”,i+1,stud[i].course);
printf (“The marks of %d student is %d\n”,i+1,stud[i].marks_obtained);
}
}
Example
/*Program to read and print data related to five students having marks of three subjects each
using the concept of arrays */
#include<stdio.h>
struct student {
int roll_no;
char name [20];
char course [20];
int subject [3] ;
};
main( )
{
struct student stud[5];
int i,j;
printf (“Enter the data for all the students:\n”);
for (i=0;i<=4;i++)
{
printf (“Enter the roll number of %d student”,i+1);
scanf (“%d”,&stud[i].roll_no);
printf(“Enter the name of %d student”,i+1);
scanf (“%s”,stud[i].name);
printf (“Enter the course of %d student”,i+1);
scanf (“%s”,stud[i].course);
for (j=0;j<=2;j++)
{
printf (“Enter the marks of the %d subject of the student
%d:\n”,j+1,i+1);
scanf (“%d”,&stud[i].subject[j]);
}
}
printf (“The data you have entered is as follows:\n”);
for (i=0;i<=4;i++)
{
printf (“The %d th student's roll number is %d\n”,i+1,stud[i].roll_no);
printf (“The %d the student's name is %s\n”,i+1,stud[i].name);
printf (“The %d the student's course is %s\n”,i+1,stud[i].course);
for (j=0;j<=2;j++)
{
Developed by: Thilak Reddy
printf (“The %d the student's marks of %d I subject are %d\n”,i+1, j+1,
stud[i].subject[j]);
}
}
printf (“End of the program\n”);
}
UNIONS
C Union is also like structure, i.e. collection of different data types which are grouped together.
Each element in a union is called member.
Union and structure in C are same in concepts, except allocating memory for their
members.
Structure allocates storage space for all its members separately.
Whereas, Union allocates one common storage space for all its members
We can access only one member of union at a time. We can‟t access all member values
at the same time in union. But, structure can access all member values at the same time.
This is because, Union allocates one common storage space for all its members.
Whereas Structure allocates storage space for all its members separately.
Many union variables can be created in a program and memory will be allocated for each
union variable separately.
Below table will help you how to form a C union, declare a union, initializing and
accessing the members of the union.
Syntax:-
union union-tag {
datatype variable1;
datatype variable2;
...
};
For example,
union temp{
int x;
char y;
float z;
};
In this case a float is the member which requires the largest space to store its value hence the
space required for float (8 bytes) is allocated to the union. All members share the same space.
Let us see how to access the members of the union.
Example
Write a program to illustrate the concept of union.
Let us see, how to initialize a Union with the help of the following example:
Example
union date_tag {
char complete_date [9];
struct part_date_tag {
char month[2];
char break_value1;
char day[2];
char break_value2;
char year[2];
} parrt_date;
}date = {“01/01/05”};
Individual union members can be used in the same way as the structure members, by using the
member operator or dot operator (.). However, there is an important difference in accessing the
union members. Only one union member should be accessed at a time. Because a union stores
its members on top of each other, it‟s important to access only one member at a time. Trying to
access the previously stored values will result in erroneous output.
Example:-
#include <stdio.h>
#include <string.h>
union student
{
char name[20];
Developed by: Thilak Reddy
char subject[20];
float percentage;
};
int main()
{
union student record1;
union student record2;
strcpy(record2.subject, "Physics");
printf(" Subject : %s \n", record2.subject);
record2.percentage = 99.50;
printf(" Percentage : %f \n", record2.percentage);
return 0;
}
File
Meaning of Mode During Inexistence of file
Mode
r Open for reading. If the file does not exist, fopen() returns NULL.
rb Open for reading in binary mode. If the file does not exist, fopen() returns NULL.
r+ Open for both reading and writing. If the file does not exist, fopen() returns NULL.
Open for both reading and writing in If the file exists, its contents are overwritten. If
wb+
binary mode. the file does not exist, it will be created.
File
Meaning of Mode During Inexistence of file
Mode
#include <stdio.h>
#include <stdlib.h> /* For exit() function */
int main()
{
char sentence[1000];
FILE *fptr;
fptr = fopen("program.txt", "w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter a sentence:\n");
gets(sentence);
fprintf(fptr,"%s", sentence);
fclose(fptr);
return 0;
}
Output
Enter sentence:
I am awesome and so are files.
After termination of this program, you can see a text file program.txt created in the same
location where this program is located.
If you open and see the content, you can see the sentence: I am awesome and so are files.
In this program, a file is opened using opening mode "w". In this mode, if the file exists, its
contents are overwritten and if the file does not exist, it will be created. Then, user is asked to
enter a sentence. This sentence will be stored in file program.txt using fprintf() function.
Example 6: Write a C program to read name and marks of n number of students from user
and store them in a file.
#include <stdio.h>
int main()
{
char name[50];
int marks, i, num;
printf("Enter number of students: ");
scanf("%d", &num);
FILE *fptr;
fptr = (fopen("C:\\student.txt", "w"));
if(fptr == NULL)
{
printf("Error!");
exit(1);
7|Page Developed By: THILAK REDDY
}
for(i = 0; i < num; ++i)
{
printf("For student%d\nEnter name: ", i+1);
scanf("%s", name);
printf("Enter marks: ");
scanf("%d", &marks);
fprintf(fptr,"\nName: %s \nMarks=%d \n", name, marks);
}
fclose(fptr);
return 0;
}
Example 7:- Write a C program to read name and marks of n number of students from
user and store them in a file. If the file previously exits, add the information of n
students.
#include <stdio.h>
int main()
{
char name[50];
int marks, i, num;
printf("Enter number of students: ");
scanf("%d", &num);
FILE *fptr;
fptr = (fopen("C:\\student.txt", "a"));
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
for(i = 0; i < num; ++i)
{
printf("For student%d\nEnter name: ", i+1);
scanf("%s", name);
1. What is C language?
C is a programming language developed at AT & T‟s Bell Laboratories of USA in 1972. The C
programming language is a standardized programming language developed in the early 1970s by
Ken Thompson and Dennis Ritchie for use on the UNIX operating system. It has since spread to
many other operating systems, and is one of the most widely used programming languages.
2. What is an algorithm?
An algorithm is a step-by-step method of performing any task.
3. What is a flow chart?
A flowchart is a type of diagram that represents an algorithm or process, showing the steps as
boxes of various kinds, and their order by connecting these with arrows.
4. What is a C Preprocessor?
C Preprocessor is a program that processes our source program before it is passed to the compiler.
5. What is the use of header files as used in C programming?
Header files are used to have declarations. It is simple to include a single header file than writing all
the needed functions prototypes.
6. What is the Structure of a C Program?
Documentation Section, Linking Section, Definition Section, Global declaration Section, main
function, subprogram section.
7. Explain some Header Files?