Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
117 views

C Programing Basic Notes With Program

The document contains C code to demonstrate the use of for loops. It includes two programs: 1. A program that uses a for loop to print all natural numbers from 1 to a user-input value of n. 2. A program that uses a for loop to print all odd numbers from 1 to a user-input value of n. Both programs initialize the loop counter variable, specify the loop condition to repeat until the counter reaches n, and increment the counter by 1 each iteration. The first program prints each counter value, while the second only prints odd values.

Uploaded by

Yogesh Katre
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
117 views

C Programing Basic Notes With Program

The document contains C code to demonstrate the use of for loops. It includes two programs: 1. A program that uses a for loop to print all natural numbers from 1 to a user-input value of n. 2. A program that uses a for loop to print all odd numbers from 1 to a user-input value of n. Both programs initialize the loop counter variable, specify the loop condition to repeat until the counter reaches n, and increment the counter by 1 each iteration. The first program prints each counter value, while the second only prints odd values.

Uploaded by

Yogesh Katre
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 54

WAP to read cost price and sales price and determine weather

shopkeeper made profit or loss or no profit no loss and by how


much amount.
#include<stdio.h>
Void main( )
{
float cp,sp,amount;
clrscr();
printf( “ Enter cost price and sales price”);
Scanf(“ %f %f “ ,&cp,&sp);
amount = sp – cp;
if( amount > 0)
printf(“ The shopkeeper makes profit = % f Rs “,amount);
else if(amount < 0)
printf(“The shopkeeper loss= %f Rs”, amount);
else
printf(“ No profit no loss”);
getch();
}

1
WAP to read student name and marks of 3 subjects.calculate and print
total percentage and grade as per following condition.
Percentage Grade
>=75 Distinction
60 – 75 First
50 – 60 second
< 50 Third
#include <stdio.h>
void main()
{
char stn;
float per;
int m1,m2,m3,total;
clrscr();
printf(“ Enter student name:”);
gets(stn);
printf(“ Enter marks of m1 , m2 and m3 subjects”);
scanf(“ %d %d %d “ &m1,&m2,&m3);
total= m1 + m2 + m3;
per= total/3.0;
printf(“ Total = %d “, total);
printf(“ percentage= %d”, per);
if (per >= 75)
printf(“ grade is distinction”);
else if(per > 60)
printf(“grade is first”);
else if( per > 50)
printf(“ grade is second”);
else
printf(“ grade is third);
getch();
}

2
WAP to read customer name,current meter reading and last meter
reading .Calculate and print total unit consumes and bill amount.As per
following condition.
Unit consumes Rate per unit
>= 500 7
400- 500 6
300-400 5
< 300 4
#include< stdio.h>
{
int cmr,lmr,uc,ba;
char cn;
clrscr();
printf(“ Enter customer name:”);
gets(cn);
printf(“ Enter current meter reading and last meter reading “);
scanf(“ %d %d “, &cmr,&lmr);
uc= cmr – lmr;
printf(“ unit consumes= %d “, uc);
if ( uc >= 500)
ba= uv * 7;
else if (uc > 400)
ba= uc * 6;
else if( uc > 300)
ba= uc * 5;
else
ba= uc * 4;
printf(“ Bill Amount = %d “, ba);
getch();
}

3
WAP to read emp-name and his basic salary.calculate and print hra,ta of gross salary as per
following condition.
Basic salary HRA TA PF
>=35000 10% 12% 14%
2000>35000 8% 10% 12%
<2000 6% 8% 10%
#include<stdio.h>
Void main()
{
char ename;
float bs,hra,ta,pf,gs;
clrscr();
printf(“ Enter employee name: “);
gets(ename);
printf(“Basic salary:”);
scanf(“%f”, &bs);
if( bs >= 35000)
{
hra = bs * 0.10;
ta= bs * 0.12;
pf= bs * 0.14;
}
else if( bs >= 20000)
{
hra= bs * 0.08;
ta= bs * 0.10;
pf= bs * 0.12;
}
else
{
hra= bs * 0.06;
ta= bs * 0.08;
pf= bs * 0.12;
}
gs = (bs+ hra + ta) – pf;
printf(“ \n HRA= %f “, hra);
printf(“\n TA= %f”, ta);
printf(“ \n PF= %f”, pf);
printf(“\n Gross salary= %f”,gs);
getch();
}

4
Logical operator:
Logical operators allow us to form more complex test
expressions for decision and repetition statements. The logical
operators are
1) &&(logical AND)
2) || (logical OR)
3) !(logical not)

“&&” and “||” are binary operator,but “!” is a unary operator.Each of


these operators returns a value of 0(false) OR 1 (true)

WAP to read sides of triangle and print wheather it is an


isosceles triangle or equilateral triangle or scaler triangle.
#include<stdio.h>
void main()
{
int a,b,c;
clrscr();
printf(“Enter side:”);
scanf(“%d %d %d”,&a,&b,&c);
if( a==b && a==c)
printf(“\n It is an equilateral triangle”);
else if(a==b || a==c || b==c)
printf(“\n It is an isosceles triangle”);
else
printf(“\n it is an scalar triangle”);
getch();
}

5
Conditional or Ternary operator
This operator is combination of ? and : and takes three operands and hence
popularly known as ternary operator.The general form of ternary operator is
as follows
Condition? Expression1: Expression2
The condition is evaluated first.if the result is nonzero(true),expression1 is
evaluated and is returned as the value of the conditional
expression,otherwise expression2 is evaluated and its value is returned.
WAP to find biggest number among three.
#include<stdio.h>
void main()
{
int big,a=1,b=3,c=2;
clrscr();
big= a>b(a>c?a:c):(b>c?b:c);
printf(“\n Big=%d”,big);
getch();
}
WAP to receive three number from the keyboard and check whether
the number inputted are in sorted order or not.
#include<stdio.h>
Void main()
{
int n1,n2,n3;
clrscr();
printf(“\n input three number”);
scanf(“%d%d%d”,n1,n2,n3);
if( n1<= n2 && n2 <=n3)
printf(“Number are sorted”);
else
printf(“number are not sorted”);
getch()
}

6
If the month and the year is inputted through the keyboard, then write
a program to calculate number of days of an inputted month.
Void main()
{
int month,year,days;
clrscr();
printf(\n Enter month :”);
scanf(“%d”,&month);
printf(“\n Enter year”);
scanf(“%d”,&year);
/* FEBRUARY*/
If(month==2)
{
/* If Leap Year */
If((year%4==0 && year % 100 != 0) || (year % 400==0))
days=29;
else
days=28;
}
else
/* if month is April,June,September or November then days=30 */
If((month ==4) || (month==6) || (month==9) || (month==11))
days=30;
else
days=31;
printf(“\n Number of Days=%d”,days);
getch();
}

7
The Switch Statement
The switch is a multiple branching statement.This statement
allows us to make a decision from the number of choices.The
general form of switch statement is as follows.
switch(integral expression)
{
case value:
execute this;
break;
case value:
execute this;
break;
case value:
execute this;
break;
default :
executes this;
}
First the integral expression (either integer Or character)
following the keyword switch gets evaluated. The value of the
expression then matches one by one against the constant value
that follows the case statement. when the match is found ,the
program executes the statement following the case and then all
the subsequent case and default statement as well. If no match
is found with any of case statements, the default statement get
executed.

8
WAP to enter any character and find it is vowel or not a vowel.
#include<stdio.h>
#include<ctype.h>
Void main()
{
char alpha;
clrscr();
printf(“\n Enter any alphabet:”);
scanf(“%c”,&alpha);
alpha= toupper(alpha);
switch(alpha)
{
case ‘A’:
case ‘E’:
case ‘ I’:
case ‘O’:
case ‘U’:
printf(“The enter character is a vowel…”);
break;
default:
printf(“/n The entered character is not a vowel…”);
}
getch ();
}

9
WAP which inputs a date in the format dd/mm/yy and outputs
it in the format: month,dd,year.For example ,20/06/74 june 6
1974become june 6,1974.
#include<stdio.h>
Void main()
{
int day,month,year;
char ch,slash1,slash2;
clrscr();
printf(“\n Input a date as dd/mm/yy”);
scanf(“%d %c %d %c %d”,&day,&slash1,&month,&slash2,&year);
switch(month)
{
case 1: printf(“January”);
break;
case 2: printf(“february”);
break;
case 3: printf(“March”);
break;
case 4: printf(“April”);
break;
case 5: printf(“May”);
break;
case 6: printf(“June”);
break;
case 7: printf(“July”);
break;
case 8: printf(“August”);
break;
case 9: printf(“September”);
break;

10
case 10: printf(“October”);
break;
case 11: printf(“November”);
break;
case 12: printf(“december”);
break;
}
printf(“%d %d “,day,year);
getch();
}
WAP to read any no. and print its even or odd using switch
#include<stdio.h>
{
int n;
clrscr();
printf(“Enter any number:”);
scanf(“ %d “,&n);
switch( n % 2)
{
case 1:
printf(“\n Number is even”);
break;
case 2:
printf(“\n Number is even”);
break;
}
getch();
}

11
What is loop?
Loop control structures are used to execute and repeat a block
of statements depending on the value of a condition. There are
three types of loop control structures /statement in c language.
a)for loop
b) while loop
c)do while loop

a)for loop
A for loop is used to execute and repeat a block of statement
depending on a condition. It has the following form.
for(<initial value>;<condition>;<increment>)
{
< Statement block>;
}
Where <initial value> is the assignment expression which
initializes the value of a variable.
<condition> is a relational or logical expression which will have
the vale true or false.
<increment> is the increment value of the variable which will
be added every time.
Example:
for(i=0;i<10;i++)
{
printf(“C is best”);
}

12
Programs on for loop:
Write a c program to print natural number from 1 to n.
/* program to natural number upto n*/
#include<stdio.h>
Void main()
{
int i,n;
clrscr();
printf(“\n Enter value to n:);
scanf(“%d”,&n);
// loop to generate and print natural numbers
for( i=1;i<=n;i++)
printf(“ 8d%”,i);
getch();
}

Output:

Enter value to n: 15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

13
Write a c program to print odd number from 1 to n.
Write a c program to read any 10 numbers and print sum of all
numbers.
#include<stdio.h>
Void main()
{
int num,i,sum=0;
clrscr();
for(i=1; i<=10;i++)
{
printf(“ Enter any number”);
scanf(“%d “,&num);
sum=sum + num;
}
Printf(“ Sum of all numbers= %d”,sum);
getch();
}

1)Write a program to enter 10 number and print sum of odd and even
number.
2)Write a program to print the square of numbers from 1 to 10;
3)Write a program to print the sum of following series:
1x + 2x + 3x + 4x……………………………….+ nx.
4) Write a program to read n numbers and count the total positive
negative and zeros you entered.
5) Write a program to read n numbers and print the greatest number.
6)Write a program to read n numbers and print the smallest number.
7) Write a c program to generate and print the numbers between 100
and 200 which are divisible by 3,but not divisible by 4.

14
Write a program to read n numbers and print highest and lowest
number.
#include<stdio.h>
Void main()
{
int n,I,num,high,low;
clrscr();
printf(“ enter the value of n”);
scanf(“ %d”,&n);
for(i=1;i<=n;i++)
{
printf(“\nEnter any number:”);
scanf(“%d”,&num);
if(i==1)
high=low=1;
if( num> high)
high=num;
if(num < low)
low=num;
}
printf(“\n highest number= %d”,high);
printf(“\n lowest number=%d”,low);
getch();
}

15
While loop:
The while loop is entry controlled loop(the entry controlled loop test
the condition first and then executes the body of the loop)
The general form of while loop is as follows.
While(expression)
{
Statements;
}

Write a program to print the number in reverse order from 1 to 10.


#include<stdio.h>
Void main()
{
int i=10;
clrscr();
while(i>=1)
{
printf(“\n %d”,i);
i--;
}
getch();
}
Output:
10 9 7 6 5 4 3 2 1

16
Write a program to print odd and even numbers from the set of the
first twenty number.
#include<stdio.h>
Void main()
{
int i=1;
clrscr();
while(i<=20)
{
if(i%2==0)
printf(“\n %d: Even”, i);
else
printf(“\n %d : odd”,i);
}
getch();
}
WAP to read any number and print its factorial
#include<stdio.h>
{
int num;
long int fact=1;
clrscr();
printf(“enter any number”);
scanf(“%d”,&num);
while(num !=1)
{
fact= fact * num;
num--;
}
printf(“factorial = %d”,fact);
getch();
}

17
Write a program to find armstrong numbers between 1 to 500 including them. If
the sum of cubes of each digit of the number is equal to the number itself, then
the number is called an Armstrong number.A
#include<conio.h>
#include<stdio.h>
Void main()
{
int number,sum=0,p,i=1,arm=0;
clrscr();
while(i<=500)
{
number=i;
arm=0;
while(number!=0)
{
p=number%10;
arm=arm + pow(p,3);
number=number/10;
}
if(arm==0)
printf(“\n Armstrong Number= %d”,arm);
i++;
}
getch();
}
Assignment:
1) Write a c program to accept an integer number and print the digit using
words( for example ,356 is printed as three five six).
2) Write a c program to reverse a given integer(for example ,28431 is reversed
as 13482).
3) Write a c program to find the sum of the digit of any given positive integer
( example n=123,then sum of digit 1+2+3=6)
4) Write a program to generate the first 50 positive integer that are divisible by
7.
5) Write a c program to print the individual digit of a 6 digit number.

18
Write a c program to generate the Fibonacci series.
0 1 1 2 3 5 8….up to n.
#include<stdio.h>
main()
{
int n,n1,n2,newtern;
clrscr();
printf(“ \n Enter the final term of the series:”);
scanf(“%d”,&n);
n1=0;
n2=1;
printf(“%8d %8d”,n1,n2);
newtern =n1 + n2;
while(newtern <= n)
{
printf(“%8d”, newterm);
n1=n2;
n2= newtern;
newtern= n1 + n2;
}
getch();
}
OUTPUT
Enter the final term of the series: 25
0 1 1 2 3 5 8 13 21

19
Do while statement:

The do while loop is exit controlled loop (it executes the body of the
loop first and then check the test condition).The do while loop allow
its body to get executed one or more times. Remember that, the body
of the do while loop always gets executed at least once,but it is
imposible to determine in advance how many execution are
necessary.
Syntax:
do
{
Statement;
}while(expression);

WAP to read any number and count total digit in that number.
#include<stdio.h>
Void main()
{
long int num;
int count=0;
clrscr();
printf(“enter any number”);
scanf(“%d”,&num);
do
{
count++;
num = num/10;
}while(num>0);
printf(“\n total digit=%d”,ct);
getch();
}

20
Comparision of the loop control:
For loop While loop Do-while loop
1. The for loop is used to A while loop is used to
execute and repeat a execute and repeat a
statement block depending statement
on a condition which is
evaluated at the beginning
of the loop.
Example:
for( i=1; i<=10; i++)
{
s= s+ I;
p=p * I;
}

21
A function is a self contained block of statement that performs
a systematic task of some kind. we know that ,every C program
is the collection of several standard library function and user
defined function. main() is one of the user defined function
which indicates the beginning of the program. Function are
divided into two categories.
1) Standard library function or Inbuilt function or Predefined
function.
2) User defined function
Standard library function:
Standard library function are the function which are supplied
with the c compiler. The definition of these function are coded
in the standard library files having the extension.h(header file)
E.g: clrscr(),getch() etc.

User defined function:


User defined function are the function which are created by the
user of the computer sysyem(i.e programmer).

Why function
Function are very useful to read,write,debug and modify
complex programs.
The main advantages of using functions are:
1) Easy to read ,write and debug.
2) Easy to maintain and modify.
3) Small function tend to be self documentary and highly
readable.
4) The function can be called any number of times in any
place with different parameters.
22
How function works?
When the function is called(either standard library or user defined).the
program execution is transferred to the first statement in the called
function. The function is completed when it executes the last statement
in the function or when it encounter a return statement. After
execution of function completed then the control back to the main
function .
#include<stdio.h>
main()
{
message();
getch();
}
Void message()
{
printf(“ first c program”);
}
2)#include<stdio.h>
main()
{
add();
getch();
}
Void add()
{
int a,b,c;
printf(“enter value of a and b”);
scanf(“%d %d”,&a,&b);
c=a+b;
printf(“sum=%d”,c);
}

23
Defining function
Syntax:
return_type function_name(type agr1,type arg2…type argn)
{
local variable declare
statements();
return(expression); //optional
}

Example: float area(float radius)


{
Statement;
return(value);

}
When we use function in a program we declare
1)Function prototype
2) Function definition
3) Function call

Function prototype:
The calling function needs information about the called
function.so we declare function prototype after header file
define.
Example:
Void addition(int,int,int)

24
Function definition:
The function definition contain the whole definition of the
function,its return type ,its name,its arguments and what
the function do.Here we write all the definition about
function.
Example:
Void addition(int a,int b,int c)
{
int d;
d=a+b+c;
printf(“ sum value=%d”,d);
}

Function call:
The function definition describe what a function can do
but we call that function from main function that we called
function call.
Example:
addition(); // this function call from main

25
Write a program to add three number and print there sum .
#include<stdio.h>
void addition(int,int,int) // function prototype
void main()
{
int x,y,z;
clrscr();
printf(“ enter any three numbers”);
scanf(“ %d %d %d”,&x,&y,&z);
addition(a,b,c); // function call
getch();
}
void addition(int a,int b,int c) // function definition
{
int d;
d= a+ b+c;
printf(“ sum=%d”,d);
}
1)Every C program contains at least one function. And if the
program contains only one function,then that function must be
main().
2) You can declare any number of function in your c program.
3) To call a, just write the function name followed by
semicolon. if the function has arguments, then include the
arguments in parenthesis.
Example:
sum_two(a,b) //function call with arguments
print_hello(); //function call without arguments
4) Any function can be called from any other function.
26
Passing parameter to the function.
C supports following two types of parameters passing schemes
1) Sending the values of arguments OR call by value.
2) Sending the addresses of arguments OR call by reference.

1)Sending the values of arguments OR call by value.


When we pass argument through the calling function to the called function, the
value are passed through temporary variables all manipulation are done with
this temporary variables. The called function cannot access the actual memory
location of the original variable and therefore cannot change its value.
Example of call by value:
#include<stdio.h>
void swap( int ,int) // function prototype
void main()
{
int a=10,b=20;
clrscr();
printf(“\n The value before function call:”);
printf(“a=%d and b=%d”,a,b);
swap(a,b); // function call
printf(“\n The value after function call:”);
printf(“a=%d and b=%d”,a,b);
getch();
}
void swap(int x,int y) // function defination
{
x=x+10;
y=y+10;
}
The value before function call: a=10 and b=20
The value after function call: a=10 and b=20

27
2)Sending the addresses of arguments OR call by reference.
In call by reference the function is allowed acess to the actual memory
location of the variable passed as an argument and therefore can
change the value of the arguments of the calling function. There may
be cases their values of the arguments of the calling function have to be
change. It means changes made to the formal argument in the called
function have effect on the value of the actual argument in the calling
functions.
Example call by reference;
#include<stdio.h>
void swap(int *,int *) // function prototype
void main()
{
int a=10,b=20;
clrscr();
printf(“\n The value before function call:”);
printf(“a=%d and b=%d”,a,b);
swap(&a,&b); // function call
printf(“\n The value after function call:”);
printf(“a=%d and b=%d”,a,b);
getch();
}
swap( int *x, int *y) //function defination
{
*x=*x+10;
*y=*y+10;
}
The value before function call: a=10 and b=20
The value after function call: a=20 and b=10

28
Recursion:
In C any function can call itself( even main() can call itself).
When the function calls itself then the recursion occurred. A
function is said to be recurcive if a statement in a body of the
function cause itself each recursive function must specify an
exit condition for it to terminate otherwise it will go on
indefinite.
WAP to find factorial of a number using recursion function.
#include<stdio.h>
int fact(int);
void main()
{
int result,number;
clrscr();
printf(“ Enter a number:”);
scanf(“%d”,&number);
result=fact(number);
printf(“\n Factorial of %d is %d”,number,result);
getch();
}
int fact(int num)
{
int f;
if(n<=1)
return(1);
else
return( n * fact(n-1));
}

29
Point to remember about function:

 A function is self contained block of statement that perform a


systematic task of some kind.
 Standard library functions are the function which are supplied
with the C compiler.
 User defined function are very useful to read,write,debug and
modify complex programs.
 If the program contain only one function then it must be main()
 A function can be nested.
 By default every function returns an integer value.
 When a non prototyped function gets called, all chars get
converted to ints and all floats get converted to doubles.
 Using call by values ,changes made to the formal arguments in the
called function have no effect on the values of the actual
argument in the calling function.
 Using call by address, the changes made to the formal argument
in the called functions have effect on the value of the actual
argument in the calling function.
 When the function calls itself,recursion occurs.
Assignment:
1.Write a function cube(x) to find the cube of x, where x is the value
supplied by the user.
2.Write a function fib(n) which generates the fibonacci series of n
numbers. The series must be in following order 1 1 2 3 5 8……
3.Write function series1(n) and series(2) to evaluate the following two
series.
sum= 1 + 3 + 5 + ……………+n.
sum= 2+4+6+8+……………..+n.
4.Write a function big3(x,y,z) to find the biggest number among x,y,z.
5.Write a function to reverse the given integer( e.g 1234 should be
printed as 4321).Also write the main program.

30
Test
1) Write a program to read any five real number and print
their average.
2) Expalin about if else statement with general syntax.
3) Write different between for,while and do while loop.
4) Explain unary and binary operators in c.
5) Two variable a and b contain values 10 and 20.write a
program to interchange the content of a and b without
using a third variable.
6) Write a c program to print Armstrong number from 100 to
999.
7) Write a c program to accept an integer number between 1
and 9.write the value of the number in words.
8) Write a c program to evaluate the series
s=1+1/2+1/3+1/4+--------+ 1/N
9) Explain break,continue and exit.
10) Write a c program to generate and print the number
between 100 and 200 which are divisible by 3 but not
divisible by 4.

31
TEST

1)Write a c program to find the biggest of given three

32
ARRAY

An array is a collection of similar elements. These similar


elements could be all ints or floats or chars etc. Usually
the array of character is called a string. Whereas an array
of ints or floats is called simply an array. Remember that
all element of any given array must be if the same type.
we cannot have an array of 10 number, of which 5 are
ints and 5 are floats.
Array are widely used within programming from
different purpose such as sorting , searching etc.

Types of Array:
1) One dimensional
2) Two dimensional
3) Strings

One dimensional:
In one dimensional array the elements are store one by
one. The general form of one dimensional array is:
Syntax:
Datatype arrayname[size]
Example: int num[5]
Array initialization:
int num[ ]= {10,20,30,40,50}

33
It means num[0]=10 num[1]=20 num[2]=30 num[3]=40
num[4]=50
num[0] num[1] num[2] num[3] num[4]
10 20 30 40 50
1000 1002 1004 1006 1008
Insert value in an array:
The following code we use
for(i=0;i<5;i++)
scanf(“%d”, &num[i]);

Print value of array:


The following code we use
for(i=0;i<5;i++)
printf(“ %d”, num[i])

Array Declaration:
Arrays are declared using type declaration statement
with a maximum number of values accommodated in
them. consider the following example.
int x[50]
This statement declares an one dimensional array x
having 50 elements.

34
NOTE:
1) Array size to store values is always an integer;a
declaration like int x[n];is not permitted.
2) Subscript value beyond the array size should not be
used. This will not be detected by the compiler and it
leads to error during program execution. For
example, x[51] should not be used.
3) Array elements are stored in contiguous memory
location.
4) The size of the array should be mention while
declaring e.g: x[5].
5) Array element are always counted from 0 onwards.
6) Array element can be accessed using the position of
the element in the array. e.g. x[5] refer of ith
element.

35
Assignment
1)Write a c program to read a list if n integers. Count the
number of positive and negative integers. Also count the
number of zeroes in the list and display the result.
2)Write a C program to sort the element of an array in
descending order.
3)Given a matrix A if size 10 X 10 ,write a c program to find sum
of all positive and negative element.
4)Explain the syntax of array, one dimensional and two
dimensional.
5)Write a program to obtain transpose of a 4 X 4 matrix.The
transpose of a matrix is obtained by exchanging the element of
each row with the element of the corresponding column.
6)Write a program to pick up the largest number from any 5
row and 5 column matrix.

36
Sorting:
To arrange the element in array in a specific manner is called
sorting.There are so many technique to arrange element in a
specific manner.such as
a) Selection sort
b) Bubble sort
c) Insertion sort
d) Merge sort
e) Quick sort
f) Heap sort
g) Radix sort
Selection sort:
In this method find the first smallest element and stored this
element in the first position,then find the second number
stored in second position and so on.

37
Two dimensional array
So far, we have explored arrays with only one
dimension. It is also possible for always to have
two or more dimensions. The two dimension
array is also called a matrix.
Syntax:
Datatype arrayname[row size][coloumn size]
Eg:
int mat[5][3];
The following example show how to store roll
number and marks are obtained by the student.
#include<stdio.h>
Void main()
{
int stu[4][2];
int i,j;
for(i=0;i<=3;i++)
{
printf(“\n Enter roll number and marks:”);
scanf(“%d %d”,&stu[i][0],&stu[i][1]);
}
for(i=0;i<=3;i++)
{
printf(“\n %d %d”,stu[i][0[],stu[i][1]);
}
getch();

38
}

Initialising a 2-dimensional array:

int stu[4][2]={
{1234,56}
{1212,33}
{1434,80}
{1312,78}
}
Even we can initialize:
int stu[4][2]={1234,56,1212,33,1434,80,1312,78}

Note: It is important to remember that ,while initializing a 2D array, it


is necessary to mention the second (column) dimension, whereas the
first dimension (row) is optional.

Example:
int arr[2][3]={12,34,23,45,56,45};
int arr[ ][3]={12,34,23,45,56,45};
are perfectly valid but

int arr[2][3]={12,34,45,56,45,46};
int arr[ ][ ]={12,34,45,46,56};
are not valid

39
STRING

The way a group of integers can be stored in an integer array, similarly a


group of character can be stored in a character array. Character arrays
are many a time also called string.
A string can be define as a character type array which is terminated by
null character.

A string constant is a one-dimensional array of character terminated by a


null (“\0’).
For example:
char name[ ]={‘R’,’A’,’V’,’I’,’\0’}

Each character in the array occupies one byte of memory and the last
character is always ‘\0’.This terminating null(‘\0’)is important, because
it is the only way the function that work with a string can know where
the string ends.

C supports wide range of string function found in the header file


<string.h>

Function Description
strcpy (s1,s2) copies s2 into s1
strcat(s1,s2) Concatenation or append s2 on to
the end of s1
strlen(s) Return the length if s
strrev(s) Return reverse of string
strcmp(s1,s2) Return 0 if s1 and s2 are same <0 if
s1<s2,>0 if s1>s2.
strcmpi(s1,s2) same as strcmp just ignoring cases.

40
Note:
1) A string is nothing but an array of character terminated by
‘\0’.
2) Being an array, all the character of a string are stored in
contiguous memory location.
3) Though scanf( ) can be used to receive multi-word
strings,gets can do the same job in a clener way.
4) Both printf( ) and puts can handle multi-word string.
5) String can be operated upon using several standard library
function like strlen( ). Strcpy( ), strcat( ) and strcmp(
).which can manipulate string.

41
Structure

A structure contain number of data type grouped together .These


data types may or may not be of the same type. A structures has
the following general form.
Syntax:
struct<structure name>
{
structure element1;
structure element1;
structure element1;
structure element1;
………………….
}
Example:
Declaring a structure:
struct book
{
char name;
float price;
int pages;
}

This statement define a new data type called struct book. Each
variable of this data type will consist of a character variable
called name, a float variable called price and an integer variable
called pages.

42
After define the new structure data type then we create variable
of that data type
Struct book b1,b2,b3;
It means we create three variable of type book and each variable
hold three data type having char ,float and int.

Example we can write:


struct book
{
char name;
float price;
int pages;
};
struct book b1,b2,b3;

or

struct book
{
char name;
float price;
int pages;
}b1,b2,b3;

or
struct
{
char name;
float price;
int pages;
}b1,b2,b3;
43
Declaration with initialization:
We can declare primary variable and initialize value the same
way we can also be declared and initialize value to the structure
variable.
struct
{
char name;
float price;
int pages;
};
struct book b1={“Basic”,130.00,550};
struct book b2={“physics”,150.80,800};
struct book b3={0};

Note:
1) The declaration at the beginning of the program combines
dissimilar datatype into a single entity called struct book.
Here struct is a keyword, book is the structure name, and
the entities are structure element.
2) The closing brace in the structure type declaration must be
followed by a semicolon.
3) It is important to understand that a structure type
declaration does not tell the compiler to reserve any space
in memory. All a structure declaration does is, it define the
form of the structure.
4) Usually structure type declaration appears at the top of the
source code file,before any function or variable defined.

44
5) If a structure variable is initiated to a value {0}, then all its
element are set to value 0, as in b3 above. This is handy
way of initializing structure variables.

Accessing structure element:

To accessing structure element use a dot(.) operator.suppose we


access the element of above book example.we acess the struct
book element name,price and pages in a following way.

b1.pages;
b1.name;
b1.price;

How structure element are store:


Whatever the element of a structure , they are always stored in
contiguous memory location.
Example with address refer program.

Array of structure:
We know that array is a collection of elements of same data
type. we can declare array of structure where each element of
array is of structure type.
Array of structure can be declare as,

struct student s[5];

Explain with example struct4.c:

45
Union

Union is a derived datatype like structure it can also contain


member of different data type.The syntax and the variable
declaration are same as structure. To acess data member of
union is same as structure.
The main difference between structure and union the way
they allocate memory to its data member. In structure each data
member has its own memory whereas in union one data member
memory use by other data member.

Sizeof( ) of a union:
The size of a union is equal to the number of bytes occupied in
RAM by the largest data member in the union.
Example:
union student
{
int roll_no;
char sname[20];
}

The size of this union is equal to 20 bytes the largest data


member sname occupies 20 bytes in RAM.Thus union is use to
save the memory.
Syntax:
Union union-name
{
datatype member1;
datatype member2;
datatype member3;
}u;
46
Union declaration same as structure declaration only difference
we use keyword union here.when we acess the element of union
same as to acess the element of structure.
Example:
u.member1;
u.member2;

Difference between structure and an union;

Structure Union
1)The keyword struct is used to 2)The keyword union is used to
declare a structure. declare an union.
2)All data member in a 2)Only one data member is
structure are active at time. active at a time.
3)It is useful to declare a 3)It is useful in certain cases
compound data type to group where the user will select any
data members related to a one data member in the group
person or item. of data member.
4)It is commonly used in most 4) It is not commonly used.
of the application.

47
Pointer

A pointer is a variable which hold the address of another


variable. If one variable hold the address of another variable it
means pointer variable able to acess the value of another
variable.

Explain pointer1;

Write a C program to find the sum of the given n integers using an array.
#include<conio.h>
#include<stdio.h>
void main( )
{
int x[50 ],n,I,sum;
clrscr( );
printf(“ \n how many integers?”);
scanf(“%d”,&n);
/* code for enter values in array*/

48
for( i=0;i<n;i++)
{
printf(“\n Enter the %d value:”,i+1);
scanf(“%d”,&x[i]);
}
sum=0;
/* loop to find sum of all integers*/
for( i=0;i<n;i++)
{
sum=sum + x[i];
}
printf(“ \n sum of all integers=%d”,sum);
getch( );
}
output
How many integers? 5
Enter the 1 value: 36
Enter the 2 value: 45
Enter the 3 value: 52
Enter the 4 value: 44
Enter the 5 value: 62
Sum of all integers: 239

Write a c program to find the biggest of given n number.


#include<conio.h>
#include<stdio.h>
void main( )
{
int x[50],n,i,big;
clrscr( );
printf(“ \n How many numbers?”);
scanf(“%d”,&n);
49
for(i=0;i<n;i++)
{
printf(“\n Enter the %d value:”,i+1);
scanf(“%d”,&x[i]);
}
/* Assume first value as big*/
big=x[0];
for(i=1;i<n;i++)
{
if(x[i] > big)
big=x[i];
}
printf(“\n %d is the biggest number”,big);
}

How many integers? 5


Enter the 1 value: 36
Enter the 2 value: 45
Enter the 3 value: 52
Enter the 4 value: 44
Enter the 5 value: 62
62 is the biggest number.

Write a C program to find the smallest of given n number.


Write a C program to find sum of odd number and even number.
Write a C program to read the given n number. Find the sum of all positive and
negative number.
#include<conio.h>
#include<stdio.h>
void main( )
{
int x[50],psum,nsum,n,i;
clrscr( );
printf(“ \n How many values”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
50
{
printf(“\n Enter the %d value:”,i+1);
scanf(“%d”,&x[i]);
}
/* loop to find sum of all positive and negative number*/
psum = 0;
nsum = 0;
for(i=0;i< n;i++)
{
if(x[i]>0)
psum = psum + x[i];
else
nsum = nsum + x[i];
}
printf(“ sum of positive values= %d\n”,psum);
printf(“ sum of negative values= %d\n”,nsum);
getch( );
}
How many integers? 5
Enter the 1 value: 8
Enter the 2 value: -12
Enter the 3 value: -16
Enter the 4 value: 12
Enter the 5 value: -9
sum of positive number=20
sum of negative number= -37

WAP to read n elements and insert a new element at specific position


of linear array.
#include<conio.h>
#include<stdio.h>
void main( )
{
int x[50],n,i,pos,val;
clrscr( );
printf(“ \n How many values”);
scanf(“%d”,&n);
for(i=0;i<n;i++)

51
{
printf(“\n Enter the %d value:”,i+1);
scanf(“%d”,&x[i]);
}
printf(“\n Enter new value to insert:”);
scanf(“ %d”,&val);
printf(“\n Enter its position:”);
scanf(“%d”,&pos);
for(i=n-i; i>=pos-1;i--)
{
x[i+1]= x[i];
}
x[pos-1]=val;
printf(“ \n after insertion value:”);
for(i=0;i<n+1;i++)
{
printf(“\n the %d value is:”,i+1);
}
getch( );
}
WAP to read n element and delete a specific element from linear array.

Write a C program to search the key value in a set of n values. Print the
position of the key value if it is a successful search.
#include<conio.h>
#include<stdio.h>
void main( )
{
int arr[50],n,i,s;
clrscr( );
printf(“ \n How many values”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
52
{
printf(“\n Enter the %d value:”,i+1);
scanf(“%d”,&arr[i]);
}
printf(“Enter the key value to be searched : );
scanf(“%d”,&s);
/*loop to search the key value in the list*/
for( i=0;i< n;i++)
{
if( s== arr[i])
{
printf(“\n %d is available in %dth location”,s,i+1);
getch( );
exit( );
}
}
printf(“\n The key value %d is not present in the list”,s);
getch( );
}
How many integers? 5
Enter the 1 value: 8
Enter the 2 value: -12
Enter the 3 value: -16
Enter the 4 value: 12
Enter the 5 value: -9
Enter the key value to be searched: 12
12 is available in 4th position

WAP to create two array and size of array first and array second may be
different. Create third array that merge element of array first and second.
#include<stdio.h>
#include<conio.h>
void main( )
{
int arr1[50],arr2[50],arr3[100];
int i,n1,n2;
clrscr( );
printf(“ \n How many values in array 1”);

53
scanf(“%d”,&n1);
for(i=0;i<n1;i++)
{
printf(“\n Enter the %d value:”,i+1);
scanf(“%d”,&arr1[i]);
}
printf(“ \n How many values in array 2”);
scanf(“%d”,&n2);
for(i=0;i<n2;i++)
{
printf(“\n Enter the %d value:”,i+1);
scanf(“%d”,&arr2[i]);
}
for(i=0;i<n1;i++)
arr3[i]= arr1[i];
for( i=0;i<n2;i++)
arr3[n1+i]= arr2[i];
printf(“ After merging of array1 and array2 array 3 contents are: );
for(i=0;i<n1 + n2;i++)
printf(“ array3[%d]=%d”,i,arr3[i]);
getch( );
}

54

You might also like