Anda di halaman 1dari 46

Notes ICPC

Introduction to C Language
C is a general-purpose high level language that was originally developed by Dennis Ritchie for the Unix
operating system. C has now become a widely used professional language for various reasons.

Easy to learn

Structured language

It produces efficient programs.

It can handle low-level activities.

It can be compiled on a variety of computers.

Difference between variable and constants


A constant and variable are variations of data types.
int a;
is a variable and its value can be changed by the program as the program runs.
const int b;
is a constant with a fixed value and will have its value set and may not be changed by the program as as the
program runs.
All data types may be declaired as a constant.

Key words in C
"Keywords" are words that have special meaning to the C compiler. A ivariable cannot have the same
spelling and case as a C keyword. Some basic keyword are int, float, char, double.

Data types in C Language


C supports different types of data, each of which may be represented differently within a computer's
memory. Data type is used to determine what type of value a variable or a constant can contain
throughout the program. In C language, different variables contain different data types e.g. Roll No
contains an 'integer' value whereas percentage contains a 'float' value.

Keyword
char
unsigned char
int

Format Specifier
%c
<-- -- >
%d

Size
1 Byte
8 Bytes
2 Bytes

Data Range
-128 to +127
0 to 255
-32768 to +32767

long int
unsigned int
float
double
long double

%ld
%u
%f
%lf
%Lf

-231 to +231
0 to 65535
-3.4e38 to +3.4e38
-1.7e38 to +1.7e38
-3.4e38 to +3.4e38

4 Bytes
2 Bytes
4 Bytes
8 Bytes
12-16 Bytes

Derived Data types: Array, Function, Structure, Union and pointers are considered as derived data
type.

Operators in C Language
What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are
called operands and + is called operator. C language supports following type of operators.

Arithmetic Operators

Logical (or Relational) Operators

Bitwise Operators

Assignment Operators

Misc Operators

Arithmetic Operators:
There are following arithmetic operators supported by C language: Assume variable A holds 10 and
variable B holds 20 then:

Operator

Description

Example

Adds two operands

A + B will give 30

Subtracts second operand from the first

A - B will give -10

Multiply both operands

A * B will give 200

Divide numerator by denumerator

B / A will give 2

Modulus Operator and remainder of after


an integer division

B % A will give 0

++

Increment operator, increases integer value A++ will give 11


by one

--

Decrement operator, decreases integer


value by one

A-- will give 9

Try following example to understand all the arithmatic operators.


main()
{
int a = 21;
int b = 10;
int c ;
c = a + b;
printf("Line 1 - Value of c is %d\n", c );
c = a - b;
printf("Line 2 - Value of c is %d\n", c );
c = a * b;
printf("Line 3 - Value of c is %d\n", c );
c = a / b;
printf("Line 4 - Value of c is %d\n", c );
c = a % b;
printf("Line 5 - Value of c is %d\n", c );
c = a++;
printf("Line 6 - Value of c is %d\n", c );
c = a--;
printf("Line 7 - Value of c is %d\n", c );
}

Logical Operators
&
&

Called Logical AND operator. If both the operands are non zero then then condition becomes
true.

||

Called Logical OR Operator. If any of the two operands is non zero then then condition
becomes true.

Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is
true then Logical NOT operator will make false.

Relational Operators
=
=

Checks if the value of two operands is equal or not, if yes then condition becomes
true.

!= Checks if the value of two operands is equal or not, if values are not equal then
condition becomes true.

>

Checks if the value of left operand is greater than the value of right operand, if
yes then condition becomes true.

<

Checks if the value of left operand is less than the value of right operand, if yes
then condition becomes true.

>
=

Checks if the value of left operand is greater than or equal to the value of right
operand, if yes then condition becomes true.

<
=

Checks if the value of left operand is less than or equal to the value of right
operand, if yes then condition becomes true.

Try following example to understand all the Logical operators..


main()
{
int a = 21;
int b = 10;
int c ;
if( a == b )
{
printf("Line 1 - a is equal to b\n" );
}
else
{
printf("Line 1 - a is not equal to b\n" );
}
if ( a < b )
{
printf("Line 2 - a is less than b\n" );
}
else
{
printf("Line 2 - a is not less than b\n" );
}
if ( a > b )
{
printf("Line 3 - a is greater than b\n" );
}
else
{
printf("Line 3 - a is not greater than b\n" );
}
/* Lets change value of a and b */
a = 5;
b = 20;
if ( a <= b )
{
printf("Line 4 - a is either less than or euqal to b\n" );

(A >= B) is
not true.

}
if ( b >= a )
{
printf("Line 5 - b is either greater than or equal to b\n" );
}
if ( a && b )
{
printf("Line 6 - Condition is true\n" );
}
if ( a || b )
{
printf("Line 7 - Condition is true\n" );
}
/* Again lets change the value of a and b */
a = 0;
b = 10;
if ( a && b )
{
printf("Line 8 - Condition is true\n" );
}
else
{
printf("Line 8 - Condition is not true\n" );
}
if ( !(a && b) )
{
printf("Line 9 - Condition is true\n" );
}
}

Assignment Operators:
There are following assignment operators supported by C language:

Operator

Description

Example

Simple assignment operator, Assigns C = A + B will assigne value of A + B


values from right side operands to left into C
side operand

+=

Add AND assignment operator, It


adds right operand to the left operand
and assign the result to left operand

-=

Subtract AND assignment operator, It C -= A is equivalent to C = C - A


subtracts right operand from the left
operand and assign the result to left
operand

C += A is equivalent to C = C + A

*=

Multiply AND assignment operator, It C *= A is equivalent to C = C * A


multiplies right operand with the left
operand and assign the result to left
operand

/=

Divide AND assignment operator, It


divides left operand with the right
operand and assign the result to left
operand

Misc Operators
Operato
r

Description

Example

sizeof()

Returns the size of an variable.

sizeof(a), where a is interger, will return


2.

&

Returns the address of an


variable.

&a; will give actaul address of the


variable.

Pointer to a variable.

*a; will pointer to a variable.

?:

Conditional Expression

If Condition is true ? Then value X :


Otherwise value Y

Precedence of C Operators
Operator precedence determines the grouping of terms in an expression. This affects how
an expression is evaluated. Certain operators have higher precedence than others; for
example, the multiplication operator has higher precedence than the addition operator:
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedenace than + so it first get multiplied with 3*2 and then adds into 7.

Decision Control Statements in C

C program executes program sequentially. Sometimes, a program requires checking of


certain conditions in program execution. C provides various key condition statements to
check condition and execute statements according conditional criteria.
These statements are called as 'Decision Making Statements' or 'Conditional Statements.'
Followings are the different conditional statements used in C.
1.
2.
3.
4.

If Statement
If-Else Statement
Nested If-Else Statement
Switch Case

If Statement:
This is a conditional statement used in C to check condition or to control the flow of
execution of statements. This is also called as 'decision making statement or control
statement.' The execution of a whole program is done in one direction only.
Syntax:
if(condition)
{
statements;
}
In above syntax, the condition is checked first. If it is true, then the program control flow
goes inside the braces and executes the block of statements associated with it. If it returns
false, then program skips the braces. If there are more than 1 (one) statements in if
statement then use { } braces else it is not necessary to use.
Program :
#include <stdio.h>

#include <conio.h>
void main()
{
int a;
a=5;
clrscr();
if(a>4)
printf("\nValue of A is greater than 4 !");
if(a==4)
printf("\n\n Value of A is 4 !");
getch();
}
If-Else Statement:
This is also one of the most useful conditional statement used in C to check conditions.
Syntax:
if(condition)
{
true statements;
}
else
{
false statements;
}
In above syntax, the condition is checked first. If it is true, then the program control flow
goes inside the braces and executes the block of statements associated with it. If it returns
false, then it executes the else part of a program.
Example :
#include <stdio.h>

#include <conio.h>
void main()
{
int no;
clrscr();
printf("\n Enter Number :");
scanf("%d",&no);
if(no%2==0)
printf("\n\n Number is even !");
else
printf("\n\n Number is odd !");
getch();
}

Nested If-Else Statement:

It is a conditional statement which is used when we want to check more than 1 conditions
at a time in a same program. The conditions are executed from top to bottom checking
each condition whether it meets the conditional criteria or not. If it found the condition is
true then it executes the block of associated statements of true part else it goes to next
condition to execute.
Syntax:
if(condition)
{
if(condition)
{
statements;
}
else
{
statements;
}
}

else
{
statements;
}
In above syntax, the condition is checked first. If it is true, then the program control flow
goes inside the braces and again checks the next condition. If it is true then it executes the
block of statements associated with it else executes else part.
Example:

#include <stdio.h>
#include <conio.h>
void main()
{
int no;
clrscr();
printf("\n Enter Number :");
scanf("%d",&no);
if(no>0)
{
printf("\n\n Number is greater than 0 !");
}
else
{
if(no==0)
{
printf("\n\n It is 0 !");
}
else
{
printf("Number is less than 0 !");
}
}
getch();
}

Switch case Statement:


This is a multiple or multiway brancing decision making statement.
When we use nested if-else statement to check more than 1 conditions then the
complexity of a program increases in case of a lot of conditions. Thus, the program is
difficult to read and maintain. So to overcome this problem, C provides 'switch case'.
Switch case checks the value of a expression against a case values, if condition matches
the case values then the control is transferred to that point.
Syntax:
switch(expression)
{
case expr1:
statements;
break;
case expr2:
statements;
break;
''''''''''''''''
''''''''''''''''
case exprn:
statements;
break;
default:
statements;
}
In above syntax, switch, case, break are keywords.
expr1, expr2 are known as 'case labels.'

Statements inside case expression need not to be closed in braces.


Break statement causes an exit from switch statement.
Default case is optional case. When neither any match found, it executes.
Example :
#include <stdio.h>
#include <conio.h>
void main()
{
int no;
clrscr();
printf("\n Enter any number from 1 to 3 :");
scanf("%d",&no);
switch(no)
{
case 1:
printf("\n\n It is 1 !");
break;
case 2:
printf("\n\n It is 2 !");
break;
case 3:
printf("\n\n It is 3 !");
break;
default:
printf("\n\n Invalid number !");
}
getch();
}

Difference between continue and break statement:

There are two statement built in C, break; and continue; to interrupt the normal flow of control of a program.
Loops performs a set of operation repeately until certain condition becomes false but, it is sometimes desirable
to skip some statements inside loop and terminate the loop immediately without checking the test expression.
In such cases, break and continue statements are used.

break Statement
In C programming, break is used in terminating the loop immediately after it is encountered. The break
statement is used with conditional if statement.

Syntax of break statement


break;
The break statement can be used in terminating all three loops for, while and do...while loops.

The figure below explains the working of break statement in all three type of loops.

Example of break statement


Write a C program to find average of maximum of n positive numbers entered by user. But, if the
input is negative, display the average(excluding the average of negative input) and end the
program.

/* C program to demonstrate the working of break statement by terminating a loop, if


user inputs negative number*/

# include <stdio.h>
int main(){
float num,average,sum;
int i,n;
printf("Maximum no. of inputs\n");
scanf("%d",&n);
for(i=1;i<=n;++i){
printf("Enter n%d: ",i);
scanf("%f",&num);
if(num<0.0)
break;
//for loop breaks if num<0.0
sum=sum+num;
}
average=sum/(i-1);
printf("Average=%.2f",average);
return 0;
}
Output

Maximum no. of inputs


4
Enter n1: 1.5
Enter n2: 12.5
Enter n3: 7.2
Enter n4: -1
Average=7.07
In this program, when the user inputs number less than zero, the loop is terminated using break statement
with executing the statement below it i.e., without executing sum=sum+num.
In C, break statements are also used in switch...case statement. You will study it in C switch...case statement
chapter.

continue Statement
It is sometimes desirable to skip some statements inside the loop. In such cases, continue statements are
used.

Syntax of continue Statement


continue;
Just like break, continue is also used with conditional if statement.

For better understanding of how continue statements works in C programming. Analyze the figure below which
bypasses some code/s inside loops using continue statement.

Example of continue statement


Write a C program to find the product of 4 integers entered by a user. If user enters 0 skip it.

//program to demonstrate the working of continue statement in C programming


# include <stdio.h>
int main(){
int i,num,product;
for(i=1,product=1;i<=4;++i){
printf("Enter num%d:",i);
scanf("%d",&num);
if(num==0)
continue; / *In this program, when num equals to zero, it skips the
statement product*=num and continue the loop. */
product*=num;
}
printf("product=%d",product);
return 0;
}
Output

Enter num1:3

Enter num2:0
Enter num3:-5
Enter num4:2
product=-30
- See more at: http://www.programiz.com/c-programming/c-break-continue-statement#sthash.qwGf4dr9.dpuf

Example based on Decision Control Statements /Repetition control statements in C


Language
Program to find out greatest of three numbers using Decision Control Statement
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf("Enter the value of a:");
scanf("%d",&a);
printf("\nEnter the value of b:");
scanf("%d",&b);
printf("\nEnter the value of c:");
scanf("%d",&c);
if(a>b)
{if(a>c)
printf("a is largest");
else

printf("c is largest");}
else
if(b>c)
printf("b is largest");
else
printf("c is largest");
getch();
}
Program to Make Calculator using Switch case statements
#include<stdio.h>
#include<stdlib.h>
void main()
{
int a,b,res,ch;
printf("\t *********************");
printf("\n\tMENU\n");
printf("\t********************");
printf("\n\t(1)ADDITION");
printf("\n\t(2)SUBTRACTION");
printf("\n\t(3)MULTIPLICATION");
printf("\n\t(4)DIVISION");
printf("\n\t(5)REMAINDER");
printf("\n\t(0)EXIT");
printf("\n\t********************");
printf("\n\n\tEnter your choice:");
scanf("%d",&ch);
if(ch<=5 & ch>0)
{
printf("Enter two numbers:\n");
scanf("%d%d",&a,&b);
}

switch(ch)
{
case 1:
res=a+b;
printf("\n Addition:%d",res);
break;
case 2:
res=a-b;
printf("\n Subtraction:%d",res);
break;
case 3:
res=a*b;
printf("\n Multiplication:%d",res);
break;
case 4:
res=a/b;
printf("\n Division:%d",res);
break;
case 5:
res=a%b;
printf("\n Remainder:%d",res);
break;
case 0:
printf("\n Choice Terminated");
exit(1);
break;
default:
printf("\n Invalid Choice");
}
}
LOOPS in C Language

To execute a set of instructions repeatedly until a particular condition is being satisfied.


Three types of looping statements are there
1)

For Loop

2)

While Loop

3)

Do while Loop

For Loop:In for looping statement allows a number of lines represent until the condition is satisfied
Syntax:
for(initialize counter variable ; condition ; increment/decrement the counter variable)
{
Statement1;
...
Statement n;
}
WHILE LOOP
In While looping statement allows a number of lines represent until the condition is
satisfied
Syntax:
while( condition)
{
Statement1;
...
Statement n;
}
DO WHILE LOOP:
In DO WHILE LOOP first execute the statements then it checks the condition.
Syntax:

do
{
Statement1;
...
Statement n;
}while(condition);

Difference between While loops and Do-While loop


1. In While loop the condition is tested first and then the statements are executed if
the condition turns out to be true.
In do while the statements are executed for the first time and then the conditions
are tested, if the condition turns out to be true then the statements are
executed again.
2. A do while is used for a block of code that must be executed at least once.
These situations tend to be relatively rare, thus the simple while is more commonly
used.
3. A do while loop runs at least once even though the the condition given is false
while loop do not run in case the condition given is false
4. In a while loop the condition is first tested and if it returns true then it goes in the
loop In a do-while loop the condition is tested at the last.
5. While loop is entry control loop where as do while is exit control loop.
Example
while loop :
while (condition)
{
Statements;

}
do while loop :
Do
{
Statements;
}while(condition);

Example For loop and while loop.


Ex1. Write a program to reverse a 5 digit number using while loop.
Ex2. Write a program to print following Pattern using for loop.
1
1

Ex3. Program to Calculate factorial of a number using loops.


Solution EX-1.
#include<stdio.h>
main ()
{
int num,mod,rev=0;
printf("Enter a number:");
scanf("%d", &num);
while (num>0)
{
mod=num%10;

rev=(rev*10)+mod;
num=num/10;
}
printf("Reverse of the given number: %d", rev);
getchar();
}
Solution Ex-2:
#include<stdio.h>
void main()
{
int i,j,n;
for(i=0 ; i<4 ; i++)
{
for(j=0 ; j <= i ; j++)
{
Printf("*");
}
Printf(\n);
}
}
Solution Ex-3:
#include<stdio.h>
int main(){
int input,i,result=1;
printf("please input a Integer: ");
scanf("%d",&input);
for(i=input;i>0;i--)
{
result=result*i;
}
printf("the factorial of %d is %d\n",input,result);
}

ARRAY
Array by definition is a variable that holds multiple elements which have the same data
type.
Declaring Arrays
In order to declare an array, you need to specify:

Data type of the array's elements. It could be int, float, double, char...etc.

The name of the array.

Fixed number of elements that array contains. The number of elements is put inside
square brackets followed the array name.
The following illustrates the typical syntax of declaring an array:
1
data_type array_name[size];
For example, to declare an array of integers with size of 10, you can do as follows:
1
int a[100];
In the memory, you have 10 consecutive objects like following:

For example, to declare an array of integers with size of 10, you can do as follows:
You must follow the rules below when you declare an array in C:

The data type can be any valid C data types.

The name of an array has to follow the rule of C variables.

The size of array has to be a positive constant integer.


Initializing Arrays
Similar to a variable, an array can be initialized. To initialize an array, you provide
default values enclosed within curly braces in the declaration and assign that expression
to the array.
Here is an example of initializing an array of integers.
1
int list[5] = {2,1,3,7,8};

Bounds Checking
In C there is no check to see if the subscript used for an array exceeds the size of the
array. Data entered with a subscript exceeding the array size will simply be placed in
memory outside the array; probably on top of other data, or on the program itself. This
will lead to unpredictable results, to say the least, and there will be no error message to
warn you that you are going beyond the array size. In some cases the computer may just
hang. Thus, the following program may turn out to be suicidal.
main( )
{
int num[40], i ;
for ( i = 0 ; i <= 100 ; i++ )
num[i] = i ;
}
Thus, to see to it that we do not reach beyond the array size is entirely the programmers
botheration and not the compilers.
Accessing Array's Elements using Pointers
#include<stdio.h>
Void main()
{
int a[5]={1,2,3,4,5};
int *ptr,i;
ptr=&a[0];
for (i=0;i<=4;i++)
{
Printf(%d,*(ptr+i));
}

getch();
}
Program of Linear search :
#include<stdio.h>
int main(){
int a[5]={10,11,12,13,14,15},i,n,m,count=0;
printf("Enter the number to be search: ");
scanf("%d",&m);
for(i=0;i<=n-1;i++){
if(a[i]==m){
count=1;
break;
}
}
if(c==0)
printf("The number is not in the list");
else
printf("The number is found");
}

return 0;

What is 2D ARRAY?
It is also possible for arrays to have two or more dimensions. The two-dimensional array
is also called a matrix.
Memory Map of 2D array
In memory whether it is a one-dimensional or a two-dimensional array the array elements
are stored in one continuous chain. The arrangement of array elements of a twodimensional array in memory is shown below.

Initialising and declaration of a 2-Dimensional Array


Declaration of 2D array
Int a[2][2];
Initialization of 2D array
Int a[2][2]={
{2,2},
{3,3}
};
Matrix Addition Program
#include <stdio.h>
int main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter the elements of second matrix\n");
for (c = 0; c < m; c++)
for (d = 0 ; d < n; d++)
scanf("%d", &second[c][d]);

printf("Sum of entered matrices:-\n");


for (c = 0; c < m; c++) {
for (d = 0 ; d < n; d++) {
sum[c][d] = first[c][d] + second[c][d];
printf("%d\t", sum[c][d]);
}
printf("\n");
}
return 0;
}

Multiplication of two matrix using 2D array


# include <stdio.h>
main()
{
int m1[10][10],i,j,k,m2[10][10],mult[10][10],r1,c1,r2,c2;
printf("Enter number of rows and columns of first matrix (less than 10)\n");
scanf("%d%d",&r1,&c1);
printf("Enter number of rows and columns of second matrix (less than 10)\n");
scanf("%d%d",&r2,&c2);
if(r2==c1)
{
printf("Enter Elements in First matrix \n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&m1[i][j]);
}
}
printf("Enter Elements in Second matrix \n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf("%d",&m2[i][j]);
}
}

printf("Multiplication of the Matrices:\n");


for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
mult[i][j]=0;
for(k=0;k<r1;k++)
mult[i][j]+=m1[i][k]*m2[k][j];
printf("%d\t",mult[i][j]);
}
printf("\n");
}
}
else
{
printf("Matrix multiplication cannot be done");
}
return 0;
}
FUNCTION
Function: A function is a self-contained block of statements that perform a
task of some kind. A function is a group of statements for execution.

Difference between Recursion and Iteration


1) Recursive function is a function that is partially defined by itself whereas Iterative
functions are loop based imperative repetitions of a process
2) Recursion Uses selection structure whereas Iteration uses repitation structure
3) Recursion is usually slower then iteration

4) Recursion uses more memory than iteration


5) Infinite recursion can crash the system whereas infinite looping uses CPU.
6) Recursion makes program smaller and iteration makes program longer
Program to calculate factorial using Recursion.
main( )
{
int a, fact ;
printf ( "\nEnter any number " ) ;
scanf ( "%d", &a ) ;
fact = rec ( a ) ;
printf ( "Factorial value = %d", fact ) ;
}
rec ( int x )
{
int f ;
if ( x == 1 )
return ( 1 ) ;
else
f = x * rec ( x - 1 ) ;
return ( f ) ;
}

Difference between call by value and call by reference


Calling by value makes a copy of the variable so the function can use it, calling by
reference sends the memory address of the variable to the function so the function works
with the original value.

Program 1 Call by value


swap(int x1, int y1)
{
int z1;
z1=x1;
x1=y1;
y1=z1;
printf(x1=%d y1=%d,x1,y1);
}
main()
{
int x=100, y=200;
swap(x,y);
printf(x=%d y=%d,x,y);
}
Program 2 Call by reference
swap(int *x1, int *y1)
{
int z1;
z1=*x1;

//This statement will print 100 and 200

*x1=*y1;
*y1=z1;
printf(*x=%d *y=%d,x1,y1);
}
main()
{
int x=100, y=200;
swap(&x,&y);
printf(x=%d y=%d,x,y);

//This statement will print 200 and 100 because call by


reference will work on the original value

Storage Classes
Moreover, a variables storage class tells us:
(a) Where the variable would be stored.
(b) What will be the initial value of the variable, if initial value is not specifically
assigned.(i.e. the default initial value).
(c) What is the scope of the variable; i.e. in which functions the value of the variable
would be available.
(d) What is the life of the variable; i.e. how long would the variable exist.

There are four storage classes in C:


(a) Automatic storage class
(b) Register storage class
(c) Static storage class
(d) External storage class
Automatic Storage Class

The features of a variable defined to have an automatic storage class are as under:
Storage Memory.
Default initial value An unpredictable value, which is often called a garbage value.
Scope Local to the block in which the variable is defined.
Life Till the control remains within the block in which the variable is defined.
Following program shows how an automatic storage class variable is declared, and the
fact that if the variable is not initialized it contains a garbage value.
Register Storage Class
The features of a variable defined to be of register storage class are as under:
Storage
- CPU registers.
Default initial value - Garbage value.
Scope - Local to the block in which the variable is defined.
Life - Till the control remains within the block in which the variable is defined.
Static Storage Class
The features of a variable defined to have a static storage class are as under:
Storage Memory.
Default initial value Zero.
Scope Local to the block in which the variable is defined.
Life Value of the variable persists between different function calls.
External Storage Class
The features of a variable whose storage class has been defined as external are as follows:
Storage Memory.
Default initial value Zero.
Scope Global.
Life As long as the programs execution doesnt come to an end.
STRUCTURE: Structure can be a collection of heterogeneous data type.
Structure Declaration:

struct struct-name{
type field-name;
type field-name;
... };

Accessing Structure Elements


#include <stdio.h>
#include <conio.h>
struct student
{
int id;
char *name;
float percentage;
} student1;
int main()
{
student1.id=1;
student2.name = "Angelina";
student3.percentage = 90.5;
printf(" Id is: %d \n", student1.id);
printf(" Name is: %s \n", student2.name);
printf(" Percentage is: %f \n", student3.percentage);
getch();
return 0;
}
Use of structures
We have seen earlier how ordinary variables can hold one piece of information and how
arrays can hold a number of pieces of information of the same data type. These two data

types can handle a great variety of situations. But quite often we deal with entities that
are collection of dissimilar data types. In some types of situation when we have to store
dissimilar data structure can be used.
How structure members are stored in memory
Whatever be the elements of a structure, they are always stored in contiguous memory
locations. The following program would illustrate this:
/* Memory map of structure elements */
main( )
{
struct book
{
char name ;
float price ;
int pages ;
};
struct book b1 = { 'B', 130.00, 550 } ;
printf ( "\nAddress of name = %u", &b1.name ) ;
Chapter 10: Structures 371
printf ( "\nAddress of price = %u", &b1.price ) ;
printf ( "\nAddress of pages = %u", &b1.pages ) ;
}
Here is the output of the program...
Address of name = 65518
Address of price = 65519
Address of pages = 65523
Actually the structure elements are stored in memory as shown in the Figure below.

Preprocessor Directives:
We would learn the following preprocessor directives here:
(a) Macro expansion
(b) File inclusion
(c) Conditional Compilation
Macro Expansion
Have a look at the following program.
#define UPPER 25
main( )
{
int i ;
for ( i = 1 ; i <= UPPER ; i++ )
printf ( "\n%d", i ) ;
}
In this program instead of writing 25 in the for loop we are writing it in the form of
UPPER, which has already been defined before main( ) through the statement,
#define UPPER 25
This statement is called macro definition or more commonly, just a macro. What
purpose does it serve? During preprocessing, the preprocessor replaces every occurrence
of UPPER in the program with 25.
File Inclusion (#include)
A preprocessor include directive causes the preprocessor to replace the directive with
the contents of the specified file.

If the file name is enclosed in double quotation marks, for example:


#include "payroll.h"
the preprocessor treats it as a user-defined file, and searches for the file in a manner
defined by the preprocessor.
If the file name is enclosed in angle brackets, for example:
#include <stdio.h>
it is treated as a system-defined file, and the preprocessor searches for the file in a
manner defined by the preprocessor.

#include: Search the file only include directory


(c:\tc\include)
#include filename.h: Search the file include directory as
well as current working directory(Search in all of TC
folders).

Conditional Compilation
We can, if we want, have the compiler skip over part of a source code by inserting the
preprocessing commands #ifdef and #endif, which have the general form:
#ifdef macroname
statement 1 ;
statement 2 ;
statement 3 ;
#endif

STRING
strlen( )

This function counts the number of characters present in a string. Its usage is illustrated in
the following program.
main( )
{
char arr[ ] = "Bamboozled" ;
int len1, len2 ;
len1 = strlen ( arr ) ;
len2 = strlen ( "Humpty Dumpty" ) ;
printf ( "\nstring = %s length = %d", arr, len1 ) ;
printf ( "\nstring = %s length = %d", "Humpty Dumpty", len2 ) ;
}
The output would be...
string = Bamboozled length = 10
string = Humpty Dumpty length = 13
strcpy( )
This function copies the contents of one string into another. The base addresses of the
source and target strings should be supplied to this function. Here is an example of
strcpy( ) in action...
main( )
{
char source[ ] = "Sayonara" ;
char target[20] ;
strcpy ( target, source ) ;
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;

}
And here is the output...
source string = Sayonara
target string = Sayonara
strcat( )
This function concatenates the source string at the end of the target string. For example,
Bombay and Nagpur on concatenation would result into a string BombayNagpur.
Here is an example of strcat( ) at work.
main( )
{
char source[ ] = "Folks!" ;
char target[30] = "Hello" ;
strcat ( target, source ) ;
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;
}
And here is the output...
source string = Folks!
target string = HelloFolks!
strcmp( )
This is a function which compares two strings to find out whether they are same or
different. The two strings are compared character by character until there is a mismatch
or end of one of the strings is reached, whichever occurs first. If the two strings are
identical, strcmp( ) returns a value zero. If theyre not, it returns non zero values.
main( )

{
char string1[ ] = "Jerry" ;
char string2[ ] = "Ferry" ;
int i, j, k ;
i = strcmp ( string1, "Jerry" ) ;
j = strcmp ( string1, string2 ) ;
k = strcmp ( string1, "Jerry boy" ) ;
printf ( "\n%d %d %d", i, j, k ) ;
}
And here is the output...
0 4 -32
In the first call to strcmp( ), the two strings are identicalJerry and Jerryand the
value returned by strcmp( ) is zero. In the second call, the first character of Jerry
doesn't match with the first character of Ferry and the result is 4, which is the numeric.

***Write User defind functions to calculate length of string.


main( )
{
char arr[ ] = "Bamboozled" ;
int len1, len2 ;
len1 = xstrlen ( arr ) ;
len2 = xstrlen ( "Humpty Dumpty" ) ;
printf ( "\nstring = %s length = %d", arr, len1 ) ;
printf ( "\nstring = %s length = %d", "Humpty Dumpty", len2 ) ;
}

xstrlen ( char *s )
{
int length = 0 ;
while ( *s != '\0' )
{
length++ ;
s++ ;
}
return ( length ) ;
}
The output would be...
string = Bamboozled length = 10
string = Humpty Dumpty length = 13

***Write user defined function to copy one string in to another

main
{
char source[ ] = "Sayonara" ;
char target[20] ;
xstrcpy ( target, source ) ;
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;
}

xstrcpy ( char *t, char *s )


{
while ( *s != '\0' )
{
*t = *s ;
s++ ;
t++ ;
}
*t = '\0' ;
}

Formatted and Unformatted input output functions


Unformatted I/O functions
Getch()- To read single character from keyboard with out echoing.
Getche()- To read single character with echoing.
Getchar()- Read on character from user
Putchar()- Print one characher on the output screen
Gets()- Read one string from user
Puts()- Print one srting on the output screen
Formatted I/O Functions
Sscanf()Syntax:
sscanf(characterArray, "Conversion specifier", address of variables);

This will extract the data from the character array according to the conversion specifier
and store into the respective variables.
Let us understand this using an example.
char *str = "Learn C Online";
char *first, *second, *third;
sscanf(str, "%s %s %s",first,second,third);
In the above example,
"Learn" will get stored in variable first
"C" will get stored in variable second
"Online" will get stored in variable third
Sprintf()
sprintf() function is exactly opposite to sscanf() function. Sprint() function writes the
formatted text to a character array.
Syntax:
sprintf (CharacterArray,"Conversion Specifier", variables);
Let us understand this using an example.
char *str;
char *first = "Learn", *second = "C", *third = "Online";
sprintf(str, "%s %s %s",first,second,third);
In the above example, Learn C Online will get stored in the character array str.
FILE HANDLING
What is file handling?
File is a place where information or data is stored.
we make use of some of the file-handling functions in c like:
fopen()-for opening a file.
fclose()-to close a file. Every file being opened for any operations like:

"r"- Read-Only mode.


"w"-Write-only mode.
"a"-append mode.
"r+"-read+write mode.
"w+"-write+read mode.
"a+"-read+append mode.
We should make use of FILE pointer, in order to perform any such operations on the
files.
Various File Accessing Modes
"r"- Read-Only mode.
"w"-Write-only mode.
"a"-append mode.
"r+"-read+write mode.
"w+"-write+read mode.
"a+"-read+append mode.

Program to copy content of one file in to another


#include<stdio.h>
int main(){
FILE *p,*q;
char file1[20],file2[20];
char ch;
printf("\nEnter the source file name to be copied:");
gets(file1);
p=fopen(file1,"r");
if(p==NULL){
printf("cannot open %s",file1);
exit(0);
}
printf("\nEnter the destination file name:");
gets(file2);
q=fopen(file2,"w");
if(q==NULL){
printf("cannot open %s",file2);
exit(0);
}

while((ch=getc(p))!=EOF)
putc(ch,q);
printf("\nCOMPLETED");
fclose(p);
fclose(q);
return 0;
}

POINTER
What is pointer? Explain with examples
A pointer is a variable that holds a memory address.
The general form of declaring a pointer variable is:
type *name;
type is the data type of the pointer.
name is the name of pointer variable.
The data type of the pointer defines what type of variables the pointer can point to.
Two special pointer operators are: * and &.
The & is operator that gives the memory address.
The * is complement of &. It returns the value located at the address that follows.
int i, *p;
i = 5;
p = &i;

//places the memory address of i into p

The expression *p will return the value of variable pointed to by p.

Managing I/O operation on Integer and string

Modular programming
Modular programming is the process of subdividing a computer program into separate sub-programs.
A module is a separate software component. It can often be used in a variety of applications and functions
with other components of the system. Similar functions are grouped in the same unit of programming code
and separate functions are developed as separate units of code so that the code can be reused by other
applications.
Object-oriented programming (OOP) is compatible with the modular programming concept to a large extent.
Modular programming enables multiple programmers to divide up the work and debug pieces of the program
independently.
The benefits of using modular programming includ:

Less code has to be written.

A single procedure can be developed for reuse, eliminating the need to retype the code many times.

Programs can be designed more easily because a small team deals with only a small part of the
entire code.

Modular programming allows many programmers to collaborate on the same application.

The code is stored across multiple files.

Code is short, simple and easy to understand.

Errors can easily be identified, as they are localized to a subroutine or function.

The same code can be used in many applications.

The scoping of variables can easily be controlled.

Types of software
Component of computer system or architecture of computer system
Number systems.

Anda mungkin juga menyukai