Professional Documents
Culture Documents
In the C programming language, data types refer to an extensive system used for
declaring variables or functions of different types. The type of a variable determines how
much space it occupies in storage and how the bit pattern stored is interpreted.
The types in C can be classified as follows:
S.N.
They are arithmetic types and consists of the two types: (a) integer types and (b)
floating-point types.
Enumerated types:
They are again arithmetic types and they are used to define variables that can only
be assigned certain discrete integer values throughout the program.
The type void:
3
The type specifier void indicates that no value is available.
Derived types:
4
They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types
and (e) Function types.
Link section : The link section provides instructions to the compiler to link functions
from the system library.
Definition section : The definition section defines all symbolic constants.
Global declaration section : There are some variables that are used in more than one
function. Such variables are called global variables and are declared in the global
declaration section that is outside of all the functions. This section also declares all the
user-defined functions.
main () function section : Every C program must have one main function section. This
section contains two parts; declaration part and executable part
Declaration part : The declaration part declares all the variables used in the executable
part.
Executable part : There is at least one statement in the executable part. These two parts
must appear between the opening and closing braces. The program execution begins at
the opening brace and ends at the closing brace. The closing brace of the main function is
the logical end of the program. All statements in the declaration and executable part end
with a semicolon.
Subprogram section : The subprogram section contains all the user-defined functions that
are called in the main () function. User-defined functions are generally placed
immediately after the main () function, although they may appear in any order.
All section, except the main () function section may be absent when they are not required.
Loop
There may be a situation, when you need to execute a block of code several number of
times. In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times
and following is the general form of a loop statement in most of the programming
languages:
Loop Type
while loop
Description
Repeats a statement or group of statements while a given
condition is true. It tests the condition before executing the
loop body.
for loop
do...while loop
nested loops
You can use one or more loop inside any another while, for or
do..while loop.
Description
break statement
continue statement
goto statement
Switch statement
A switch statement allows a variable to be tested for equality against a list of values.
Each value is called a case, and the variable being switched on is checked for each switch
case.
Syntax:
The syntax for a switch statement in C programming language is as follows:
switch(expression){
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
You can have any number of case statements within a switch. Each case is
followed by the value to be compared to and a colon.
The constant-expression for a case must be the same data type as the variable in
the switch, and it must be a constant or a literal.
When the variable being switched on is equal to a case, the statements following
that case will execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control
jumps to the next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow of control
will fall through to subsequent cases until a break is reached.
A switch statement can have an optional default case, which must appear at the
end of the switch. The default case can be used for performing a task when none of the
cases is true. No break is needed in the default case.
Flow Diagram:
Example:
#include <stdio.h>
int main ()
{
/* local variable definition */
char grade = 'B';
switch(grade)
{
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well done\n" );
break;
case 'D' :
printf("You passed\n" );
break;
case 'F' :
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
}
printf("Your grade is %c\n", grade );
return 0;
}
Nested loops in C
C programming language allows to use one loop inside another loop. Following section
shows few examples to illustrate the concept.
Syntax:
do
{
statement(s);
}while( condition );
}while( condition );
A final note on loop nesting is that you can put any type of loop inside of any other type
of loop. For example, a for loop can be inside a while loop or vice versa.
Example:
The following program uses a nested for loop to find the prime numbers from 2 to 100:
#include <stdio.h>
int main ()
{
/* local variable definition */
int i, j;
When the above code is compiled and executed, it produces the following result:
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
Arrays
C programming language provides a data structure called the array, which can store a
fixed-size sequential collection of elements of the same type. An array is used to store a
collection of data, but it is often more useful to think of an array as a collection of
variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99,
you declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
index of an array will be total size of the array minus 1. Following is the pictorial
representation of the same array we discussed above:
Array Presentation
Accessing Array Elements
An element is accessed by indexing the array name. This is done by placing the index of
the element within square brackets after the name of the array. For example:
double salary = balance[9];
The above statement will take 10th element from the array and assign the value to salary
variable. Following is an example which will use all the above mentioned three concepts
viz. declaration, assignment and accessing arrays:
#include <stdio.h>
int main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
/* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ )
{
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
/* output each array element's value */
for (j = 0; j < 10; j++ )
{
printf("Element[%d] = %d\n", j, n[j] );
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
call by value
call by reference
{
int t;
t = a; a = b; b = t;
}
OUTPUT
======
n1: 10, n2: 20
The swapByValue() does not affect the arguments n1 and n2 in the calling function it
only operates on a and b local to swapByValue() itself. This is a good example of how
local variables behave.
}
void swapByReference(int *a, int *b)
{
int t;
t = *a; *a = *b; *b = t;
}
OUTPUT
======
n1: 20, n2: 10
Recursion
Recursion is the process of repeating items in a self-similar way. Same applies in
programming languages as well where if a programming allows you to call a function
inside the same function that is called recursive call of the function as follows.
void recursion()
{
recursion(); /* function calls itself */
}
int main()
{
recursion();
}
The C programming language supports recursion, i.e., a function to call itself. But while
using recursion, programmers need to be careful to define an exit condition from the
function, otherwise it will go in infinite loop.
Recursive function are very useful to solve many mathematical problems like to calculate
factorial of a number, generating Fibonacci series, etc.
Number Factorial
Following is an example, which calculates factorial for a given number using a recursive
function:
#include <stdio.h>
int factorial(unsigned int i)
{
if(i <= 1)
{
return 1;
}
return i * factorial(i - 1);
}
int main()
{
int i = 15;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}
When the above code is compiled and executed, it produces the following result:
Factorial of 15 is 2004310016
Fibonacci Series
Following is another example, which generates Fibonacci series for a given number using
a recursive function:
#include <stdio.h>
int fibonaci(int i)
{
if(i == 0)
{
return 0;
}
if(i == 1)
{
return 1;
}
return fibonaci(i-1) + fibonaci(i-2);
}
int main()
{
int i;
for (i = 0; i < 10; i++)
{
printf("%d\t%n", fibonaci(i));
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
0
13
21
34
clrscr();
printf(" Enter the elements of A\n");
for(i=0 ; i<2 ; i++)
{
for(j=0 ; j<3 ; j++)
{
scanf("%d" , &A[i][j] );
}
}
printf(" Matrix is\n");
for(i=0 ; i<2 ; i++)
{
for(j=0 ; j<3 ; j++)
{
printf("%d\t" , A[i][j] );
}
printf("\n");
}
for(i=0 ; i<3 ; i++)
{
for(j=0 ; j<2 ; j++)
{
B[i][j] = A[j][i];
}
}
printf(" After Transpose\n");
for(i=0 ; i<3 ; i++)
{
for(j=0 ; j<2 ; j++)
{
printf("%d\t" , B[i][j] );
}
printf("\n");
}
getch();
}
fclose(fptr2);
return 0;
}
printf("%d\t",b[i][j]);
}
for(i=0;i<3;i++)
for(j=0;j<3;j++)
c[i][j]=a[i][j]+b[i][j];
printf("\nThe Addition of two matrix is\n");
for(i=0;i<3;i++){
printf("\n");
for(j=0;j<3;j++)
printf("%d\t",c[i][j]);
}
return 0;
}
Write a c program to read one matrix and find the sum of its diagonal
#include<stdio.h>
void main()
{
int a[10][10],sum=0;
int i,j,m,n;
clrscr();
printf("Enter Order of Matrix = ");
scanf("%d%d",&m,&n);
if(m!=n)
{
printf("Not a Square Matrix : ");
getch();
exit();
}
printf("Enter Elements : ");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(i==j)
{
sum+=a[i][j];
}
}
}
printf("Sum of Diagonal Elements = %d ",sum);
getch();
}
Output
/* variable description
rl -> Roll No
s1 -> Subject1 Marks
s2 -> Subject2 Marks
s3 -> Subject3 Marks
t -> total
per -> percentage
nm -> name of student
div -> division */
/* linking section */
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
void main()
{
/*variable declaration part */
int rl,s1,s2,s3,t;
float per;
char nm[25],div[10];
clrscr();
/*reading part */
printf("Enter the Roll No : ");
scanf("%d",&rl);
printf("Enter Name
: ");
fflush(stdin);
gets(nm);
printf("Enter Three Subject Marks :\n");
scanf("%d%d%d",&s1,&s2,&s3);
/* processing part */
t=s1+s2+s3;
per=t/3.0;
if(per>=75)
strcpy(div,"Honour");
else if( per>=60)
strcpy(div,"First");
else if( per>=48)
strcpy(div,"Second");
else if (per>=36)
strcpy(div,"Pass");
else
strcpy(div,"Fail");
/* display part */
printf("\t\tUniversity of Gwalior\n");
printf("\n\n");
printf("Roll No: %d \t Name : %s\n",rl,nm);
printf("---------------------------------------------------\n");
printf("Subject
Max
Min
Obt.Marks\n");
printf("---------------------------------------------------\n");
printf("Hist
100
36
%d\n",s1);
printf("socio.
100
36
%d\n",s2);
printf("Hindi
100
36
%d\n",s3);
printf("---------------------------------------------------\n");
printf("
Total
%d\n",t);
Write a program using command line arguments to calculate the sum of three
numbers
#include<stdio.h>
void main(int argc, char * argv[]) {
int i, sum = 0;
if (argc != 3) {
printf("You have forgot to type numbers.");
exit(1);
}
printf("The sum is : ");
for (i = 1; i < argc; i++)
sum = sum + atoi(argv[i]);
printf("%d", sum);
}
Output :
The sum is : 30
Array of Structures
C Structure is collection of different datatypes ( variables ) which are grouped
together. Whereas, array of structures is nothing but collection of structures. This is
also called as structure array in C.
Example program for array of structures in C:
This program is used to store and access id, name and percentage for 3 students.
Structure array is used in this program to store and display records for many
students. You can store n number of students record by declaring structure
variable as struct student record[n], where n can be 1000 or 5000 etc.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[30];
float percentage;
};
int main()
{
int i;
struct student record[2];
// 1st student's record
record[0].id=1;
strcpy(record[0].name, "Raju");
record[0].percentage = 86.5;
// 2nd student's record
record[1].id=2;
strcpy(record[1].name, "Surendren");
record[1].percentage = 90.5;
// 3rd student's record
record[2].id=3;
strcpy(record[2].name, "Thiyagu");
record[2].percentage = 81.5;
for(i=0; i<3; i++)
{
printf(" Records of STUDENT : %d \n", i+1);
printf(" Id is: %d \n", record[i].id);
printf(" Name is: %s \n", record[i].name);
printf(" Percentage is: %f\n\n",record[i].percentage);
}
return 0;
}
Output:
Records of STUDENT : 1
Id is: 1
Name is: Raju
Percentage is: 86.500000
Records of STUDENT : 2
Id is: 2
Name is: Surendren
Percentage is: 90.500000
Records of STUDENT : 3
Id is: 3
Name is: Thiyagu
Percentage is: 81.500000