BSc_2ndSem_PS_using_C
BSc_2ndSem_PS_using_C
Computer:
Computer is an electro – mechanical device, which takes information from the user, processes it
and gives results.
The information which the user gives to the computer is called Input.
The devices which give input to the computer are called Input devices.
Ex: Keyboard, Mouse, Joystick, Scanner.
The result which the computer gives to the user is called Output.
The devices which give output to the user are called Output devices.
Ex: Monitor, Printer, Speaker
Characteristics of computers:
SPEED :
A computer can process the data and gives output in fraction of seconds.
ACCURACY :
Inspite of processing data at high speed, computer gives accurate results.
RELIABILITY :
The output generated by the computer is reliable. It is reliable only when the data given to the
computer and the instructions to process the data are reliable.
STORAGE CAPACITY :
Computer has capacity to store huge amount of data using storage devices.
AUTOMATION :
Once the instructions are stored in the computer, it works automatically without human
intervention.
DILIGENCE :
Computer does not suffer from tiredness or losing concentration.
Limitations of computers:
CPU
Arithmetic &
Input Unit Logic Unit Output Unit
Control Unit
Memory Unit
Storage Unit
Input Unit:
The information which the user gives to the computer is called Input.
The devices which give input to the computer are called Input devices.
Ex: Keyboard, Mouse, Joysticks, Scanner, Barcode readers, Optical Mark Readers.
Output Unit:
The result which the computer gives to the user is called Output.
The devices which give output to the user are called Output devices.
Ex: Monitor, Printer, Speaker, Projector
CU (Control Unit):
Data transmission between I/O devices and processor is the responsibility of the control
unit.
MU (Memory Unit):
All the data & instructions for executing the program will be stored here.
Storage Unit:
The storage unit stores the data permanently into the disk.
Ex: Hard disk, Floppy disc, CD, DVD, Magnetic tapes.
Hardware is the physical components of a computer which we can touch and feel.
These are the primary electronic devices used to build up the computer.
Examples of hardware in a computer are the Processor, Memory Devices, Monitor, Printer, Keyboard,
Mouse etc.
1. Input Devices:
Input Devices are those devices through which user enters data and information into the Computer or
simply, User interacts with the Computer.
Examples of Input Devices are Keyboard, Mouse, Scanner, etc.
2. Output Devices:
Output Devices are used to show the result of the task performed by the user.
Examples of Output Devices are Monitors, Printers, Speakers, etc.
3. Storage Devices:
Storage Devices are used to store data and they are also known as Secondary Storage Devices.
Examples of Storage Devices are Memory cards, Pen drives, CDs, DVDs, Hard Disk etc.
4. Internal Components:
Internal Components consists of important hardware devices present in the System.
Examples of Internal Components are the Processor, Motherboard, RAM chips etc.
Computer Software:
Software is a collection of related programs that performs different tasks on a computer system.
We can say that Software is a programming code executed on a computer processor.
The code can be machine-level code or code written for an operating system.
Examples of software are MS- Word, Excel, PowerPoint, Google Chrome, Photoshop etc.
S/w can be divided into two types: System Software & Application Software
1. System Software:
System s/w is used to interact with computer h/w.
System s/w is also used to run Application s/w.
Following are some of the mostly used System s/w.
Operating System:
The operating system provide the interface for the user to interact with the computer.
The operating system provide icons to open many applications.
Ex: opening a web browser, open paint application, open word application for creating documents
etc.
The operating system monitors that the system resources are utilized correctly.
Some of the popular operating systems are DOS, Windows, UNIX, and Linux.
Utility Software:
Utility s/w is used to analyse & maintain the computer. Some of the utility programs are shown
below.
Disk Checkers are used to scan the hard disk to find corrupted areas & eliminate them.
Disk Cleaners are used to find the files which are not required to run the computer.
Disk defragmenters are used to move the parts of a file to one location.
Disk partitions are used to divide the hard disk into multiple drives.
Anti-virus utilities are used to scan the computer for viruses.
Compiler:
Compilers are used to convert the source code written in a programming language into the
machine language.
If the source code contain errors, then the program can’t be compiled.
These errors are called ‘syntax errors’. Spelling mistakes & typing mistakes are syntax errors.
Another type of error is logic error. When the program does not give correct result, it is logic error.
Compilers work as shown in following figure:
Interpreter:
An interpreter is a program that directly executes the instructions in a high-level language, without
converting it into machine code.
In programming, we can execute a program in two ways. Firstly, through compilation and secondly, through
an interpreter.
Interpreters work as shown in following figure:
MS Office:
MS Office is a s/w package provided by Microsoft to create documents, spread sheets, databases &
presentations. There are mainly 4 applications available in MS Office package.
These are MS Word, MS Excel, MS Access & MS Powerpoint.
MS Word is used to create documents.
Ex: Letters, Resumes, study materials can be created in MS Word.
MS Excel is used to create the data which is in the form of rows & columns.
MS Access is used to create databases. Ex: Employee’s details, Student’s marks.
MS Powerpoint is used to create presentations on any topic.
Multimedia s/w:
Multimedia s/w can be in the form audio, video, images (or) animation.
Media players, MP3 players, VLC players are examples for multimedia s/w.
Voice recognition s/w is used to recognize the voice which was given as input.
In a multimedia keyboard, there are buttons to up the volume, down the volume, pause (or) stop
the multimedia running in the computer.
Graphics s/w:
Graphics s/w (or) Image editing s/w is a program that allows users to create & edit images.
Ex: MS Paint, Adobe photoshop etc.
Paint programs are used to create drawings. These images are stored as BMP files (Bitmap Images)
& can be easily be edited when required.
Animation s/w (2D & 3D) is used to create animations.
CAD s/w is used to create engineering drawings.
DBMS s/w:
Database Management Systems are used to store & manipulate the data in the database.
DBMS are used in ATMs & Railway reservations etc.
Using DBMS, we can get required information from the database.
Ex 1: SELECT sname FROM students WHERE marks>90.
Ex 2: SELECT emp_name FROM employees WHERE salary>8000.
MS Access, SQL server & Oracle are popular database management systems.
Examples:
Step 1: Start
Step 2: Declare variables a, b and sum.
Step 3: Read values a and b.
Step 4: Add a and b and store the result in sum.
Sum ← a + b
Step 5: Display sum
Step 6: Stop
Ex2: Algorithm to find the biggest among three different numbers entered by the User.
Step 1: Start
Step 2: Declare variables a,b and c.
Step 3: Read variables a,b and c.
Step 4: If a>b
If a>c
Display a is the biggest number.
Else
Display c is the biggest number.
Else
If b>c
Display b is the biggest number.
Else
Display c is the biggest number.
Step 5: Stop
Step 1: Start
Step 2: Declare variables n, i, result.
Step 3: Initialize variables
result ← 1
i←1
Step 4: Read value of n
Step 5: Repeat the steps until i<=n
5.1: result ← i * result
5.2: i ← i+1
Step 6: Display result
Step 7: Stop
Step 1: Start
Step 2: Declare variables first, second and temp.
Step 3: Initialize variables first ← 0 & second ← 1
Step 4: Display first and second
Step 5: Repeat the steps until second≤500
5.1: temp ← first + second
5.2: display temp
5.3: first ← second
5.4: second ← temp
Step 6: Stop
SYMBOL DESCRIPTION
Input/Output symbol
Control flow
Decision symbol
Processing step
Start and End symbols are also known as the terminal symbols and are represented as
rounded rectangles.
These symbols are the first and last symbols in a flowchart.
These are used to get input from user & display the result.
Significance of Flowcharts:
Flowcharts are very important in the programming of a problem as they help the
programmers to understand the logic of complicated and lengthy problems.
Once a flowchart is drawn, it becomes easy for the programmers to write the program in
any high-level languages.
06. Write about Concepts of Machine level, Assembly level and high-level programming.
Programming Languages:
Over the years, computer languages have been evolved from Low-Level to High-Level
Languages. In the earliest days of computers, only Binary Language was used to write
programs.
The computer languages are classified as follows:
Middle-level language is a computer language in which the instructions are created using
symbols such as letters, digits and special characters.
Assembly language is an example of middle-level language. In assembly language, we use
predefined words called mnemonics.
Binary code instructions in low-level language are replaced with mnemonics and operands in
middle-level language.
The computer cannot understand these mnemonics in middle-level language, so it needs to be
translated into a low-level language to make it understandable by the computer. Assembler is
used to translate middle-level language into low-level language.
Simple
C is a simple language in the sense that it provides a structured approach (to break the
problem into parts), the rich set of library functions, data types, etc.
Rich Library
C provides a lot of inbuilt functions that make the development fast.
Memory Management
It supports the feature of dynamic memory allocation. In C language, we can free the allocated
memory at any time by calling the free() function.
Speed
The compilation and execution time of C language is fast since there are lesser inbuilt functions.
Pointer
In C, we can directly interact with the memory by using the pointers.
Recursion
In C, we can call the function within the same function. It provides code reusability.
- Document Section: This section consists of set of comment lines which include name of the program,
author name, creation date and other information.
- Links Section (File): It is used to link the required system libraries (or) header files to execute a
program.
- Global variable declaration Section: It is used to declare global (or) public variables.
- void main(): Used to start of actual C program. It includes two parts as declaration part and
executable part.
- Local variable declaration section: Used to declare local (or) private variables.
- Function declaration section: Used to declare functions of program from which we get required
output.
- Function definition section: Used to define functions which are to be called from main().
Output:
Identifiers
In C language, identifiers are the names given to variables, constants, functions and user-
defined data.
These identifiers are defined using a set of rules.
An Identifier can only have alphanumeric characters( a-z , A-Z , 0-9 ) and underscore( _ ).
The first character of an identifier can only contain alphabet( a-z , A-Z ) or underscore ( _ ).
Identifiers are also case sensitive in C. For example name and Name are two different
identifiers.
Keywords are not allowed to be used as Identifiers.
No special characters, such as semicolon, period, whitespaces, slash or comma are permitted to
be used in or as Identifier.
Character set
Data types specify how we enter data into our programs and what type of data we enter.
C language has some predefined set of data types to handle various kinds of data that we use in our
program.
Integer type
Integers are used to store whole numbers.
Floating type
Floating types are used to store real numbers.
Character type
Character types are used to store characters value.
Type Size(bytes)
char (or) signed char 1
unsigned char 1
void type
void type means no value. This is usually used to specify the type of functions.
Declaration of variables must be done before they are used in the program.
Declaration does two things.
It tells the compiler what the variable name is.
It specifies what type of data the variable will hold.
Definition of variable means to assign a value to a variable. A variable must be declared before
it can be defined.
#include<stdio.h>
void main(){
int a,b,sum; // variable declaration
a=10; // variable definition
b=20; // variable definition
sum=a+b;
printf("Sum is %d",sum);
}
Output:
Sum is 30
#include<stdio.h>
void main(){
char ch;
char str[50];
printf("Enter a character ");
scanf("%c",&ch);
printf("Entered character is %c\n",ch);
printf("Enter a string ");
scanf("%s",&str);
printf("Entered string is %s",str);
}
Output:
Enter a character S
Entered character is S
Enter a string SUDHEER
Entered string is SUDHEER
In C programming language, printf() function is used to print the “character, string, float,
integer, octal and hexadecimal values” onto the output screen.
We use printf() function with %d format specifier to display the value of an integer variable.
Similarly %c is used to display character, %f for float variable, %s for string variable, %lf
for double and %x for hexadecimal variable.
To generate a newline, we use “\n” in C printf() statement.
The getchar() function reads a character from the input device. This function reads only single
character at a time. We can use this method in the loop if we want to read more than one character.
The putchar() function prints the character on the screen. This function puts only single character at
a time. In case you want to display more than one characters, use putchar() method in the loop.
#include <stdio.h>
void main( ){
int c;
printf("Enter a character");
c=getchar();
putchar(c);
}
When we execute the above code, it will ask us to enter a character. When we enter the character, it
will display the entered character.
#include<stdio.h>
void main(){
char str[100];
printf("Enter a string");
gets(str);
puts(str);
}
When we execute the above code, it will ask us to enter a string. When we enter the string, it will
display the entered string.
The main difference between these two functions is that scanf() stops reading characters when it
encounters a space, but gets() reads space character also.
If you enter name as SUDHEER KUMAR using scanf() it will only read and store SUDHEER and will
leave the part after space. But gets() function will read it completely.
Operators in C Language:
Arithmetic operators
OPERATOR DESCRIPTION
+ Adds two operands
- Subtract second operand from first
* Multiply two operands
/ Divide the numerator by denominator
% remainder of division
Relational operators
The following table shows all relational operators supported by C.
OPERATOR DESCRIPTION
Logical operators
C language supports following 3 logical operators.
Suppose a=TRUE and b=FALSE.
|| Logical OR a || b is TRUE
Note:
&& is TRUE only if both operands are TRUE. In all other cases, && will be FALSE.
|| is FALSE only if both operands are FALSE. In all other cases, || will be TRUE
OPERATOR DESCRIPTION
& Bitwise AND
| Bitwise OR
a b a&b a|b
0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 1
The bitwise shift operators shifts the bit value. The left operand specifies the value to be shifted and the
right operand specifies the number of positions that the bits to be shifted.
Ex:
a = 0001000
b =2
a << b = 0100000
a >> b = 0000010
Explanation:
The question mark "?" in the syntax represents the if part.
The first expression (expression1) is used to check TRUE or FALSE.
If that condition (expression1) is TRUE then expression2 is assigned to the variable.
If that condition (expression1) is FALSE then expression3 is assigned to the variable.
Ex:
#include<stdio.h>
void main(){
int n1=5, n2=10, max;
max = (n1>n2) ? n1 : n2;
printf(“Biggest number is %d”,max);
}
Output:
Biggest number is 10
Syntax:
Increment operator: ++var_name; (or) var_name++;
Decrement operator: --var_name; (or) var_name--;
Example:
Increment operator : ++i ; i++ ;
Decrement operator : ––i ; i–– ;
Ex:
#include <stdio.h>
void main(){
int i=1;
while(i<10){
printf("%d ",i);
i++;
}
}
Output:
123456789
Special operators
OPERATOR DESCRIPTION
sizeof size of the variable
Ex:
#include <stdio.h>
int main() {
char ch = 'D';
int *p = &ch;
printf("size : %d byte\n",sizeof(ch));
printf("Address : %d\n",&ch);
printf("Value : %c",*p);
return 0;
}
Output:
size : 1 byte
Address : 505952423
Value : D
#include<stdio.h>
void main(){
int i,n,fact=1;
printf("Enter the number");
scanf("%d", &n);
for(i = 1; i <= n; i++){
fact = fact*i;
}
printf("Factorial is %d", fact);
}
Output
Enter the number 5
Factorial of 5 is 120
#include<stdio.h>
void main(){
int i=0, j, k;
char str[100];
char rev[100];
printf("Enter a string ");
scanf("%s", str);
while(str[i]!='\0') i++;
k=i-1;
for(j = 0; j < i; j++){
rev[j] = str[k--];
}
printf("The reverse string is %s\n", rev);
}
Output
Enter a string university
The reverse string is ytisrevinu
#include<stdio.h>
void main(){
int n, temp, rev=0, rem;
printf("Enter a number\t");
scanf("%d", &n);
temp = n;
while(n > 0){
rem = n%10;
rev = (rev*10)+rem;
n = n/10;
}
if(rev == temp){
printf("The number is a palindrome");
}
else{
printf("The number is not a palindrome");
}
}
Output:
Enter a number 12321
The number is a palindrome
Decision making is about deciding the order of execution of statements based on given
condition.
C language handles decision-making by supporting the following statements.
if statement
switch statement
Simple if statement:
if...else statement:
The general form of ‘if...else’ statement is,
if(expression){
statement-block1;
}
else{
statement-block2;
}
Output:
x is not greater than y
if(expression1){
if(expression2){
statement block1;
}
else{
statement block2;
}
}
else{
statement block3;
}
if 'expression1' is false the 'statement-block3' will be executed, otherwise it continues to perform the test
for 'expression2' . If the 'expression2' is true the 'statement-block1' is executed otherwise 'statement-
block2' is executed.
Ex:
#include<stdio.h>
void main(){
int a,b,c;
printf("enter 3 number");
scanf("%d%d%d",&a,&b,&c);
if(a>b){
if( a > c){
printf("a is greatest");
}
else{
printf("c is greatest");
}
}
else{
if( b>c){
printf("b is greatest");
}
else{
printf("c is greatest");
}
}
}
switch(expression){
case value-1:
block-1;
break;
case value-2:
block-2;
break;
case value-3:
block-3;
break;
case value-4:
block-4;
break;
default:
default-block;
break;
}
Ex:
#include<stdio.h>
void main(){
int value = 2;
clrscr();
switch(value){
case 1: printf("A"); break;
case 2: printf("B"); break;
case 3: printf("C"); break;
}
}
Output:
B
Loops are used to execute a set of statements repeatedly until a particular condition is satisfied.
This sequence of statements to be executed is kept inside the curly braces { } known as the Loop body.
After every execution of loop body, condition is verified, and if it is found to be true the loop body is
executed again.
When the condition check returns false, the loop body is not executed.
while loop:
Syntax:
variable initialization;
while (condition){
statements ;
variable increment or decrement ;
}
#include<stdio.h>
void main(){
int a=5,i=1;
while(i<=10){
printf("%d ",a*i);
i++;
}
}
Output:
5 10 15 20 25 30 35 40 45 50
for loop:
for loop is used to execute a set of statements repeatedly until a particular condition is satisfied.
Syntax:
for(initialization; condition ; increment/decrement){
statement-block;
}
Output
5 10 15 20 25 30 35 40 45 50
do while loop
Syntax:
do{
....
....
}while(condition)
#include<stdio.h>
void main(){
int a=5,i=1;
do{
printf("%d ",a*i);
i++;
}while(i <= 10);
}
Output
5 10 15 20 25 30 35 40 45 50
Syntax:
while(condition) {
while(condition) {
statement(s);
}
statement(s);
}
do {
statement(s);
do {
statement(s);
}while( condition );
}while( condition );
Ex:
The following program uses a nested for loop.
#include<stdio.h>
void main(){
int i,j;
for(i=1;i<=5;i++){
for(j=1;j<=i;j++)
printf("%d ",j);
printf("\n");
}
}
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1) break statement:
break statement is used to immediately exit the loop, the program continues with the statement
immediately after the loop.
Example:
#include<stdio.h>
void main(){
int i;
for(i = 0; i<10; i++){
if(i == 5)
break;
printf("%d ",i);
}
printf("came outside of loop");
}
Output:
0 1 2 3 4 came outside of loop
2) continue statement
continue statement is used to leave the current cycle of loop, and starts with the next cycle.
#include<stdio.h>
33
void main(){
int i;
for(i = 0; i<10; i++){
if(i == 5)
continue;
printf("%d ",i);
}
printf("came outside of loop");
}
Output:
0 1 2 3 4 6 7 8 9 came outside of loop
3) goto statement:
A goto statement in C programming provides an unconditional jump from the 'goto' to a labeled statement
in the same function.
#include <stdio.h>
int main(){
int num=6,i=1;
table:
printf("%d x %d = %d\n",num,i,num*i);
i++;
if(i<=10) goto table;
}
Output:
6 x 1 = 6
6 x 2 = 12
6 x 3 = 18
6 x 4 = 24
6 x 5 = 30
6 x 6 = 36
6 x 7 = 42
6 x 8 = 48
6 x 9 = 54
6 x 10 = 60
Arrays:
Declaring Arrays
- To declare an array in C, we need to specify the data type and the number of elements required by an
array.
type arrayName [arraySize];
- This is called a single-dimensional array. The arraySize must be an integer greater than zero and type can
be any valid C data type.
- For example, to declare a 10-element array called balance of type integer, use this statement:
- int balance[10];
- Here, balance is an array variable which is sufficient to hold up to 10 integers.
Initializing Arrays
- We can initialize an array in C either one by one (or) using a single statement as follows:
int balance[5] = {27, 5, 19, 43, 29};
- The number of values between braces { } cannot be larger than the number of elements that we declare
for the array between square brackets [ ].
- If we not specify the size of the array, an array just big enough to hold the initialization is created.
Therefore, we can write:
int balance[] = {27, 5, 19, 43, 29};
- All arrays have 0 as the index of their first element, and the last index of an array will be total size of the
array minus 1.
- Below is the pictorial representation of the array we discussed above:
#include <stdio.h>
void main(){
int n[5]; // n is an array of 5 integers //
int i,j;
for ( i = 0; i<5; i++ ) {
n[ i ] = i + 100;
}
for (j = 0; j < 5; j++ ) {
printf("Element[%d] = %d \n", j, n[j] );
}
}
Output:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
There are number of operations that can be performed on arrays. These operations include:
Step 1: START
Step 2: initialize i 0
Step 3: Repeat until i<Array_Size
Apply process to A[i]
Set i i+1
Step 4: STOP
2. Insertion: Inserting an element in the array means adding a new data element in an array. We can
insert the element at the end of the array or in the middle of the array.
Step 1: START
Step 2: set N = N+1
Step 3: set A[N-1] = value
Step 4: EXIT
Step 1: START
Step 2: initialize i=N-1
Step 3: Repeat until i>=pos
A[i+1] A[i]
i i-1
Step 4: N N+1
Step 5: A[pos] val
Step 6: STOP
Step 1: START
Step 2: N N-1
Step 3: STOP
Step 1: START
Step 2: initialize ipos
Step 3: Repeat until i<N-1
A[i] A[i+1]
i i+1
Step 4: N N-1
Step 5: STOP
4. Search: Searching means to find whether a particular value is present in the array or not.
Step 1: START
Step 2: initialize i0
Step 3: Repeat until i<N
if A[i] = value display “Element found at i”
goto Step 5
i i+1
Step 4: display “ Element not found ”
Step 5: STOP
5. Merging:
To merge any two arrays, start appending each and every element of the first array to the third array (the
merged array). Then start appending each and every element of the second array to the third array (the
merged array)
6. Sorting:
Sorting means arranging the elements of the array in some order which may either be ascending (or)
descending.
- Every element in the array a is identified by a[ i ][ j ], where ‘a’ is the name of the array, and ‘i’ and ‘j’
are the subscripts that uniquely identify each element in ‘a’.
- Two-dimensional arrays may be initialized by specifying bracketed values for each row.
- Following is an array with 3 rows and each row has 4 columns.
int a[3][4] = { {0, 1, 2, 3} , {4, 5, 6, 7} , {8, 9, 10, 11} };
- The following initialization is equivalent to the previous example:
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
- An element in a two-dimensional array is accessed by using the subscripts, i.e., row index and column
index of the array. For example:
int val = a[2][3];
- The above statement will take the 4th element from the 3rd row of the array.
- The following program used a nested for loop to handle a two-dimensional array:
#include <stdio.h>
void main(){
int a[3][2] = {{0,0}, {1,2}, {2,4}};
int i, j;
for ( i = 0; i < 3; i++ ) {
for ( j = 0; j < 2; j++ ) {
printf(“a[%d][%d] = %d \n”, i, j, a[i][j] );
}
}
}
Output:
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
#include<stdio.h>
#include<stdlib.h>
void main(){
int i, j,r1,c1,r2,c2;
int a[10][10], b[10][10], c[10][10];
printf("Enter First Matrix Size:");
scanf("%d %d",&r1,&c1);
printf("Enter Second Matrix Size:");
scanf("%d %d",&r2,&c2);
if(r1!=r2 || c1!=c2){
printf("Matrix Addition is not possible\n");
exit(0);
}
printf("\nEnter First Matrix Elements:");
for(i=0;i<r1;i++){
for(j=0;j<c1;j++){
scanf("%d",&a[i][j]);
}
}
printf("\nEnter Second Matrix Elements:");
for(i=0;i<r2;i++){
for(j=0;j<c2;j++){
scanf("%d",&b[i][j]);
}
}
for(i=0;i<r1;i++){
for(j=0;j<c1;j++){
c[i][j]=a[i][j]+b[i][j];
}
}
printf("\nAddition of Two Matrices:\n");
for(i=0;i<r1;i++){
for(j=0;j<c1;j++){
printf(" %d",c[i][j]);
}
printf("\n");
}
}
Output:
#include<stdio.h>
#include<stdlib.h>
void main(){
int i, j,k,r1,c1,r2,c2;
int a[10][10], b[10][10], c[10][10];
printf(“Enter First Matrix Size:”);
scanf(“%d %d”,&r1,&c1);
printf(“Enter Second Matrix Size:”);
scanf(“%d %d”,&r2,&c2);
if(c1!=r2){
printf(“Matrix Multiplication is not possible\n”);
exit(0);
}
printf(“\nEnter First Matrix Elements:”);
for(i=0;i<r1;i++){
for(j=0;j<c1;j++){
scanf(“%d”,&a[i][j]);
}
}
printf(“\nEnter Second Matrix Elements:”);
for(i=0;i<r2;i++){
for(j=0;j<c2;j++){
scanf(“%d”,&b[i][j]);
}
}
for(i=0;i<r1;i++){
for(j=0;j<c2;j++){
c[i][j]=0;
for(k=0;k<c1;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
printf(“\nMultiplication of Two Matrices:\n”);
for(i=0;i<r1;i++){
for(j=0;j<c2;j++){
printf(“ %d”,c[i][j]);
}
printf(“\n”);
}
}
Output:
Example:
#include<stdio.h>
void main(){
char str[5]={'H','E','L','L','O'};
printf("%s",str);
}
Output:
HELLO
String Functions:
C supports a wide range of functions that manipulate strings. To use string functions in ‘C’ program, we
need to include the header file ‘string.h’.
#include<stdio.h>
#include<string.h>
void main(){
char s1[12] = "Hello";
char s2[12] = "World";
char s3[12];
strcpy(s3, s1);
printf("s3 : %s\n", s3 );
strcat( s1, s2);
printf("s1 : %s\n", s1 );
printf("Length of s1 : %d\n", strlen(s1) );
}
Output:
s3 : Hello
s1 : HelloWorld
Length of s1 : 10
Example 2:
#include<stdio.h>
#include<string.h>
void main(){
char s1[12] = "Hello";
char s2[12] = "World";
char s3[20] = "Life is Beautiful";
int result = strcmp(s1, s2);
printf("result : %d\n", result);
printf("%s\n",strchr(s1,'e'));
printf("%s",strstr(s3,"is"));
}
Output:
result : -15
ello
is Beautiful
isalnum(ch) : This function returns non zero value if given character is alphabet or number &
returns zero if given character is not alphabet or number.
Example:
#include<stdio.h>
#include<ctype.h>
int main(){
char ch = 'S';
if (isalnum(ch)!=0)
printf("Given character is Alphabet or Number");
else
printf("Given character is Not Alphabet or Number");
return 0;
}
Output:
Given character is Alphabet or Number
isalpha(ch) : This function returns non zero value if given character is alphabet & returns zero
if given character is not alphabet.
Example:
#include<stdio.h>
#include<ctype.h>
int main(){
char ch = '6';
if (isalpha(ch)!=0)
printf("Given character is Alphabet");
else
printf("Given character is Not Alphabet");
return 0;
}
Output:
Given character is Not Alphabet
Output:
Given character is Digit
islower(ch) : This function returns non zero value if given character is lower case alphabet &
returns zero if given character is not in lower case.
Example:
#include<stdio.h>
#include<ctype.h>
int main(){
char ch = 'R';
if (islower(ch)!=0)
printf("Given character is lower case alphabet ");
else
printf("Given character is Not in lower case ");
return 0;
}
Output:
Given character is Not in lower case
isupper(ch) : This function returns non zero value if given character is upper case alphabet &
returns zero if given character is not in upper case.
Example:
#include<stdio.h>
#include<ctype.h>
int main(){
char ch = 'R';
if (isupper(ch)!=0)
printf("Given character is Upper case alphabet ");
else
printf("Given character is Not in Upper case ");
return 0;
}
Output:
Given character is Upper case alphabet
Output:
ASCII code of Given character is 84
tolower(ch) – This function converts the given character into lower case.
Example:
#include<stdio.h>
#include<ctype.h>
int main(){
char ch = 'D';
printf("Given character in lower case is : %c",tolower(ch));
return 0;
}
Output:
Given character in lower case is : d
toupper(ch) – This function converts the given character into upper case.
Example:
#include<stdio.h>
#include<ctype.h>
int main(){
char ch = 'd';
printf("Given character in upper case is : %c",toupper(ch));
return 0;
}
Output:
Given character in upper case is : D
Functions:
Declaration of a Function:
A function declaration tells the compiler about a function name and how to call the function. The actual
body of the function can be defined separately.
A function declaration has the following parts:
return_type function_name( parameter list );
Ex:
To find maximum of two numbers, we can declare a function as follows:
int max(int a, int b);
Defining a Function
Return Type: A function may return a value. The return_type is the data type of the value the function
returns. If a function doesn’t return a value, then the return_type is the keyword ‘void’.
Function Name: This is the actual name of the function. The function name and the parameter list
together called the function signature.
Parameters: When a function is invoked, we need to pass a value to the parameter. This value is referred
to as actual parameter (or) argument. The parameter list refers to the type, order, and number of the
parameters of a function. A function may (or) may not contain parameters.
Ex: To find maximum of two numbers, the function definition will be as shown below:
Example:
#include<stdio.h>
int max(int a, int b); //function declaration
void main(){
int num1 = 100;
int num2 = 200;
printf( "Max value is : %d", max(num1,num2)); // calling the function
}
int max(int a, int b){ //function definition
int result;
if (a>b)
result = a;
else
result = b;
return result;
}
Output:
Max value is : 200
03. How to pass parameters to the functions? (or) Explain Call By Value & Call By
Reference.
If a function is to use arguments, it must declare variables that accept the values of the arguments. These
variables are called the formal parameters of the function.
Formal parameters behave like other local variables inside the function and are created upon entry into the
function and destroyed upon exit.
There are two ways in which arguments can be passed to a function:
call by value:
The call by value method of passing arguments to a function copies the actual value of an argument into
the formal parameter of the function. In this case, changes made to the parameter inside the function
have no effect on the argument.
Output:
It shows that there is no change in the values, though they had been changed inside the function.
call by reference:
The call by reference method of passing arguments to a function copies the address of an argument into
the formal parameter. Inside the function, the address is used to access the actual argument. It means the
changes made to the parameter affect the passed argument.
To pass a value by reference, we need to declare the function parameters as pointer types.
#include<stdio.h>
void swap(int *x, int *y);
void main(){
int num1 = 100;
int num2 = 300;
printf( "Before swap: num1 = %d num2 = %d \n", num1,num2);
swap(&num1,&num2);
printf( "After swap: num1 = %d num2 = %d \n", num1,num2);
}
void swap(int *x, int *y){
int temp;
temp=*x;
*x=*y;
*y=temp;
}
Output:
A scope of variable is a region of the program where the variable can have its existence.
There are mainly two places where variables can be declared in C programming language:
Local Variables:
Variables that are declared inside a function (or) block are called local variables.
They can be used only by statements that are inside that function (or) block of code.
Local variables can’t be accessible from outside functions.
The following example shows how local variables are used.
#include<stdio.h>
void main(){
int a, b, c;
a = 10;
b = 20;
c = a + b;
printf ("value of a = %d, b = %d and c = %d", a, b, c);
}
Output:
Value of a = 10, b = 20 and c = 30
Global Variables
Global variables are defined outside a function, usually on top of the main function.
Global variables hold their values throughout the lifetime of the program and they can be accessed inside
any of the functions defined for the program.
The following program shows how global variables are used in a program.
#include<stdio.h>
int g; // global variable
void main(){
int a, b; // local variables
a = 10;
b = 20;
g = a + b;
printf ("Value of a = %d, b = %d and g = %d", a, b, g);
}
Output:
Value of a = 10, b = 20 and g = 30
A program can have same name for local and global variables but the value of local variable inside a
function will take preference. Here is an example −
#include<stdio.h>
int g = 20;
void main(){
int g = 10;
printf ("value of g = %d", g);
}
Output:
value of g = 10
#include<stdio.h>
void main(){
int i = 6;
printf("Factorial of %d is %d\n", i, factorial(i));
}
int factorial(int n) {
if(n <= 1) return 1;
else return n * factorial(n-1);
}
Output:
Factorial of 6 is 720
#include<stdio.h>
void main(){
int i;
for (i = 0; i < 10; i++)
printf("%d\t", fibonacci(i));
}
int fibonacci(int i) {
if(i == 0) return 0;
if(i == 1) return 1;
return fibonacci(i-1) + fibonacci(i-2);
}
Output:
0 1 1 2 3 5 8 13 21 34
Example: Example:
#include<stdio.h> #include<stdio.h>
void main(){ void main(){
auto int i = 10; register int i = 10;
{ {
auto int i = 20; auto int i = 20;
printf(“%d\n”,i); printf(“%d\n”,i);
} }
printf(“%d”,i); printf(“%d”,i);
} }
Output: Output:
20 20
10 10
Example: Example:
#include<stdio.h> #include<stdio.h>
extern int i=10; void main(){
void main(){ int i;
void show(); void incre();
int i = 20; for (i=0;i<3;i++)
printf("%d\n",i); incre();
show(); }
} void incre(){
void show(){ int a=1;
printf("%d\n",i); static int b =1;
} a++;
b++;
Output: printf("a = %d ",a);
20 printf("b = %d\n",b);
10 }
Output:
a=2b=2
a=2b=3
a=2b=4
Pointers in C language is a variable that stores/points the address of another variable. A Pointer in C is
used to allocate memory dynamically i.e. at run time. The pointer variable might be belonging to any of
the data type such as int, float, char, double, short etc.
Pointer Syntax : data_type *var_name; Example : int *p; char *p;
Here, * is used to denote that “p” is pointer variable and not a normal variable.
Normal variable stores the value whereas pointer variable stores the address of the variable.
The content of the C pointer always be a whole number i.e. address.
Always C pointer is initialized to null, i.e. int *p = null.
The value of null pointer is 0.
& symbol is used to get the address of the variable.
* symbol is used to get the value of the variable that the pointer is pointing to.
If a pointer in C is assigned to NULL, it means it is pointing to nothing.
Two pointers can be subtracted to know how many elements are available between these two pointers.
But, Pointer addition, multiplication, division are not allowed.
The size of any pointer is 2 byte (for 16 bit compiler).
#include<stdio.h>
int main(){
int *ptr, q;
q = 50;
ptr = &q;
printf("%d", *ptr);
return 0;
}
Output:
50
Pointer Arithmetic
We can perform addition and subtraction of integer constant from pointer variable.
Addition
We can perform pointer addition like ptr +1, ptr + 2 etc.
Example:
#include<stdio.h>
void main(){
int a;
int *ptr = &a;
printf("%p\n",ptr);
printf("%p\n",ptr+1);
printf("%p",ptr+2);
}
Output:
0x7ffdc7effe34
0x7ffdc7effe38
0x7ffdc7effe3c
Example:
#include<stdio.h>
void main(){
int a;
int *ptr = &a;
printf("%p\n",ptr);
printf("%p\n",ptr-1);
}
Output:
0x7ffc509f2d34
0x7ffc509f2d30
Multiplication
Example:
#include<stdio.h>
void main(){
int x = 10, y = 20, z;
int *ptr1 = &x;
int *ptr2 = &y;
z = *ptr1 * *ptr2 ;
printf("z = %d",z);
}
Output:
z = 200
Division
There is a blank space between '/' and * in the below program because the symbol /*is considered as
beginning of the comment and therefore the statement fails.
#include<stdio.h>
void main(){
int a=20,b=4,c;
int *ptr1 = &a, *ptr2 = &b;
c = *ptr1/ *ptr2;
printf("c = %d", c);
}
Output:
c=5
Example:
#include <stdio.h>
void main(){
int salary=10000, bonus=2000;
salaryhike(&salary, bonus);
printf("Final salary: %d", salary);
}
void salaryhike(int *var, int b){
*var = *var+b;
}
Output:
Final salary: 12000
If we try this same program without pointer, we find that the bonus amount will not be added in the
salary, this is because the change made by the function would be done to the local variables of the
function.
When we use pointers, the value is changed at the address of variable.
When an array is declared, compiler allocates sufficient amount of memory to contain all the elements of
the array.
Base address i.e. address of the first element of the array is also allocated by the compiler.
Suppose we declare an array arr,
int arr[5] = { 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two bytes, the five elements will
be stored as shown below:
We can also declare a pointer of type int to point to the array arr.
int *p;
p = arr;
// or,
p = &arr[0]; //both the statements are equivalent.
Now we can access every element of the array arr using p++ to move from one element to another.
NOTE: You cannot decrement a pointer once incremented. p-- won't work.
Pointer to Array
As studied above, we can use a pointer to point to an array, and then we can use that pointer to access
the array elements. Let’s have an example,
#include <stdio.h>
void main(){
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i = 0; i < 5; i++){
printf("%d", *p);
p++;
}
}
Output:
12345
In the above program, the pointer *p will print all the values stored in the array one by one. We can also
use the Base address (a in above case) to act as a pointer and print all the values.
The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at
runtime.
Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.
malloc() - allocates single block of requested memory.
calloc() - allocates multiple block of requested memory.
realloc() - reallocates the memory occupied by malloc() or calloc() functions.
free() - frees the dynamically allocated memory.
Before learning above functions, let's understand the difference between static memory allocation and
dynamic memory allocation.
malloc() function in C
#include<stdio.h>
#include<stdlib.h>
void main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL){
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i){
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
}
Output:
Enter number of elements: 3
Enter elements of array: 12
14
16
Sum=42
#include<stdio.h>
#include<stdlib.h>
void main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
if(ptr==NULL){
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum = sum + *(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
}
Output:
realloc() function in C
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function.
In short, it changes the memory size.
Syntax of realloc() function.
ptr=realloc(ptr, new-size)
free() function in C
The memory occupied by malloc() or calloc() functions must be released by calling free() function.
Otherwise, it will consume memory until program exit.
Syntax of free() function.
free(ptr)
It may be defined as a secondary data type which can store collection of dissimilar data elements. In order
to define structure we have to use the special keyword “struct”.
Syntax:
struct structure_name{
datatype variablename;
datatype variablename;
datatype variablename;
}structure_variable;
Example:
struct employee{
int eno;
char name[20]; 26 bytes elements/members of structure
float salary;
};
struct employee e1,e2; each structure variables occupies 26 bytes of memory.
Initialization of Structure:
Structure can be initialized by placing the elements within a pair of braces and separated by comma.
struct employee e1={101,”SUDHEER”,3500.00};
Structure elements can be accessed with the help of dot (or) arrow operators.
Ex: e.eno,e.name,e.salary;
Ex: eeno,ename,esalary;
#include<stdio.h>
void main(){
struct employee{
int eno;
char name[20];
float salary;
} e1;
printf("Enter Employee Details:");
scanf("%d%s%f",&e1.eno,&e1.name,&e1.salary);
printf("******** EMPLOYEE DETAILS *******");
printf("\n Employee No = %d", e1.eno);
printf("\n Employee Name = %s", e1.name);
printf("\n Salary = %f", e1.salary);
}
Output:
This implies that although a union may contain many members of different types, it cannot handle all
the members at the same time. A union is declared using the union keyword.
Initializing Unions:
A difference between a structure and a union is that in case of a union, the fields share the same memory
space, so fresh data replaces any existing data.
#include<stdio.h>
union employee{
int eno;
char name[20];
float salary;
} e1;
void main(){
printf("Enter Employee Details:");
scanf("%d%s%f",&e1.eno,&e1.name,&e1.salary);
printf("******** EMPLOYEE DETAILS *******");
printf("\n Employee No = %d", e1.eno);
printf("\n Employee Name = %s", e1.name);
printf("\n Salary = %f", e1.salary);
}
Output:
Enter Employee Details:102 Sudheer 20000
In the output of the above program, only salary is displayed correctly, because the data entered for salary
replaced already entered data for employee number & name.
Problem Solving using C – Sudheer Kumar
59
B.Sc (Honours) Computer Science
(Examination at the end of Second Semester)
Problem Solving using C
(Regulation : 2023-24) – Model paper 1
SECTION A – (5 x 4 = 20 marks)
Answer any FIVE of the following questions.
SECTION B – (5 x 10 = 50 marks)
Answer following questions.
UNIT 1 UNIT IV
UNIT II UNIT V
10. a) Write about conditional statements in C. 13. a) Explain Dynamic memory allocation in C.
(or) (or)
b) Write about iterative statements in C. b) Write about ‘structures’ in C.
UNIT III
SECTION A – (5 x 4 = 20 marks)
Answer any FIVE of the following questions.
1. Data types in C.
2. C-tokens.
3. Write about flow charts.
4. History of C Programming Language.
5. How to use switch statement.
6. Rules to construct variable names.
7. Pointer variables in C.
8. How to use pointers in Arrays.
SECTION B – (5 x 10 = 50 marks)
Answer following questions.
UNIT 1 UNIT IV
UNIT II UNIT V
10. a) Write about nested loops in C. 13. a) Explain : malloc(), calloc() & realloc() in C.
(or) (or)
b) Break, continue & goto statements b) Write about ‘unions’ in C.
UNIT III