Nothing Special   »   [go: up one dir, main page]

0% found this document useful (0 votes)
26 views25 pages

CCP Notes

C program notes for computer

Uploaded by

Anjali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views25 pages

CCP Notes

C program notes for computer

Uploaded by

Anjali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Programming For Problem Solving (BCS -101) By Dhananjay Sharma 1

UNIT-I
Introduction of Computer-
Computer System is an electronic data processing device which does the following:
• Accept and store an input data.
• Process the data input.
• And output the processed data in required format.

Block Diagram of a Digital Computer

Input Unit
This unit contains devices with the help of which we enter data into computer.This unit makes link between user and computer.
The input devices translate the human being information into the form understandable by computer.
CPU (Central Processing Unit)
CPU is considered as the brain of the computer. CPU perform all types of data processing operations.It stores data , intermediate
results and instructions(program).It controls the operation of all parts of computer.
CPU itself has following three components
• ALU(Arithmetic Logic Unit)
• Memory Unit
• Control Unit

Input Unit
This unit assists for reading data from the user’s end. Following are few of the important input devices which are used in Computer
Systems
• Keyboard
• Mouse
• Joy Stick
• Light pen
• Track Ball
• Scanner
• Graphic Tablet
• Microphone
• Magnetic Ink Card Reader(MICR)
• Optical Character Reader(OCR)
• Bar Code Reader
• Optical Mark Reader

Output Unit
Output unit consists of devices with the help of which we get the information from computer. This unit is a link between computer
and users.
Following are few of the important output devices which are used in Computer Systems
• Monitors
• Graphic Plotter
• Printer
Programming For Problem Solving (BCS -101) By Dhananjay Sharma 2
Operating System-
• An operating system is a program that acts as an interface between the software and the computer hardware.
• It is an integration set of specialized programs that are used to manage overall resources and operations of the computer.
• It is specialized software that controls and monitors the execution of all other programs that reside in the computer,
including application programs and other system software.
Examples: Windows XP/7/8 ..., Linux, UNIX, Android etc.

Functions of Operating System-


• Memory Management It keeps tracks of primary memory i.e what part of it are in use by whom, what part are not in use
etc.Allocates the memory when the process or program request it.
• Processor Management - Allocate the processor(CPU) to a process. Deallocate processor when processor is no longer
required.
• Device Management - Keep tracks of all devices.This is also called I/O controller. Decides which process gets the device
when and for how much time.
• File Management - Allocates the resources. De-allocates the resource. Decides who gets the resources.
• Security - By means of passwords & similar other techniques, preventing unauthorized access to programs & data.
• Networking -In the Internet age, networking capabilities of operating systems are very important. Networking capabilities
can be either with an outside computer as in accessing the Internet or computer to computer as in a large mainframe
operation. The operating system will coordinate all of this below the surface without the user even being aware it is
happening.

Generations of Computer Programming Languages


1. First Generation Language (Machine language)
2. Second Generation language (Assembly Language)
3. Third Generation languages (High-Level Languages)
Examples: C++, C, Java Visual Basic

4. Fourth generation language (Very High-level Languages)


Examples: HTML, CSS, PHP,Python, SQL

5. Fifth generation language (Artificial Intelligence Language)


Examples: mercury, prolog, OPS5

6. Sixth generation language (No Code & Visual Development)


Programming For Problem Solving (BCS -101) By Dhananjay Sharma 3
Memory
A memory is just like a human brain. It is used to store data and instruction. Computer memory is the storage space in computer
where data is to be processed and instructions required for processing are stored.

Memory Hierarchy

Memory is primarily of three types


• Cache Memory
• Primary Memory/Main Memory
• Secondary Memory

Cache Memory
Cache memory is a very high speed semiconductor memory which can speed up CPU. It acts as a buffer between the CPU and
main memory.
It is used to hold those parts of data and program which are most frequently used by CPU. The parts of data and programs are
transferred from disk to cache memory by operating system, from where CPU can access them.

ADVANTAGE
• Cache memory is faster than main memory.
• It consumes less access time as compared to main memory.
• It stores the program that can be executed within a short period of time.
• It stores data for temporary use.

DISADVANTAGE:
• Cache memory has limited capacity.
• It is very expensive.

Primary Memory (Main Memory)


Primary memory holds only those data and instructions on which computer is currently working. It has limited capacity and data get
lost when power is switched off.
It is generally made up of semiconductor device. These memories are not as fast as registers. The data and instruction required to
be processed earlier reside in main memory. It is divided into two subcategories RAM (Random Access Memory) and ROM (Read
Only Memory).

Characteristic of Main Memory


• These are semiconductor memories.
• It known as main memory.
• Usually volatile memory.
• Data is lost in case power is switch off.
• It is working memory of the computer.
Programming For Problem Solving (BCS -101) By Dhananjay Sharma 4
• Faster than secondary memories.
• A computer cannot run without primary memory.

Secondary Memory
This type of memory is also known as external memory or non-volatile. It is slower than main memory. These are used for storing
Data/Information permanently. For example: Hard Disk, CD-ROM,DVD etc.

Characteristic of Secondary Memory


• These are magnetic and optical memories.
• It is known as backup memory.
• It is non-volatile memory.
• Data is permanently stored even if power is switched off.
• It is used for storage of the data in the computer.
• Computer may run without secondary memory.
• Slower than primary memories.
Programming For Problem Solving (BCS -101) By Dhananjay Sharma 5

Flow Chart
A flow chart is a graphical or symbolic representation of a process. Each step in the process is represented by a different symbol
and contains a short description of the process step. The flow chart symbols are linked together with arrows showing the process
flow direction. The symbols of flowchart are-

Algorithm
To make a computer do anything, you have to write a computer program. To write a computer program, you have to tell the
computer, step by step, exactly what you want it to do. The computer then "executes" the program, following each step
mechanically, to accomplish the end goal.
When you are telling the computer what to do, you also get to choose how it's going to do it. That's where computer algorithms
come in. The algorithm is the basic technique used to get the job done.
Every algorithm should have the following five characteristics:
1. Input
2. Output
3. Definiteness
4. Effectiveness
5. Termination
Programming For Problem Solving (BCS -101) By Dhananjay Sharma 6
UNIT-II
Introduction of C Language-
1. C was developed by Denish Ritche in 1972 at AT & T Bell Lab.
2. It is a high level programming language, some times called middle level programming language.
3. It is a case sensitive language.
4. The extention of C program must be .c or .cpp.
5. C uses compiler for converting high level code into machine level code.

A Simple C Program -
#include<stdio.h>
int main()
{
printf("Hello Rishab");
printf("\nWelcome in C Language");
return 0;
}

Step By Step Demostration of the program -


1. #include is known as preprocessor directive and it attach the given header file with our program at compile time.
2. main() function indicates that program is begin now.
4. {} (curly braces) indicates a block
5. printf() is also a library function defined inside stdio.h which print the givcen message on he screen
6. \n changes a new line
7. ;(semi colon) indictes the compiler that statement is end now

Que- WAP which genertates the following output-


Welcome Friends
I The World of Programming
Hope you will enjoy

Tokens- The smallest individual units of a program are known as tokens.It consist the following elements-
1. Identifiers
2. Constant
3. Keywords
4. DataType
5. Operators

1. Identifiers- The name of any programming element is known as identifiers. like name of variable, function etc.
2. Constant- They are the fixed values which did not change during execution of a program.
like
10,20,30
"ram","shyam"
3. Keywords- They are the reserve words which implements any particular meaning in your program. there are 32
keywords in c language.
like -
int,for,if,while,do etc

4. Datatype- It specifies the type of a variable.


Variable- They represent a memory location where we can put any value according to their datatype.
Syntax
datatype variable_name;
5. Opeartors- They are the symbols which perform any particular operation with their operands. They could be
classified into following categories-
1. Assignment Operator
2. Arithmetical Operator
3. Relational Operator
4. Logical Operator
5. Increment/Decrement Operator
6. Conditional Operator
7. Shorthand Operators
8. Bitwise Operators
9. sizeof() operators
Programming For Problem Solving (BCS -101) By Dhananjay Sharma 7
1. Assignment Operator- The equals to sign(=) is known as assignment operator and it assign the value from right to
left.
Syntax
variable=value;
<--------------------
ex
int a;
a=10;
Que- WAP for swapping the value of two variables with each other.
a=10;
b=20

2. Arithmetical Operator- They are used for performing the arithmetic operations. They are-
Operator Meaning
+ Add
- Subtract
* Multiply
/ Divide
% Modulo Division

Que- WAP for adding two values.


Que- WAP for calculaing the area of rectangle
Que- WAP for calculating area of a circle.
Que- WAP which contains a number having three digits & write a program for reversing the digits of number.

scanf() function - This function is used for reading any value at run time-
Syntax
scanf("format_specifiers",&variable_list)
Format_Specifiers
%c - Characters
%d - Integer
%f - Float
%lf - Double
%s - String
%x - Hexadecimal
%o - Octal
%u - Unsigned Integer

Que- Read two values & Add Them.


Que- Read marks of a student in P,C,M and calculate their total percetnage & division
Que- Read Principal amount,rate & Time & Calculate simple intrest.
si=p*r*t/100

3. Relational Operator- They are used for comparing two or more than two variables. they return 1 if condition is true
otherwise return 0. They are-
Operator Meaning
< is less than
<= is less than or equals to
> is greater than
>= is greater than or equals to
== is equals to
!= is not equals to

4. Logical Opeartors- They are used for working with more than one conditions. They are-
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Programming For Problem Solving (BCS -101) By Dhananjay Sharma 8
5. Increment/Decrement Operator- The ++ sign is known as increment operator and -- sign is known as decrement
operator. ++ increase 1 into its operand and -- decrease 1.
Here is two term known as-
Pre Incremenet/Decrement =>++/--Operand => First increase or decrease then perform operation
Post Incremenet/Decrement =>Operand++/-- => First perform operation then increase or decrease
6. Conditional Operator- It is also known as ternary operator and it used as a substitute of if else statement.
Syntax
condition?true statement:false statement;
Que- Check given number is even or odd?
Que- Read two values & print the largest.
7. Shorthand Operators- They are tricky method for working with operators, like
+=
-=
*=
/=
num=5
num=num+2; => num+=2
num=num*5;=>num*=5;

8. sizeof() operators- It returns how much memory space (bytes) is occupied by variable in memory.
9. Bitwise Operators- The bitwise operators works on binary bits.
Operator Meaning
<< right shift
>> left shift
& bitwise AND
| bitwise OR
Programming For Problem Solving (BCS -101) By Dhananjay Sharma 9
UNIT-III
Decision Making Statements- They are used for making the decision inside your program. The Decision Making
Statements are-
1. if statement
2. switch statement

1. if statement- We can use different variations of if statement, These are-


a. if else statement
b. if else if ladder statement
c. netsed if statement

a. if else statement- if we have a condition & their are two aspect of the condition, first for true and second for
false, then we use such type of statement.
Syntax
if(condition)
{
true statement block
}
else
{
false statement block
}
Que- Check given number is even/odd.
Que- Check The Triangle is equilateral or not?
Que- Read age of a person & print whether he/she can vote or not?
Que- Read basic salary & calculate the allowances like the following-
if basic>5000 then

ta=5% of basic
da=10% of Basic
hra=6% of Basic
pf=15% of Basic
gross_sal=basic+ta+da+hra;
net_sal=gross - pf
if basic<=5000 then

ta=2% of basic
da=5% of Basic
hra=3% of Basic
pf=7% of Basic
gross_sal=basic+ta+da+hra;
net_sal=gross - pf

b. if else if ladder statement- if we have more than one conditions then we can use if else if ladder
statement.
Syntax
if(condition-1)
statement-1
else if(condition-2)
statement-2
_______________
_______________
else if(condition-n)
statement-n
else
default statement
Que- Read 3 values & print the largest one.
Que- WAP for calculating the electric bill. Read the value of current reading & last reading and calculate unit ,
rate and amount like the following-
unit=cr-lr;
rate
if unit>1000 then rate=2
Programming For Problem Solving (BCS -101) By Dhananjay Sharma 10
if unit is b/w 500 to 1000 then rate=3
if unit<500 then rate=4
amount=unit*rate

Que- Read marks of a students in physics, chemistry & math & calculate and print their total , percentage &
division.

c. nested if statement - if, if statement contains one or more than one if statement then this term is known as
nested if statement.
Syntax
if(condition)
{
______________
______________
if(condition)
{
---------------
----------------
}
}
Que- Read 3 values & print the largest one.

switch case statement- It is also a decision making statement.It works faster than if statement, but the
disadvantages is that it did not support logical and relational operator.
Syntax
switch(expression)
{
case value-1:
statement-1;
break;
case value-2:
statement-2;
break;
_____________________
_____________________
case value-n:
statement-n;
break;
default:
default statement
}
Que- Read day number & print the day name.
Que- Read two values & then print the following menu-
1. Add
2. Subtract
3. Multiply
4. Divide
then read the choice(1-4) & print the result according to choice.
Programming For Problem Solving (BCS -101) By Dhananjay Sharma 11
Loop – Loop statements are used for repeating a part of program during finite or infinite times. It is also known as
iterative or repetitive statement. It could be classified into two categories-
a) Entry Controlled Loop
b) Exit Controlled Loop

a) Entry Controlled Loop – This type of loop first checks the condition & if condition is satisfied then execute the
body of the loop. “for loop” & “while loop” belongs to this category.
b) Exit Controlled Loop – This type of loop execute at least one time either condition is satisfied or not. “do while
loop” belongs to this category.

for loop : It is an entry controlled loop & the general form of this loop will be-

for(initialization ; test condition ; increment/decrement)


{
body of the loop
}

Important Questions –
Que- 1: WAP for printing the table of given number. Que-2 : WAP for calculating the factorial of given
#include<stdio.h> number.
int main() #include<stdio.h>
{ int main()
int num,i; {
printf("Enter Number :"); int num,i,fact=1;
scanf("%d",&num); printf("Enter Number :");
for(i=1;i<=10;i++) scanf("%d",&num);
{ for(i=num;i>=1;i--)
printf("%d\n",num*i); {
} fact=fact*i;
return 0; }
} printf("\nFactorial : %d",fact);
return 0;
}
Que- 3: WAP for printing the Fibonacci series up to Que- WAP which read base number(x) & power
the given limit. number(n) & calculate xn.
#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int a=0,b=1,c,i,limit; int x,n,res=1,i;
printf("Enter Limit Number :"); clrscr();
scanf("%d",&limit); printf("Enter Base Number :");
if(limit>=2) scanf("%d",&x);
{ printf("Enter Power Number :");
printf("%d\n%d\n",a,b); scanf("%d",&n);
for(i=1;i<=limit-2;i++) for(i=1;i<=n;i++)
{ {
c=a+b; res=res*x;
printf("%d\n",c); }
a=b; printf("\nResult : %d",res);
b=c; return 0;
} }
}
return 0;
}

Exercise on for loop-


Que-1 : WAP for printing 1 to 10.
Qie-2 : WAP for printing 10 to 1.
Que-3 : WAP for printing number & their square up to the given limit.
Que-4 : WAP for printing the list of even numbers between 1 to 100.
Programming For Problem Solving (BCS -101) By Dhananjay Sharma 12
Que-5 : WAP
while loop : It is also an entry controlled loop & the general form of this loop will be-

while(condition)
{
body of the loop
}

Important Questions –
Que- WAP for reversing the digits of a given number. Que – WAP for printing the sum & average of digits,
#include<stdio.h> of a given number.
int main() #include<stdio.h>
{ int main()
int num,r,rev=0; {
printf("Enter Number :"); int num,sum=0,avg,r,nod=0;
scanf("%d",&num); clrscr();
while(num>0) printf("Enter Number :");
{ scanf("%d",&num);
r=num%10; while(num>0)
rev=rev*10+r; {
num=num/10; r=num%10;
} sum=sum+r;
printf("\nReverse : %d",rev); nod++;
return 0; num=num/10;
} }
avg=sum/nod;
printf("\nSum of Digits : %d",sum);
printf("\nAverage of Digits : %d",avg);
return 0;
}
Que- WAP which read a number & check whether Que- WAP which read a number & check whether
given number is Palindrome or not? given number is Armstrong or not?
#include<stdio.h> #include<stdio.h>
int main() #include<conio.h>
{ void main()
int num,r,rev=0,n; {
printf("Enter Number :"); int num,r,s=0,n;
scanf("%d",&num); printf("Enter Number :");
n=num; scanf("%d",&num);
while(num>0) n=num;
{ while(num>0)
r=num%10; {
rev=rev*10+r; r=num%10;
num=num/10; s=s+(r*r*r);
} num=num/10;
if(n==rev) }
printf("\nNumber is Palindrome"); if(n==s)
else printf("\nNumber is Armstrong");
printf("\nNumber is Not Palindrome"); else
return 0; printf("\nNumber is Not Armstrong");
} return 0;
}
Exercise on while loop-
Que-1: WAP for printing the largest digit of a given number.
Que-2: WAP for calculating the factorial of a given number using while loop.
Que-3: WAP which count how many even & odd digits in a given number.
do while loop : it is an exit controlled loop, means it will execute at least one time either condition is satisfied or not.
The general form will be-
Difference between while loop & do while loop
while Loop do while loop
Programming For Problem Solving (BCS -101) By Dhananjay Sharma 13
1. it is entry controlled loop. 1. it is an exit controlled loop.
do{ 2. it first check the condition & if 2. it execute the body of loop either
body of the loop satisfied then execute body of loop. condition is satisfied or not?
}while(condition); 3. Most frequently used. 3. Occasionally used.

Example of do while loop break Statement- This statement is used for terminating
#include<stdio.h> the flow of loop as per the given condition.
int main() Example
{ #include<stdio.h>
int a,b,ch; int main()
do{ {
printf("\nEnter First Number :"); int i;
scanf("%d",&a); clrscr();
printf("Enter Second Number :"); for(i=1;i<=10;i++)
scanf("%d",&b); {
printf("Sum : %d",a+b); printf("%d\n",i);
printf("\nPress 1 For Continue The if(i==5)
Program :"); break;
scanf("%d",&ch); }
}while(ch==1); getch();
printf("\nBye-Bye"); }
return 0;
}

Que- Check given number is prime or not? continue statement- This statement is used for ignoring
#include<stdio.h> the sequence of loop.
int main() #include<stdio.h>
{ int main()
int num,i,isprime=0; {
printf("Enter Number :"); int i;
scanf("%d",&num); clrscr();
for(i=2;i<=num-1;i++) for(i=1;i<=10;i++)
{ {
if(num%i!=0) if(i>=5 && i<=8)
isprime=1; continue;
else printf("%d\n",i);
{ }
isprime=0; return 0;
break; }
}
}
if(isprime==1)
printf("\nGiven Number is Prime");
else
printf("\nGiven Number is not Prime");
}
Exercise
Que- WAP which read three numbers & print the LCM of these numbers.
Nesting of loop statement- if loop statement contains one or more than one another loop statement into its body then
this term is known as nesting of loop statement.
Que-1: WAP for printing the table of 2 to Exercise-
10. Que-1: WAP for printing the list of prime nos between 1 to 100.
#include<stdio.h> Que-2: WAP for printing the list of Palindrome numbers between 1 to
int main() 1000.
{ Que-3: Write programs for printing the following structures-
int i,j;
Programming For Problem Solving (BCS -101) By Dhananjay Sharma 14
1 1 A 1 1
for(i=2;i<=10;i++) 12 01 AB 23 12
{ 123 010 ABC 456 123
for(j=1;j<=10;j++) 1234 1010 ABCD 78910 1234
{ 12345 10101 ABCDE 12345
printf("%d\t",i*j); 12345 ***** 1 1 12345
} 1234 123 121 1234
****
printf("\n"); 123 12345 12321 123
} ***
12 ** 1234567 1234321 12
return 0; 1 123456789 123454321 1
} *

Array
Array – It is the collection of same type of data type that shares a common name. It is also known as subscripted
variable. It could be classified into following categories-
a) Single Dimensional Array
b) Double Dimensional Array
a) Single Dimensional Array – This type of array contains single rows with multiple columns. The general form
of this type of array will be-
datatype arrayname[size];
ex. Index starts from
0
Int arr[5]; to size-1

Arr[0] arr[1] arr[2] arr[3] arr[4]


Important Questions –
Que-1: Read 5 values using array & print them. Que-2: WAP for searching an element from an array.
#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int i,arr[5]; int arr[5];
clrscr(); int i,found=0,num;
printf("Enter Five Values \n"); printf("Enter Five Values \n");
for(i=0;i<=4;i++) for(i=0;i<=4;i++)
{ {
scanf("%d",&arr[i]); scanf("%d",&arr[i]);
} }
printf("\nThe Given Values are \n"); printf("\nEnter Number For Search :");
for(i=0;i<=4;i++) scanf("%d",&num);
{ for(i=0;i<=4;i++)
printf("%d\n",arr[i]); {
} if(arr[i]==num)
return 0; {
} found=1;
break;
}
}
if(found==1)
printf("\nNumber Exist in Array");
else
printf("\nNumber Not Exist in Array");
return 0;
}
Que-3: WAP for printing the largest element from an Que-4: WAP for sorting the elements of an
array. array.(Selection Sort).
#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int arr[5]; int arr[]={190,20,300,40,50};
int i,max; int i,j,temp;
clrscr(); clrscr();
printf("Enter Five Values \n"); printf("Before Sorting Elements are \n");
for(i=0;i<=4;i++) for(i=0;i<=4;i++)
Programming For Problem Solving (BCS -101) By Dhananjay Sharma 15
{ {
scanf("%d",&arr[i]); printf("%d\n",arr[i]);
} }
max=arr[0]; for(i=0;i<=4;i++)
for(i=0;i<=4;i++) {
{ for(j=i+1;j<=4;j++)
if(max<arr[i]) {
max=arr[i]; if(arr[i]>arr[j])
} {
printf("\nLargest Value is : %d",max); temp=arr[i];
return 0; arr[i]=arr[j];
} arr[j]=temp;
}
}
}
printf("\nAfter Sorting Elements are \n");
for(i=0;i<=4;i++)
{
printf("%d\n",arr[i]);
}

return 0;
}
Exercise on Single Dimensional Array-
Que-1: WAP for printing the Binary Equivalent of given integer value.
Que-2: WAP for counting how many even & odd elements in an array.
Que-3: WAP for printing the prime elements from an array.

b) Double Dimensional Array – This type of array contains multiple rows with multiple columns. The general
form of this type of array will be-
Datatype ArrayName[Rows][Cols];
Ex.
int mat[3][3];
mat[0][0] mat[0][1] mat[0][2]
mat[1][0] mat[1][1] mat[1][2]
mat[2][0] mat[2][1] mat[2][2]
Important Questions -
Que-1: WAP which read 9 values for a matrix of 3*3 & Que-2: WAP for multiplying two matrixes.
print the elements in matrix form. #include<stdio.h>
#include<stdio.h> int main()
int main() {
{
int a[3][3],b[3][3],c[3][3],i,j,k;
int mat[3][3],i,j; printf("\nEnter Nine Numbers For First Matrix
printf("\nEnter Nine Numbers For Matrix of 3*3\n"); \n");
for(i=0;i<=2;i++) for(i=0;i<=2;i++)
{ {
for(j=0;j<=2;j++) for(j=0;j<=2;j++)
{ {
scanf("%d",&mat[i][j]); scanf("%d",&a[i][j]);
} }
} }
printf("\nMatrix is \n"); printf("\nEnter Nine Numbers For Second \n");
for(i=0;i<=2;i++) for(i=0;i<=2;i++)
{ {
for(j=0;j<=2;j++) for(j=0;j<=2;j++)
{ {
printf("%d\t",mat[i][j]); scanf("%d",&b[i][j]);
} }
printf("\n"); }
} for(i=0;i<=2;i++)
return 0; {
} for(j=0;j<=2;j++)
Programming For Problem Solving (BCS -101) By Dhananjay Sharma 16
{
c[i][j]=0;
for(k=0;k<=2;k++)
{

c[i][j]=c[i][j]+(a[i][k]*b[k][j]);
}
}
printf("\n");
}
printf("\nFirst Matrix is \n");
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
printf("%d\t",a[j][i]);
}
printf("\n");
}
printf("\nSecond Matrix is \n");
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
printf("%d\t",b[j][i]);
}
printf("\n");
}
printf("\nMultiply of Both Matrix is \n");
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
printf("%d\t",c[j][i]);
}
printf("\n");
}
return 0;
}

Exercise on Double Dimensional Array-


Que-1: WAP for transposing a matrix.
Que-2: WAP for adding two matrixes.
Programming For Problem Solving (BCS -101) By Dhananjay Sharma 17
String Handling
String is an array of characters, for declaring a string variable we will use the following syntax-
char variablename[size];
ex.
char n[35];
Que- Read A name & print it with hello message. Que- Read A name & print it with hello message.
#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
char n[40]; char n[40];
printf("Enter Name :"); printf("Enter Name :");
scanf("%s",n); gets(n);
printf("Hello %s",n); printf("Hello %s",n);
return 0; return 0;
} }
Note- the scanf() function read a word, not a sentence. Note- the gets() function read a complete sentence.

Note- When we press enter key for terminating the string the compiler automatically placed a Null Character(‘\0’) at the
last, which indicates string is end now, like-
U N I T E D ‘\0’
Important Questions
Que-1: Read a name & print the length of name. Que-2: Read a name & print characters of name in
#include<stdio.h> reverse form.
int main() #include<stdio.h>
{ int main()
char n[40]; {
int i; char n[40];
printf("Enter Name :"); int i,j;
gets(n); printf("Enter Name :");
for(i=0;n[i]!='\0';i++) gets(n);
{} for(i=0;n[i]!='\0';i++)
printf("\nLength is : %d",i); {}
return 0; printf("\nThe Reverse is :");
} for(j=i-1;j>=0;j--)
{
printf("%c",n[j]);
}
return 0;
}
Que-3: Check given string is palindrome or not? palin=0;
#include<stdio.h> break;
int main() }
{
char n[40]; }
int i,j,palin=0; if(palin==1)
printf("Enter Name :"); printf("String is Palindrome");
gets(n); else
for(i=0;n[i]!='\0';i++) printf("String is not Palindrome");
{} return 0;
i=i-1; }
for(j=0;n[j]!='\0';j++,i--)
{
if(n[j]==n[i])
palin=1;
else
{
Programming For Problem Solving (BCS -101) By Dhananjay Sharma 18
Important String Handling Functions: String handling functions are defined inside string.h header file, they provide
the facility for processing string easily. The important string handling functions are-
1. strlen() – this function contains a string as argument & return the length of the string.
2. strcpy() – this function contains two strings as argument & copies the value of second argument into
first argument( string variable).
3. strcat()- this function contains two strings as argument & returns the concatenation of both string.
4. strcmp()- this function contains two strings as argument & return 0 if both strings are equal otherwise
return a non zero value.

Functions
Functions are also known as sub programs, they are the named block which perform any particular action when they
are called. Functions could be classified into two categories, they are-
a) Library Functions
b) User Defined Functions
a) Library Functions- They are built in functions & provide by ‘C’ standard library. They are defined inside any
particular header file, only we call these functions without knowing the background details. Some most
frequently used library functions are – printf(), scanf(), getch(), clrscr(), strlen(), sqrt() etc.
b) User Defined Functions- The functions which are defined by the user as per the requirement are known as
user defined functions. The main objectives for creating an UDF are-
i. Dividing a big problem into different small modules.
ii. Implementing the concept of reusability
iii. Increasing the readability of the program
iv. Decreasing the complexity of the program.
v. Scalability
The general form of an UDF will be-
return_type function_name(argument_list)
{
body of the function
}
return_type- It specifies which type of value will be return by the function. Here we specify the data type of
return value, if there is nothing to return then write void here.
function_name- Here we specify the name of function, it may be any valid name.
argument_list- Here we specify the name & type of the return value. If there is no argument then you can
either leave it blank or write void here.
body of the function- Here we specify the task of the function.
Note – During creation of an UDF we must follow the following three steps-
1) Function Declaration or Function Prototype – Here we specify the signature of the function. Like-
void demo(void)// function name demo contains no argument & also not return a value
void demo(int a,int b)// function name demo contains two argument but not return a value
int demo(int a)// function name demo contains one argument and return a value
It take place either outside the main() or inside the main() function.
2) Function Calling – Here we invoke the function for performing the actual task. It take place inside the
main() function or any other function.
3) Function Definition- Here we specify that what will be actually perform by the function. It take place
outside the body of main() function or any other function.
Types of User Defined Function – An UDF could be classified into following categories-
a) Function with no argument & no return value
b) Function with argument but no return value
c) Function with argument & return value
Programming For Problem Solving (BCS -101) By Dhananjay Sharma 19
a) Function with no argument & no return value- This type of functions are used for performing the static
operations. They not contain any argument as well as not return any value at the calling position. When we
call these function the control transfer on there definition & after performing the task they return on calling
position.
Example- WAP which generate the following output- Exercise :
*********************************************************
Welcome Que-1: create a function named info() which print your nam
********************************************************* & address when it will called.
*********************************************************
#include<stdio.h>
void line(void);
int main()
{
line();
printf("\n\t\t\tWelcome\n");
line();
line();
return 0;
}
void line(void)
{
int i;
for(i=1;i<=70;i++)
{
printf("*");
}
printf("\n");
}
b) Function with argument but no return value- This type of functions are used for performing the dynamic
operations according to given value. They contain argument but not return any value at the calling position.
There are two concepts about the arguments they are-
i. Real Argument- The arguments which are passed at the time of function calling are known
as real argument.
ii. Formal Argument- The arguments which are passed at the time of function definition are
known as formal argument. The type & order of formal argument must be same as the real
argument but the name must be differ.
Example- Create a function named as table() which contains a Exercise :
number as argument & print the table of that number. Que-1: Create a function named reverse()
#include<stdio.h> which contains a number as argument & print
void table(int); the digits of number in reverse form.
int main() Que-2: Create a function named as fibo()
{ which contains a limit number as argument &
int num; print the Fibonacci series up to the given limit.
printf("Enter Number :");
scanf("%d",&num);
table(num);
return 0;
}
void table(int n)
{
int i;
for(i=1;i<=10;i++)
{
printf("%d\n",n*i);
}
}

c) Functions with argument & return value- This type of functions are used for performing the dynamic
operations & they return a value at the calling position with the help of return keyword.
Example: Create a function named as fact() which Exercise :
contains a number as argument & return the factorial of Que-1: Create a function named as power() which
that number. contains base number x & power number n & return x to
Programming For Problem Solving (BCS -101) By Dhananjay Sharma 20
#include<stdio.h> the power n.
int fact(int); Que-2: Create a function named as max() which contains
int main() three numbers as argument & return the largest value.
{
clrscr(); Que-3: Create a function named as prime() which
int num,res; contains a number as argument & return 1 if number is
printf("Enter Number :"); prime otherwise return 0.
scanf("%d",&num);
res=fact(num);
printf("\nFactorial : %d",res);
return 0;
}
int fact(int n)
{
int i,f=1;
for(i=n;i>=1;i--)
{
f=f*i;
}
return f;
}

Recursion: When a function called itself inside its own body then this term is known as recursion & this type of
functions are known as recursive functions. It is used for repeating any particular task.
Example : Create a recursive function named as fact() Exercise :
which contains a number as argument & return the Que- Create a recursive function named as reverse()
factorial of that number. which contains a number as argument & print the digits of
number in reverse form.
#include<stdio.h> Que- Create a recursive function named as fibo() which
int fact(int); print the Fibonacci series up to the given limit.
int main()
{
int num,res;
printf("Enter Number :");
scanf("%d",&num);
res=fact(num);
printf("\nFactorial : %d",res);
return 0;
}
int fact(int n)
{
if(n==1)
return 1;
else
return n*fact(n-1);
}
Programming For Problem Solving (BCS -101) By Dhananjay Sharma 21
Structure
Structure- Structure is a technique by which we can create a User Defined Data Type. Structure allows you for create
a complex data type in which more than one variable with different data type are encapsulated. The general form of a
structure will be-
struct structurename Example
{ struct stu
member-1; {
member-2; char name[30];
___________________ int age;
___________________ char address[50];
member-n; };
};

Creating variable of structure – for creating variable of structure we will follow the following syntax-
Syntax
Struct structurename variable1,variable2,…….
Ex.
Struct stu s;
For accessing the members of structure we will use the member ship operator (.).
Example: Read name, age & address of a student & Array of Structure: Like any other data type we can also
print them. declare the variable of structure as an array like the
#include<stdio.h> following-
struct stu struct structurename variablename[size];
{
char name[30]; for example if we declare the variable of stu structure as
int age; an array then it will allocate the memory like the following
char addr[50]; –
};
int main() struct stu s[5];
{ name name name name name
struct stu s; age age age age age
printf("Enter Name :"); address address address address address
gets(s.name); s[0] s[1] s[2] s[3] s[4]
fflush(stdin);
printf("Enter Age :");
scanf("%d",&s.age);
fflush(stdin);
printf("Enter Address :");
gets(s.addr);
fflush(stdin);
printf("\nName : %s",s.name);
printf("\nAge : %d",s.age);
printf("\nAddress : %s",s.addr);
return 0;
}
Programming For Problem Solving (BCS -101) By Dhananjay Sharma 22

Array of Structure Example : Excersice:


Example : Read maks of 5 student in physics, Que-1: Write a program for storing the basic details
chemistry & math & calculate and print their total, like Name, Course, Branch of 5 students & print
percentage & division. them.
Que-2: Design a structure named as Date which
#include<stdio.h> contains three integer members date, month & year.
#include<string.h> Write a program which read two dates & check
struct stu whether both are equals or not?
{
char name[30],div[30];
int p,c,m,tot,per;
};
int main()
{
struct stu s[5];
int i;
for(i=0;i<=4;i++)
{
printf("\nEnter Record Number : %d\n",i+1);
printf("Enter Name :");
gets(s[i].name);
fflush(stdin);
printf("Enter Marks of Physics :");
scanf("%d",&s[i].p);
fflush(stdin);
printf("Enter Marks of Chemistry :");
scanf("%d",&s[i].c);
fflush(stdin);
printf("Enter Marks of Math :");
scanf("%d",&s[i].m);
fflush(stdin);
s[i].tot=s[i].p+s[i].c+s[i].m;
s[i].per=s[i].tot/3;
if(s[i].per>=60)
strcpy(s[i].div,"First");
else if(s[i].per>=45 && s[i].per<60)
strcpy(s[i].div,"Second");
else if(s[i].per>=33 && s[i].per<45)
strcpy(s[i].div,"Third");
else
strcpy(s[i].div,"Failed");
}
for(i=0;i<=4;i++)
{
printf("\nRecord Number : %d\n",i+1);
printf("\nName : %s",s[i].name);
printf("\nTotal : %d",s[i].tot);
printf("\nPercetage : %d",s[i].per);
printf("\nDivision : %s",s[i].div);

printf("\n*******************************************\n");
}
return 0;
}
Programming For Problem Solving (BCS -101) By Dhananjay Sharma 23
Pointer
Pointers are used for creating a memory variable which points the address of some other variables. For creating a
pointer variable we will use the following syntax-
datatype *variablename;
ex.
int *p;
in pointers we use two types of operators these are –
* - value at the address
& - address at the value
Basic Example: Pointer with Array (Pointer Arithmetic): Remember
#include<stdio.h> that a pointer variable could not hold the address of an
int main() array. It only reference the base address of an array like
{ the following –
int n,*p;
n=10; Ex.
p=&n; int arr[5];
printf("\nValue & Address Through Variable \n"); int *p;
printf("\nValue : %d",n); p=arr;
printf("\nAddress : %u",&n); 1024 1026 1028 1030 1032
printf("\nValue & Address Through Pointer\n"); 10 20 30 40 50
printf("\nValue : %d",*p);
printf("\nAddress : %u",p);
return 0; *p
} here by using ++ we can move on next location & by
using -- we can move on previous location. This term is
known as pointer arithmetic.
Pointer with Array Example : Pointer with function- There are two mechanisms for
#include<stdio.h> passing a value to a function. These are –
int main()
{ Call By Value – In this case we pass the value as
int arr[]={10,20,30,40,50}; function argument. In this case all the changes which
int i,*p; occur inside the function will not reflect outside the
p=arr; function.
printf("\nValue\tAddress\n");
for(i=1;i<=5;i++) Call By Address or Call By Reference - In this case we
{ pass the address as function argument. In this case all
printf("%d\t%u\n",*p,p); the changes which occur inside the function will reflect
p++; outside the function.
}
return 0;
}
Call By Value Example Call By Address or Call By Reference Example
#include<stdio.h> #include<stdio.h>
void swap(int,int); #include<conio.h>
int main() void swap(int *,int *);
{ int main()
clrscr(); {
int a=10,b=20; clrscr();
printf("\nBefore Swap a=%d and b=%d\n",a,b); int a=10,b=20;
swap(a,b); printf("\nBefore Swap a=%d and b=%d\n",a,b);
printf("\nAfter Swap a=%d and b=%d\n",a,b); swap(&a,&b);
getch(); printf("\nAfter Swap a=%d and b=%d\n",a,b);
} getch();
void swap(int x,int y) }
{ void swap(int *x,int *y)
int z; {
z=x;
Output – the value of a & int z; Output – the value of a &
x=y; b will not change here. z=*x; b will be change here.
y=z; *x=*y;
} *y=z;
}
Dynamic Memory Allocation - Allocating memory at run time is known as dynamic memory allocation. It is
implemented by pointers. C language provides some function which are used for implanting DMA. These are –
Programming For Problem Solving (BCS -101) By Dhananjay Sharma 24

malloc() function – This function is used for allocating a block of memory. The general form will be-
Syntax
*ptr=(datatype *)malloc(sizeof(datatype))

calloc() function – This function is used for allocating multiple block of memory. The general form will be-
Syntax
*ptr=(datatype *)calloc(number_of_blocks,sizeof(datatype))

free() function – This function is used for releasing the memory which is allocated by calloc() or malloc() function.
File Handling
File handling is a technique by which we can store the processed data in form of file & we can access that data
whenever required. For creating working with a file we must create a file pointer like the following –
FILE *fp;
Some important file handling functions are –

fopen()- this function initialize a file pointer. The syntax will be-
fopen(file_name,file_mode);
file_mode – it specifies the file opening mode like-
w – write mode(creating a file)
r- read mode (reading the content of a file)
a – append mode (modifying an existing file).
fgetc() – gets a character from a file stream(memory).
fputc() – puts a character on a file stream(memory).
Fclose()- closes a file.
Important Questions –
Que-1: Read data from keyboard & store that data in a Que-1: Write a program for reading the contents of an
file. existing file.
#include<stdio.h> #include<stdio.h>
int main() #include<process.h>
{ int main()
{
FILE *fp;
char fn[15],ch; FILE *fp;
printf("Enter File Name For Craete a New File :"); char fn[15],ch;
scanf("%s",&fn); printf("Enter File Name For Read :");
fp=fopen(fn,"w"); scanf("%s",&fn);
printf("\nInput Contents of File, Press Ctrl+Z or F6 fp=fopen(fn,"r");
For Exit\n"); if(fp==NULL)
while((ch=getchar())!=EOF) {
{ puts("File Not Exist");
fputc(ch,fp); getch();
} exit(0);
puts("File Created"); }
return 0; while((ch=fgetc(fp))!=EOF)
} {
printf("%c",ch);
}
return 0;
}
Programming For Problem Solving (BCS -101) By Dhananjay Sharma 25
Que-3: WAP for creating the duplicate file of any existing file.
#include<stdio.h>
#include<process.h>
int main()
{
clrscr();
FILE *fp1,*fp2;
char source[30],target[30],ch;
printf("Enter Source File Name:");
scanf("%s",&source);
fp1=fopen(source,"r");
if(fp1==NULL)
{
puts("File Not Exist");
getch();
exit(0);
}
printf("Enter Target File Name:");
scanf("%s",&target);
fp2=fopen(target,"w");
while((ch=fgetc(fp1))!=EOF)
{
fputc(ch,fp2);
}
puts("Copy Created...");
getch();
}

Standard C Preprocessors
The preprocessors directives are processed at the time of program compilation. They are generally starts with #
symbol. Some important preprocessors are –
#include – This preprocessor directive is used for attaching a header file with our program at compile time.
#define – This preprocessor is used for defining an identifier or macro.
A Macro Example –
#include<stdio.h>
#include<conio.h>
#define max(a,b) (a>b?a:b)
int main()
{
int x,y;
printf("Enter Two Numbers :\n");
scanf("%d%d",&x,&y);
printf("\nLargest : %d",max(x,y));
return 0;
}

Storage Classes
auto - This is the default storage class, which initialize a local variable. It initialize a variable with a garbage value.
The syntax will be-
int a; or auto int a;
register – These variables are stored inside the registers( a kind of fast access memory) instead of RAM. So they are
faster than auto. They are initialized by garbage value. The Syntax will be-
register int a;
static – These variable share a single copy to each function of a program. So change the value in any function reflects
to other function. They are initialized by 0. The Syntax will be –
static int a;
extern – They are used as a global variable. Default initialize value will be 0. the Syntax will be-
extern int a;

You might also like