0% found this document useful (0 votes)
13 views53 pages

ME Lab Manual

The document outlines a programming lab curriculum focused on C programming, covering the introduction to the programming environment, phases of C program development, and the structure of a simple C program. It details the use of decision-making and loop statements, providing examples and exercises for students to implement. The document also includes instructions for using Integrated Development Environments (IDEs) and lists assignments to reinforce learning.

Uploaded by

shlokbarhate641
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)
13 views53 pages

ME Lab Manual

The document outlines a programming lab curriculum focused on C programming, covering the introduction to the programming environment, phases of C program development, and the structure of a simple C program. It details the use of decision-making and loop statements, providing examples and exercises for students to implement. The document also includes instructions for using Integrated Development Environments (IDEs) and lists assignments to reinforce learning.

Uploaded by

shlokbarhate641
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/ 53

Government College of Engineering, Karad Programming for Problem Solving Lab

Experiment No .1

Title: Introduction to various components of programming environment.

Outcome: Students can execute a simple C program language and get familiarized with
programming environment.

Theory: The C programming language is a general-purpose, high-level language that was


originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs.
C was originally first implemented on the DEC PDP-11 computer in 1972.

Different phases of C program development:


Phase 1: Editor
Programmer creates program in the editor and stores it on disk. The example of editors can be
given as notepad in Windows, vim in Linux.

Phase 2: Preprocessor
The C preprocessor is a macro processor that is used automatically by the C compiler to
transform your program before actual compilation.

Phase 3: Compiler & Interpreter


The compiler read the whole program and translated it into machine language
completely. Compiler needs syntactically correct program to produce an executable code.
Interpreter translates the program statements line-by-line.

Phase 4: Linker
Linker links the object code with the libraries, creates an executable file and stores it on disk.

Phase 5: Loader
Loader loads the program into memory (RAM) and then instructs the processor to start the
execution of the program from the first instruction.

Phase 6: CPU
CPU takes each instruction and executes it. It stores new data values as the program executes.

What is C Compiler?
• C Compiler is a program that converts human readable code into machine readable code.
This process is called compilation.
• Human readable code is a program that consists of letters, digits and special characters
that we type on program window. Machine readable code is in 0’s & 1’s
• For example, let’s assume that we type” HELLO” in program window. We know that we
have typed “HELLO” in program window.
• But, processor knows only 01001000 for letter “H”, 01000101 for letter “E”, 01001100
for letter “L”, 01001100 for letter “L”, 01001111 for letter “O”
• Because, all C programs are executed by processor which resides in CPU.
• So, entire C source code should be converted into 0’s and 1’s as processor can understand
only 0’s and 1’s.
• So, compiler converts entire source code into 0’s and 1’s during compilation.

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

• Output produced by compiler is in the form of 0’s and 1’s which is saved in .exe file. This
file is called as executable or binary file.

Structure of C program:

A simple C program:
//Simple C program to print Hello on the screen
//Date: Name:
#include <stdio.h>
void main()
{
/* my first C Prog*/
printf("Hello,
World! \n");
}

1. The first line of the program #include <stdio.h>is a preprocessor command, which tells the
C compiler to include stdio.h file before going to actual compilation.
2. The next line void main() is the main function where program execution begins.
3. The next line /*...*/ will be ignored by the compiler and it has been put to add additional
comments in the program. So such lines are called comments in the program.
4. The next line printf(...) is another function available in C which causes the message
"Hello, World!" to be displayed on the screen.

Steps for Compiling and Executing the C Program in TURBO C++

1. Open Turbo C++ IDE


2. File > New and then write your C program
3. Save the program using F2 (OR file > Save) at C:\TC\BIN\, remember the extension should
be “.c”.
4. Compile the program using Alt + F9 OR Compile > Compile

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

5. Press Ctrl + F9 to Run (or select Run > Run in menu bar ) the C program.
6. Alt+F5 to view the output of the program at the output screen.

Integrated Development Environment (IDE):

The process of editing, compiling, running, and debugging programs is often managed by a single
integrated application known as an Integrated Development Environment, or IDE for short. An
IDE is a windows-based program that allows us to easily manage large software programs, edit
files in windows, and compile, link, run, and debug programs.

List of Integrated Development Environment (IDE):

1. Turbo C++
2. Eclipse
3. Code Blocks
4. Dev C++
5. NetBeans

Analysis:
1.

2.

3.

4.

5.

List of similar programs: Assignment 1


1. Write a C program to display your personal details.
2. Write a C program to display experiment list of Programming for Problem Solving Lab.
3. Write a C program to find square and cube of given number.
4. Write a C program to calculate sum of marks in 5 subjects and percentage of marks
obtained.
5. Write a C program to calculate simple and compound interest.

Programs:
1. Write a C program to display your personal details.

//Simple program to print personal details.


#include<stdio.h>
int main()
{
printf("\n Name: Asmita Patil");
printf("\n Registratio Number: 20261102");
printf("\n Qualification: PhD Computer Engineering");
return 0;
}

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

Output:

Conclusion:

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

Experiment No.2

Title: Implement a program by using decision making statements.

Outcome: Student will be able use branching statements used in C.

Theory:
C language supports the following statements known as control or decision making.
statements:
1. if statement
2. switch statement
3. conditional operator statement
4. goto statement

1. if statement:
The if statement is used to control the flow of execution of statements and is of the
form:

if (test expression)

It allows the computer to evaluate the expression first and then, depending on whether the
value of the expression is „true‟ or „false‟, it transfers the control to a particular statement.

The if statement may be implemented in different forms depending on the complexity of


conditions to be tested.
1. Simple if statement
2. if…..else statement
3. Nested if…..else statement
4. Else if ladder

1.1 Simple if statement:

The general form of a simple if statement is:

The statement-block‟ may be a single statement or a group of statement. If the


test expression is true, the statement-block will be executed; otherwise the statement-block
will be skipped and the execution will jump to the statement-x.

1.2 if…..else statement

The general form of a simple if else statement is:

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

If the test expression is true, then the true block statements are executed; otherwise
the false block statement will be executed.

1.3 Nested if…..else statement:

When a series of decisions are involved, we may have to use more than one if….else
statements, in nested form as follows.

This construct is known as the else if ladder.

1.4 The else if ladder:

A multipath decisions is a chain of ifs in which the statements associated with


each else is an if. It takes the general form:

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

2. switch statement
Switch statement is used for complex programs when the number of alternatives
increases.
The switch statement tests the value of the given variable against the list of case
values and when a match is found, a block of statements associated with that case is

executed.

3. conditional operator statement


➢ A ternary operator pair “?:” is available in C to construct conditional expression of
the form:
exp1 ? exp2 : exp3;
➢ Here exp1 is evaluated first.
➢ If it is true then the expression exp2 is evaluated and becomes the value of the
expression.
➢ If exp1 is false then exp3 is evaluated and its value becomes the value of the
expression.
➢ Example:
a=10; b=15;
x=(a>b)? a :
b;

4. goto statement:
➢ C supports the goto statement to branch unconditionally from one point of the
program to another.
➢ The goto requires a label in order to identify the place where the branch is to be
made.
➢ A label is any valid variable name and must be followed by a colon.
➢ The general from is:

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

Note: A label can be anywhere in the program, either before or after the goto label;
statement.

Analysi
s:
1.

2.

3.

4.

5.

List of similar programs: Assignment No.2


1. Write a C program to check inputted number is even or odd using if else
statement.
2. Write a C program to find largest of given 3 numbers using Nested if else
statement.
3. Write a C program to check inputted character is upper case or lower case using
conditional operator.
4. Write a C program to check whether given number is positive or negative.
5. Write a C program to check given character is vowel or not.
6. Write a C program to check given number is even or odd.
7. Write a C program to check given number is binary or not.
8. Write a C program to read a year as an input and find whether it is leap year or
not. Also consider end of the centuries.
9. Write a C program to display days of month when month number is given using
switch-case and else-if ladder.
10. Write a C program to display day of the week when day number is given using
switch-case and else-if ladder

Program:

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

List of questions:
1. Explain need for branching statements used in c programming.
2. List and explain different forms of if statement.
3. Differentiate between if and conditional statement.
4. Explain goto statement with example.
5. Explain switch statement with example.

Conclusion:

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

Experiment No.3

Title: Implement a program by using loop statements.

Outcome: Student will able to evaluate mathematical expressions by using looping statements
in c programming language.
Theory:

In looping, a sequence of statements are executed until some conditions for termination of the
loop are satisfied. A program loop therefore consists of two segments, one known as the body
of the loop and the other known as the control statements. Depending on the position of the
control statements in the loop, a control structure may be classified either as an entry-controlled
loop or as the exit-controlled loop.

1. Entry Controlled loops: In Entry controlled loops the test condition is checked
before entering the main body of the loop. For Loop and While Loop is Entry-
controlled loops.
2. Exit Controlled loops: In Exit controlled loops the test condition is evaluated at
the end of the loop body. The loop body will execute at least once, irrespective
of whether the condition is true or false. do-while Loop is Exit Controlled loop.
There are three types of Loops:
1) for loop
2) while loop
3) do while loop

1) The for
for loop in C programming is a repetition control structure that allows programmers to
write a loop that will be executed a specific number of times. for loop enables programmers
to perform n number of steps together in a single line.
Flow Chart-

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

Syntax-
for (initialize expression; test expression; update expression)
{
//
// body of for loop
//
}

Example:

for(int i = 0; i < n; ++i)


{
printf("Body of for loop which will execute till n");
}

In for loop, a loop variable is used to control the loop. Firstly we initialize the loop variable
with some value, then check its test condition. If the statement is true then control will
move to the body and the body of for loop will be executed. Steps will be repeated till the
exit condition becomes true. If the test condition will be false then it will stop.
Initialization Expression: In this expression, we assign a loop variable or loop counter to
some value. for example: int i=1;
Test Expression: In this expression, test conditions are performed. If the condition
evaluates to true then the loop body will be executed and then an update of the loop
variable is done. If the test expression becomes false then the control will exit from the
loop. for example, i<=9;
Update Expression: After execution of the loop body loop variable is updated by some
value it could be incremented, decremented, multiplied, or divided by any value.

Program-
// C program to illustrate for loop
#include <stdio.h>

// Driver code
int main()
{
int i = 0;

for (i = 1; i <= 10; i++)


{
printf( "Hello World\n");
}
return 0;
}

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

Output-

Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

While Loop
While loop does not depend upon the number of iterations. In for loop the number of
iterations was previously known to us but in the While loop, the execution is terminated on
the basis of the test condition. If the test condition will become false then it will break from
the while loop else body will be executed.
Flow Chart-

Syntax:
initialization_expression;

while (test_expression)
{
// body of the while loop
update_expression;
}

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

Program-
// C program to illustrate
// while loop
#include <stdio.h>

// Driver code
int main()
{
// Initialization expression
int i = 2;

// Test expression
while(i < 10)
{
// loop body
printf( "Hello World\n");

// update expression
i++;
}

return 0;
}

Output-

Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

do-while Loop-

The do-while loop is similar to a while loop but the only difference lies in the do-while
loop test condition which is tested at the end of the body. In the do-while loop, the loop
body will execute at least once irrespective of the test condition.

Syntax:

initialization_expression;

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab
do
{
// body of do-while loop

update_expression;
} while (test_expression);

Flow Chart
-

Program-
// C program to illustrate
// do-while loop
#include <stdio.h>
// Driver code
int main()
{
// Initialization expression
int i = 2;
do
{
// loop body
printf( "Hello World\n");

// Update expression

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab
i++;
// Test expression
} while (i < 1);

return 0;
}

Output-
Hello World

Analysis :

1.

2.

3.

4.

List of similar programs: Assignment No.3


1. Write a C Program to find sum of digits in a given number.
2. Write a C program to find max and min number from inputted number.
3. Write a C program to input 10 characters and count number of uppercase,
lowercase and digit characters.
4. Write a C program to display tables of 1-10.
5. Write a C language program to display the prime numbers between 1-100.
6. Write a C language program to display leap years between 2000 to 2100.
7. Write a C program to display first 10 numbers of Fibonacci Series.
8. Write a C language program to check given number is prime or not.
.
Program:

List of questions:
1. Explain need for looping statements used in c programming.
2. Which are the looping statements used in c programming.
3. Differentiate between do-while and while loops.
4. Difference between conditional and looping statements.

Conclusion:

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

Experiment No. 4

Title: Implement a program by passing argument to a function.

Outcome: Student will able to handle problem statement by passing argument to functions.

Theory:
A function is a block of code that performs a specific task and can be reused in a program
To define a function, you need to specify its return type, name, and parameters (if any)
Functions are used normally in those programs where some specific work is required to be
done repeatedly and looping fails to do the same.

Three things are necessary while using a function:

1. Declaring a function or prototype:

The general structure of a function declaration is as follows:

return_type function_name(arguments);

Before defining a function, it is required to declare the function i.e. to specify the function
prototype. A function declaration is followed by a semicolon ; . Unlike the function
definition only data type are to be mentioned for arguments in the function declaration.

2. Calling a function:

The function call is made as follows:

function_name(arguments separated by comma);

3. Defining a function:

All the statements or the operations to be performed by a function are given in the
function definition which is normally given at the end of the program outside the main.
Function is defined as follows:

return_type function_name(arguments)
{
Statements;
}

There are four types of functions depending on the return type and arguments:

• function without arguments and without return value


• function without arguments and with return value
• function with arguments and without return value

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

• function with arguments and with return value


A function that returns nothing must have the return type “void”.

For example, this is a function that returns the sum of two integers
int add(int a, int b) {
The body of the function contains the statements that implement the logic
int result = a + b;
Declare a variable to store the result
return result;
Return the result to the caller
}

To use a function, you need to call it with the appropriate arguments


For example, this is the main function that calls the add function
int main() {
Declare two variables to store the input values
int x = 10;
int y = 5;
Call the add function and assign the return value to another variable
int z = add(x, y);
Print the result to the standard output
printf("The sum of %d and %d is %d", x, y, z);
Return 0 to indicate successful termination
return 0;
}
Step-by-Step Explanation:
• A function is a way of organizing and reusing code that performs a specific task.
• To define a function, you need to specify its return type, which indicates what kind of
value the function will produce.
• You also need to give the function a name, which is used to identify and call the
function.
• Optionally, you can also define one or more parameters, which are variables that
receive the values passed by the caller.
• The body of the function contains the statements that implement the logic of the
function.
• To return a value from the function, you can use the return statement, which ends the
execution of the function and passes the value back to the caller.
• To use a function, you need to call it with the appropriate arguments, which are the
values that are passed to the function’s parameters.
• You can assign the return value of the function to a variable, or use it in other
expressions.
• The main function is a special function that is the entry point of a C program. It is
where the program starts and ends.

Example –
Function without argument and return value
#include<stdio.h>
void printName();

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

void main ()
{
printf("Hello ");
printName();
}
void printName()
{
printf("Welcome");
}

Output-

Welcome

Example-
Function without argument and with return value
#include<stdio.h>
int sum();
void main()
{
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum();
printf("sum is %d",result);
}
int sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}

Output-

Going to calculate the sum of two numbers:

Enter two numbers 10

24

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

sum is 34

Example-
Function with argument and without return value
#include<stdio.h>
void sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b)
{
printf("\nThe sum is %d",a+b);
}
Output-

Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

Example-
Function with argument and with return value
#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
}

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

int sum(int a, int b)


{
return a+b;
}
Output-
Going to calculate the sum of two numbers:
Enter two numbers:10
20
The sum is : 30

Recursive Function-
Recursion is a powerful concept where a function calls itself directly or indirectly. It allows
us to solve complex problems by breaking them down into simpler sub-problems.

• A function that calls itself is called a recursive function.


• The recursive function contains a call to itself somewhere in its body.
• Such functions can even have multiple recursive calls.

Basic Structure of Recursive Functions:


The syntax for recursive functions is as follows:
type function_name(args) {
// Function statements
// Base condition
// Recursion case (recursive call)
}

Example-
#include <stdio.h>

int nSum(int n)
{
if (n == 0)
{
return 0;
}
int res = n + nSum(n - 1);
return res;
}

int main() {
int n = 5;
int sum = nSum(n);
printf("Sum of First %d Natural Numbers: %d", n, sum);
return 0;
}

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

In the above program, nSum() calculates the sum of the first N natural numbers using
recursion.
The base condition is when n becomes 0, we return 0.
The recursion case is res = n + nSum(n - 1).

Fundamentals of C Recursion:

Two essential components of any recursive function:

Base Condition: Determines when the recursion terminates.

Recursion Case: Contains the recursive call(s) and divides the problem into smaller
subproblems.

For our example:

Base condition: n == 0

Recursion case: res = n + nSum(n - 1)

Advantages and Disadvantages:

Advantages:

1. Elegant solution for certain problems (e.g., factorial, Fibonacci series).


2. Simplifies complex problems.

Disadvantages:

1. Can lead to stack overflow if not handled properly.


2. May be less efficient than iterative solutions.

Analysis
1.

2.

3.

4.

5.

List of similar programs: Assignment No. 05


1. Write a C program to demonstrate calculator using function. Use one category of
function for one operation of calculator.
2. Write a C program to calculate area of circle using Function without argument and
with return value.
3. Write a C program to calculate area of rectangle using Function with argument and

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

with return value


4. Write a C program to print first 10 numbers of fibonacii series using recursion.
5. Write a C program to find factorial of number using recursion.

Program:

List of questions:
1. Explain need for functions in c programming.
2. Explain functions with different return types and arguments.
3. Differentiate between recursion and nesting of function.
4. What is difference between function declaration and function definition?
5. What are different types of return statement? Explain with importance.

Conclusion:

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

Experiment No. 5

Title: Implement a program for 1-D and 2-D array and operations on array.

Outcome: Student will able to handle problem statement for 1-D and 2-D array and
operations on array.

Theory:
A One-Dimensional Array is a variable that can store multiple values of a single data
type. The data is stored sequentially in computer memory and accessed via a common name
or identifier.
Here are some characteristics of 1D arrays in C:
• 1D Array stores the data in contiguous memory locations.
• 1D Array should be a list of similar data types.
• The size of the 1D array should be fixed.
• 1D Array should be stored in static memory.
• 1D Array indexing starts with size 0 and ends with size -1.

Declaration-
To declare a one-dimensional array in C, follow this syntax:
datatype array_name[size];
Here’s what each part means:

• datatype: The type of elements in the array (e.g., int, float, char).
• array_name: The name you choose for your array (must be a valid identifier).
• size: The number of elements the array can hold.

For example:

• int num[100]; declares an array of type int capable of storing 100 elements.
• float temp[20]; declares an array of type float with space for 20 elements.
• char ch[50]; declares an array of type char that can hold 50 characters.

Remember that when an array is declared, it initially contains garbage values. You can also
use variables or symbolic constants to specify the size of the array.
For instance:
#define SIZE 10
int main() {
int size = 10;
int my_arr1[SIZE]; // OK
// int my_arr2[size]; // Not allowed until C99
// ...
return 0;
}

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

Initialization-
To initialize a one-dimensional array in C, you have a few options:
1.Static Initialization:
You can assign values to the array elements during declaration.
For example:
int myArray[5] = {10, 20, 30, 40, 50};
This initializes myArray with the specified values.

2.Partial Initialization:
You can partially initialize an array, leaving some elements unspecified. The remaining
elements will be set to zero (for numeric types) or the null character (for char arrays).
For instance:
int myNumbers[10] = {1, 2, 3}; // Initializes first 3 elements, rest are 0
char myChars[5] = {'A', 'B'}; // Initializes first 2 elements, rest are '\0'
To print all elements of a one-dimensional array in C, you can follow these steps:

Use a Loop to Print Elements:


Use a loop (usually a for loop) to iterate through the array.
Inside the loop, print each element using printf or another output function.
Here’s an example of how to print all elements of an integer array:
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50}; // Example array
printf("Printing elements of the array:\n");
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]); // Print each element
}
printf("\n"); // Print a newline after all elements
return 0;
}
In this example:

• We declare an integer array arr with 5 elements.


• The for loop iterates from index 0 to 4 (inclusive).
• Inside the loop, we print each element using printf.

Two-Dimensional Array-
A two-dimensional array (also known as a 2D array) is an array that has exactly two
dimensions. It can be visualized as a grid with rows and columns, where each cell stores a
value. Here’s how you can work with 2D arrays in C:

Declaration of 2D Array:
The basic syntax for declaring a 2D array with x rows and y columns is as follows:
data_type array_name[x][y];
data_type: The type of data to be stored in each element.
array_name: The name of the array.
x: Number of rows.

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

y: Number of columns.
For example, you can declare a two-dimensional integer array named x with 10 rows and 20
columns:
int x[10][20];
Note that in this type of declaration, the array is allocated memory in the stack, and the size
of the array should be known at compile time (i.e., the size is fixed).

Initialization of 2D Arrays:
You can initialize a 2D array using an initializer list. The elements are stored in the table
from left to right, row by row.
int x[3][4] = {
{0, 1, 2, 3},
{4, 5, 6, 7},
{8, 9, 10, 11}
};
The above array has 3 rows and 4 columns.

Accessing Elements:
To access elements of a 2D array, use two subscripts instead of one:
int value = x[row_index][column_index];
Example-
#include<stdio.h>
int main(){
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++){
for(j=0;j<3;j++){
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}//end of j
}//end of i
return 0;
}
Output-
Arr[0][0]=1
Arr[0][1]=2
Arr[0][2]=3
Arr[1][0]=2
Arr[1][1]=3
Arr[1][2]=4
Arr[2][0]=3
Arr[2][1]=4

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

Arr[2][2]=5
Arr[3][0]=4
Arr[3][1]=5
Arr[3][2]=6

Analysis
1.

2.

3.

4.

5.

List of similar programs: Assignment No. 05


1. Write a program to store elements in an array and print them.
2. Write a program to find the sum of all elements of the array
3. Write a program to read n number of values in an array and display them in reverse
order.
4. Write a program to copy the elements of one array into another array.
5. Write a program to find largest element in the array.
6. Write a program to sort array elements in ascending order

Program:

List of questions:
1. Explain 1-D array.
2. Write short note on 2-D array

Conclusion:

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

Experiment No. 6

Title: Implement a program for string using string handling functions.

Outcome: Student will be able execute different string handling function by using c
programming language.

Theory:
The string in C programming language is actually a one-dimensional array of
characters which is terminated by a null character '\0'. Thus a null-terminated string
contains the characters that comprise the string followed by a null character.

The following declaration and initialization create a string consisting of the word
"Hello". To hold the null character at the end of the array, the size of the character array
containing the string is one more than the number of characters in the word "Hello".

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

If you follow the rule of array initialization then you can write the above statement as
follows:

char greeting[] = "Hello";

Following is the memory presentation of above-defined string in C:

H E l l o \0

The C compiler automatically places the '\0' at the end of the string when it initializes the
array. In C programming language some standard string handling functions are provided
in string.h header file.

Standard string function Purpose of these functions.


strcpy(s1, s2); Copies string s2 into string s1.

strcat(s1, s2); Concatenates string s2 onto the end of string s1.

strlen(s1); Returns the length of string s1.

strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2;
greater than 0 if s1>s2.
strupr(s1); Change the string s1 into upper case
strlwr(s1); Change the string s1 into lower case
strrev(s1); Change the string s1 into reverse order

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

Analysis :
1.

2.

3.

4.

5.

List of similar programs: Assignment 6


1. Write a C program to input a string and display its contents.
2. Write a C program to count uppercase and lowercase characters from inputted
string.
3. Write a C program to count number of words from inputted string.
4. Write a C program to find length of a given string and copy its contents into
other string without using string handling function.
5. Write a C program to compare one string with another string and concatenate
two strings without using string handling function.

Program:

List of questions:
1. Explain various types of string operation.
2. Explain standard string handling function in string.h header file.
3. Why null character is put at the end of the string?
4. Difference between strcpy and strcat functions.
5. What is the output of strcmp?

Conclusion:

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

Experiment No. 7

Title: Implement a program for array of structure.


Outcome: Student will able to implement structure and its array by using c programming
language.

Theory:
If we want a group of same data type we use an array. If we want a group of elements of
different data types we use structures.
For Example: To store the names, prices and number of pages of a book you can declare three
variables.
To store this information for more than one book three separate arrays may be declared.
Another option is to make a structure. No memory is allocated when a structure is declared. It
simply defines the “form” of the structure. When a variable is made then memory is allocated.
This is equivalent to saying that there is no memory for “int” , but when we declare an integer
i.e. is allocated.

Syntax for structure –

struct tag_name
{

// declaration of structure members;

};

struct tag_name struct_var_name;

Structure members are only be accessed by its structure variable by using ‘.’ operator. Structure
variable has memory allocated is total required memory for all structure members.

The structure for the above mentioned case will look like

struct books
{
char bookname[20];
float price;
int pages;
}b;

Here b is a structure variable having contiguous memory block allocated =20+4+2=26 bytes.
20 bytes for char type of array bookname, 4 bytes for floating type price and two bytes for int
type pages.

b.bookname b.price b.pages

0 20 24 26

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

An array whose elements are of type structure is called array of structure. It is generally
useful when we need multiple structure variables in our program.

Need for Array of Structures


Suppose we have 50 employees and we need to store the data of 50 employees. So for that,
we need to define 50 variables of struct Employee type and store the data within that.
However, declaring and handling the 50 variables is not an easy task. Let’s imagine a
bigger scenario, like 1000 employees.

Declaration of Array of Structures

struct structure_name array_name[number_of_elements];

Initialization of Array of Structures

We can initialize the array of structures in the following ways:


struct structure_name array_name[number_of_elements]={
{element1_value1,element1_value2,……},
{element2_value1,element2_value2,……},
………………………………….
……………………………….};

Array of structure variable has data type as its structure name. Declaration for array of structure
is as follows.
struct books
{
char bookname[20];
float price;
int pages;
}b[5];

above structure variable can hold information of 5 books.

// C program to demonstrate the array of structures


#include <stdio.h>

Example-
// structure template
struct Employee {
char Name[20];
int employeeID;
int WeekAttendence[7];
};

// driver code
int main()
{
// defining array of structure of type Employee
struct Employee emp[5];

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

// adding data
for (int i = 0; i < 5; i++) {
emp[i].employeeID = i;
strcpy(emp[i].Name, "Amit");
int week;
for (week = 0; week < 7; week++) {
int attendence;
emp[i].WeekAttendence[week] = week;
}
}
printf("\n");

// printing data
for (int i = 0; i < 5; i++) {
printf("Emplyee ID: %d - Employee Name: %s\n",
emp[i].employeeID, emp[i].Name);
printf("Attendence\n");
int week;
for (week = 0; week < 7; week++) {
printf("%d ", emp[i].WeekAttendence[week]);
}
printf("\n");
}

return 0;
}

Output-
Employe ID:0-Employee Name:Amit
Attendance
0123456
Employe ID:1-Employee Name:Amit
Attendance
0123456
Employe ID:2-Employee Name:Amit
Attendance
0123456
Employe ID:3-Employee Name:Amit
Attendance
0123456
Employe ID:4-Employee Name:Amit
Attendance
0123456

Analysis :
1.

2.

3.

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

4.

5.

List of similar programs: Solve any five


1. Write a program to store information (name, roll and marks) of a student using structure
and display information.
2. Write a program to store record of student which consists of student name, address, roll
number and age and display information.
3. Write a C program to calculate the subject-wise and student-wise totals and store them
as a part of structure using an array member to represent three subjects.
4. Write a program to search record in array of structure and display the record information
5. C program to demonstrate example of nested structure. This program will demonstrate
example of Nested Structure in C language, how to define, declare and access the nested
structure?
6. C program to demonstrate example of structure of array. Structure of Array: this
program will demonstrate example of structure of array, how to declare an array within
structure how to access its elements?
7. C program to add two distances in feet and inches using structure. This program will
read two distances in feet and inches and add them; final result will be printed in the
form of feet and inches using structure in C.

Program:

List of questions:
8. Explain what is structure and its syntax.
9. Differentiate between array and structure.
10. Differentiate between structure and union.
11. Explain how to access structure members in array of structure.

Conclusion

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

Experiment No. 8

Title: Implement a program for call by value and call by reference.

Outcome: Student will able to understand different ways of passing parameters to a function.

Theory:
Functions-
In c, we can divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}. A function can be called
multiple times to provide reusability and modularity to the C program. In other words, we can
say that the collection of functions creates a program. The function is also known as procedure
or subroutine in other programming languages.
Usually, the arguments take the input values and pass them to their corresponding parameters
in the function definition.There are generally two ways through which arguments can be passed
into the function:
• Call by value
• Call by reference
Before moving to the two methods let's acquaint with two other important terms used while
passing arguments.
They are:
• Actual parameters - the arguments used in the function call
• Formal Parameters - the parameters used in the function definition.
Formal parameters are used when we are defining a function. Whereas actual parameters come
into play when the function is called for execution. So formal parameters set the rules and
actual ones put the values in it to produce the result.
#include<stdio.h>
float area(int r); //function declaration
int main()
{
……………
arc=area(10); // function call 10 is Actual Parameter
}
float area(int r) //function definition r is formal parameter
{
………….
………………
return (a);

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

Need/Advantage of functions in C
There are the following advantages
• By using functions, we can avoid rewriting same logic/code again and again in a
program.
• We can call C functions any number of times in a program and from any place in a
program.
• We can track a large C program easily when it is divided into multiple functions.
• Reusability is the main achievement of C functions.
• However, Function calling is always a overhead in a C program.

Elements of user defined function:


There are three elements of a C function.
• Function declaration A function must be declared globally in a c program to tell
the compiler about the function name, function parameters, and return type.
• Function call Function can be called from anywhere in the program. The parameter
list must not differ in function calling and function declaration. We must pass the
same number of functions as it is declared in the function declaration.
• Function definition It contains the actual statements which are to be executed. It
is the most important aspect to which the control comes when the function is called.
Here, we must notice that only one value can be returned from the function.
Parameter passing mechanism:
Call by value and Call by reference in C
There are two methods to pass the data into the function in C language, i.e., call by value and
call by reference.
Let's understand call by value and call by reference in c language one by one.

Call by value in C
In call by value method, the value of the actual parameters is copied into the formal parameters.
In other words, we can say that the value of the variable is used in the function call in the call
by value method.
In call by value method, we cannot modify the value of the actual parameter by the formal
parameter.
In call by value, different memory is allocated for actual and formal parameters since the value
of the actual parameter is copied into the formal parameter.
The actual parameter is the argument which is used in the function call whereas formal
parameter is the argument which is used in the function definition.
Let's try to understand the concept of call by value in c language by the example given below:

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

Example-
#include<stdio.h>
void change(int);
void main()
{
int x=100;
printf("Before function call x=%d \n", x);
change(x);//passing value in function
printf("After function call x=%d \n", x);
}
void change(int num)
{
printf("Before adding value inside function num=%d \n",num);
num=num+100;
printf("After adding value inside function num=%d \n", num);
}

Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by reference in C
In call by reference, the address of the variable is passed into the function call as the actual
parameter.
The value of the actual parameters can be modified by changing the formal parameters since
the address of the actual parameters is passed.
In call by reference, the memory allocation is similar for both formal parameters and actual
parameters. All the operations in the function are performed on the value stored at the address
of the actual parameters, and the modified value gets stored at the same address.
Consider the following example for the call by reference.
Example-
#include<stdio.h>

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

void change(int *);


void main()
{
int x=100;
printf("Before function call x=%d \n", x);
change(&x);//passing reference in function
printf("After function call x=%d \n", x);
}
void change(int *num) {
printf("Before adding value inside function num=%d \n",*num);
(*num) += 100;
printf("After adding value inside function num=%d \n", *num);
}
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200

A pointer is a variable which stores address of another variable. The pointer provides a way of
accessing a variable without referring to the variable directly. The address of the variable is
used.
The declaration of the pointer,
type *var-name;
eg. int *p;
means that the expression *p is an integer type of pointer. This definition set aside two bytes
in which to store the address of an integer variable and gives this storage space the name p. If
instead of int we declare
char * p;
again, in this case 2 bytes will be occupied, but this time the address stored will be pointing to
a single byte .
Some C programming tasks are performed more easily with pointers, and other tasks, such as
dynamic memory allocation, cannot be performed without using pointers. So it becomes
necessary to learn pointers to become a perfect C programmer. Let's start learning them in
simple and easy steps.

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

Every variable is stored on a memory location and every memory location has its address
defined which can be accessed using ampersand (&) operator, which denotes an address in
memory.
void main( )
{
int x, y ;
int * ptr;
x =10;
ptr = &x;
y = *ptr;
printf (“Value of x is %d \n\n”,x);
printf (“%d is stored at addr %u \n” , x, &x);
printf (“%d is stored at addr %u \n” , *&x, &x);
printf (“%d is stored at addr %u \n” , *ptr, ptr);
printf (“%d is stored at addr %u \n” , y, &*ptr);
printf (“%d is stored at addr %u \n” , ptr, &ptr);
printf (“%d is stored at addr %u \n” , y, &y);
*ptr= 25;
printf(“\n Now x = %d \n”,x);
}
*ptr=25; this statement puts the value of 25 at a memory location whose address is the value
of ptr. We know that the value of ptr is the address of x and therefore the old value of x is
replaced by 25. This, in effect, is equivalent to assigning 25 to x. This shows how we can
change the value of a variable indirectly using a pointer and the indirection operator.
In the above example, we can pass the address of the variable a as an argument to a function in
the normal fashion. The parameters receiving the addresses should be pointers. The process of
calling a function using pointers to pass the addresses of variable is known as call by reference.
The function which is called by ‘Reference’ can change the value of the variable used in the
call.

Analysis :
1.
2.
3.
4.
5.

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

List of similar programs: Assignment No.8


1. Write a program to swapping the values of the two variables using call by values
2. Write a C to declare, assign and access array of pointers in C.
3. Write a program to display elements of a structure using pointer
4. Write a C program to print a string character by character using pointer.
5. Write a C Program to print a string using pointer.
6. Write a C program to count vowels and consonants in a string using pointer.
7. Write a C program to read array elements and print the value with the addresses.
Program:

List of questions:
1. Explain what is pointer and its applications.
2. Explain how to pass pointer arguments to a function.
3. Differentiate between call by value and call by reference.

Conclusion:

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

Experiment No.9

Title: Implement a program for dynamic memory allocation using various functions.

Outcome: Student will able to understand dynamic memory allocation using various functions.

Theory: Since C is a structured language, it has some fixed rules for programming. One of
them includes changing the size of an array. An array is a collection of items stored at
contiguous memory locations.

As can be seen, the length (size) of the array above is 9. But what if there is a requirement to
change this length (size)?
For example,
• If there is a situation where only 5 elements are needed to be entered in this array. In
this case, the remaining 4 indices are just wasting memory in this array. So there is a
requirement to lessen the length (size) of the array from 9 to 5.
• Take another situation. In this, there is an array of 9 elements with all 9 indices
filled. But there is a need to enter 3 more elements in this array. In this case, 3 indices
more are required. So the length (size) of the array needs to be changed from 9 to 12.
This procedure is referred to as Dynamic Memory Allocation in C.
Therefore, C Dynamic Memory Allocation can be defined as a procedure in which the size
of a data structure (like Array) is changed during the runtime.
C provides some functions to achieve these tasks. There are 4 library functions provided by
C defined under <stdlib.h> header file to facilitate dynamic memory allocation in C
programming. They are:
1. malloc()
2. calloc()
3. free()
4. realloc()
Let’s look at each of them in greater detail.

malloc() method
The “malloc” or “memory allocation” method in C is used to dynamically allocate a single
large block of memory with the specified size. It returns a pointer of type void which can be
cast into a pointer of any form. It doesn’t Initialize memory at execution time so that it has
initialized each block with the default garbage value initially.

Syntax of malloc() in C
Ptr=(cast-type*)malloc(byte-size)

For Example:
ptr = (int*) malloc(100 * sizeof(int));

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the
pointer ptr holds the address of the first byte in the allocated memory.

f space is insufficient, allocation fails and returns a NULL pointer.

C calloc() method
1. “calloc” or “contiguous allocation” method in C is used to dynamically
allocate the specified number of blocks of memory of the specified type. it is very
much similar to malloc() but has two different points and these are:
2. It initializes each block with a default value ‘0’.
3. It has two parameters or arguments as compare to malloc().

Syntax of calloc() in C
ptr = (cast-type*)calloc(n, element-size);
here, n is the no. of elements and element-size is the size of each element.

For Example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for 25 elements each with the size of
the float.
If space is insufficient, allocation fails and returns a NULL pointer.
free() method
“free” method in C is used to dynamically de-allocate the memory. The memory allocated
using functions malloc() and calloc() is not de-allocated on their own. Hence the free()
method is used, whenever the dynamic memory allocation takes place. It helps to reduce
wastage of memory by freeing it.

Syntax of free()
free(ptr);

realloc() method
“realloc” or “re-allocation” method in C is used to dynamically change the memory
allocation of a previously allocated memory. In other words, if the memory previously
allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically
re-allocate memory. re-allocation of memory maintains the already present value and new
blocks will be initialized with the default garbage value.

Syntax of realloc() in C
ptr = realloc(ptr, newSize);
where ptr is reallocated with new size 'newSize'.

If space is insufficient, allocation fails and returns a NULL pointer.

Analysis :
1.
2.
3.
4.

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

5.
List of similar programs: Assignment No.9
6. Write a C program to create memory for int, char and float variable at run time.
7. Write a C program to to input and print text using Dynamic Memory Allocation.
8. Write a C program to read a one dimensional array, print sum of all elements along
with inputted array elements using Dynamic Memory Allocation.
9. Write a C program to read and print the student details using structure and Dynamic
Memory Allocation.
10. Write a C program to find sum of array elements using Dynamic Memory
Allocation (malloc() and calloc()).
11. Write a C program to store a character string in a block of memory space created by
malloc() and then modify the same to store a large string.

Program:

List of questions:
6. What is dynamic memory allocation?
7. What are built-in functions for dynamic memory allocation?
8. What is the need to free the memory?
9. Differentiate malloc() and calloc() and realloc().
10. Give some applications of dynamic memory allocation

Conclusion:

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

Experiment No.10

Title: Implement a program to perform file handling operations.

Outcome: Student will able to perform file handling operations using c programming
language.
Theory:
In programming, we may require some specific input data to be generated several numbers of
times. Sometimes, it is not enough to only display the data on the console. The data to be
displayed may be very large, and only a limited amount of data can be displayed on the console,
and since the memory is volatile, it is impossible to recover the programmatically generated
data again and again. However, if we need to do so, we may store it onto the local file system
which is volatile and can be accessed every time. Here, comes the need of file handling in C.
File handling in C enables us to create, update, read, and delete the files stored on the local file
system through our C program. The following operations can be performed on a file.
• Creation of the new file
• Opening an existing file
• Reading from the file
• Writing to the file
• Deleting the file

Functions for file handling


There are many functions in the C library to open, read, write, search and close the file. A list
of file functions are given below:
No. Function Description

1 fopen() opens new or existing file

2 fprintf() write data into the file

3 fscanf() reads data from the file

4 fputc() writes a character into the file

5 fgetc() reads a character from file

6 fclose() closes the file

Opening File: fopen()

We must open a file before it can be read, write, or update. The fopen() function is used to open
a file. The syntax of the fopen() is given below.

FILE *fopen( const char * filename, const char * mode );

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

The fopen() function accepts two parameters:

o The file name (string). If the file is stored at some specific location, then we must
mention the path at which the file is stored. For example, a file name can be
like "c://some_folder/some_file.ext".
o The mode in which the file is to be opened. It is a string.

We can use one of the following modes in the fopen() function.

Mode Description

r opens a text file in read mode

w opens a text file in write mode

a opens a text file in append mode

r+ opens a text file in read and write mode

w+ opens a text file in read and write mode

a+ opens a text file in read and write mode

rb opens a binary file in read mode

wb opens a binary file in write mode

ab opens a binary file in append mode

rb+ opens a binary file in read and write mode

wb+ opens a binary file in read and write mode

ab+ opens a binary file in read and write mode

The fopen() function works in the following way.

o Firstly, It searches the file to be opened.


o Then, it loads the file from the disk and places it into the buffer. The buffer is used to
provide efficiency for the read operations.
o It sets up a character pointer which points to the first character of the file.

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

Consider the following example

//Program to read data char-by-char from keyboard, save the data into file

//again read the data char-by-char from file and display it on the console

#include<stdio.h>

#include<conio.h>

void main()
{
FILE *fp1;
char c;
clrscr();
printf("Input Data \n");
//Open the file datafile
fp1=fopen("datafile","w");
//Get a character from keyboard
while((c=getchar())!=EOF)
{
putc(c,fp1);
}
fclose(fp1);

//Reopen the file datafile


fp1=fopen("datafile","r");
//Read character from datafile
while((c=getc(fp1))!=EOF)
{
printf("%c",c);
}
fclose(fp1);
getch();
}
Output
The content of the file will be printed.

Analysis :
1.

2.

3.

4.

5.

List of similar programs: Assignment No. 10 (Solve any 7)

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

9. Write a C program to copy contents of one file into another.


10. A file named DATA contains a series of integer numbers. Code a program to read these
numbers and then write all ‘odd’ numbers to a file to be called ODD and all ‘even’
numbers to a file to be called EVEN.
11. Write a program to that appends one file at the end of another.
12. Write a C program to write into a text file using character I/O function.
13. Write a C program to read from a text file using character I/O function.
14. Write a C program to write into a binary file using block I/O fwrite().
15. Write a C program to read from a binary file using block I/O fread().
16. Write a C program to write into a text file using formatted I/O function.
17. Write a C program to read from a text file using formatted I/O function.
18. Write a C program to write into a text file using string I/O function.
19. Write a C program to read from a text file using string I/O function.

Program:

List of questions:
5. Explain types of file and file handling functions.
6. Explain different operations on file and modes in which file can be opened.
7. Explain functions used to write and read string from stream.
8. Explain functions used to write and read characters from stream.

Conclusion:

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

Experiment No.11

Title: Implement C graphics program to draw different objects.

Outcome: Student will able to perform graphics program to draw different objects.

Theory: C Graphics programming involves creating visual elements, images, and


animations using the C programming language. It allows you to draw shapes, lines, curves,
and other graphical objects on a screen. Here are some key points about C graphics
programming:
1. Graphics Libraries: In C, you can use libraries such as graphics.h, OpenGL, GDI,
or Allegro to create both 2D and 3D graphics, multimedia applications, and games.
2. Graphics Concepts: Understanding basic programming concepts is essential. You’ll
work with functions to draw shapes, change colors, and handle input.
3. Environment Setup: To get started, set up a development environment
like Code::Blocks or Visual Studio.
4. Graphics Functions: You’ll use functions from the graphics library to create visual
elements. For example:
o line(x1, y1, x2, y2) draws a line from point (x1, y1) to (x2, y2).
o circle(x, y, radius) draws a circle centered at (x, y) with the given radius.
o rectangle(left, top, right, bottom) draws a rectangle with specified coordinates.
5. Colors and Fonts: You can change colors, fonts, and other visual properties using
appropriate functions.
6. Animation: Graphics programming allows you to create simple animations, like a
moving ball or a car.

graphics.h library is used to include and facilitate graphical operations in program. C graphics
using graphics.h functions can be used to draw different shapes, display text in different fonts,
change colors and many more. Using functions of graphics.h you can make graphics
programs, animations, projects and games. You can draw circles, lines, rectangles, bars and
many other geometrical figures. You can change their colors using the available functions
and fill them.

Examples:
Input : x=250, y=200, start_angle = 0, end_angle = 360, x_rad = 100, y_rad = 50
Output :

Input : x=250, y=200, start_angle = 0,end_angle = 180, x_rad = 80, y_rad = 150
Output :

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

Explanation :The header file graphics.h contains ellipse() function which is described
below :
void ellipse(int x, int y, int start_angle, int end_angle, int x_radius, int y_radius)
In this function x, y is the location of the ellipse. x_radius and y_radius decide the radius of
form x and y.
start_angle is the starting point of angle and end_angle is the ending point of angle. The
value of angle can vary from 0 to 360 degree.
Example-Write a Program to draw basic graphics construction like line, circle, arc, ellipse
and rectangle.
Program-
#include<graphics.h>
#include<stdio.h>
int main()
{
intgd=DETECT,gm;
initgraph (&gd,&gm,"c:\\tc\\bgi");
setbkcolor(GREEN);
printf("\t\t\t\n\nLINE");
line(50,40,190,40);
printf("\t\t\n\n\n\nRECTANGLE");
rectangle(125,115,215,165);
printf("\t\t\t\n\n\n\n\n\n\nARC");
arc(120,200,180,0,30);
printf("\t\n\n\n\nCIRCLE");
circle(120,270,30);
printf("\t\n\n\n\nECLIPSE");
ellipse(120,350,0,360,30,20);
return 0;
}

Output-

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

Applications of Graphics Program in C

Graphics programming in C has a wide range of applications. Here are some examples:

• Game development: Graphics program is widely used in game development. C-


based graphics libraries such as SDL and Allegro can be used to create 2D and 3D
games.

• Computer-aided design (CAD): It is used extensively in CAD software to create and


manipulate 2D and 3D designs.

• Visualisation and data analysis: It is used to create visualizations of data in fields


such as science, engineering, and finance. This might require producing charts,
graphs, and other kinds of visualizations.

• Multimedia applications: It is used in multimedia applications such as video and


audio players, image viewers, and video editors.

• User interfaces: It is used to create graphical user interfaces (GUIs) for software
applications. This can include creating buttons, menus, and other interface elements.

• Animation and special effects: It is used to create animation and special effects in
movies, TV shows, and other media.

Advantages of Graphics Program-

• Efficient memory management

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

• Cross-platform compatibility

• Visually appealing applications

• Availability of graphics libraries

• Low-level control for advanced graphics

Analysis :
1.

2.

3.

4.

5.

List of similar programs: Assignment No. 11


1.Write a Program to draw circle filled with red colour.
2.Write a Program to draw rectangle filled blue colour.

Program:

List of questions:
1.What is C graphics program
2.What are the functions used in C graphics
3.What are the basic shapes used in the c programmimg

Conclusion:

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

Experiment No.12

Title: Implement C graphics program to demonstrate animation.

Outcome: Student will able to perform graphics program to demonstrate animation.

Theory: Animation refers to the movement on the screen of the display device created by
displaying a sequence of still images. Animation is the technique of designing, drawing,
making layouts and preparation of photographic series which are integrated into the multimedia
and gaming products. Animation connects the exploitation and management of still images to
generate the illusion of movement. A person who creates animations is called animator. He/she
use various computer technologies to capture the pictures and then to animate these in the
desired sequence.
Animation includes all the visual changes on the screen of display devices.

How does animation work?


C is a general-purpose programming language that can be used to create a wide variety of
applications, including animations. To create an animation in C, you will need to:
1. Define the objects that will be animated.
2. Create a function to draw each object.
3. Create a loop to iterate through the frames of the animation.
4. Render the animation to the screen.
Application Areas of graphics Animation

1. Education and Training: Animation is used in school, colleges and training centers for
education purpose. Flight simulators for aircraft are also animation based.

2. Entertainment: Animation methods are now commonly used in making motion pictures,
music videos and television shows, etc.

3. Computer Aided Design (CAD): One of the best applications of computer animation is
Computer Aided Design and is generally referred to as CAD. One of the earlier applications of
CAD was automobile designing. But now almost all types of designing are done by using CAD
application, and without animation, all these work can't be possible.

4. Advertising: This is one of the significant applications of computer animation. The most
important advantage of an animated advertisement is that it takes very less space and capture
people attention.

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

Example-
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h></p><p>int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\Turboc3\\BGI");</p><p> int x = getmaxx() / 2;
int y = getmaxy() / 2;
int radius = 30;</p><p> int color = 1;</p><p> while (!kbhit()) {
setcolor(color);
circle(x, y, radius);
delay(50);
cleardevice();

x += 5; // Move the circle to the right</p><p> if (x > getmaxx()) {


x = 0; // Reset to the left side when the circle goes beyond the screen
color = rand() % 15 + 1; // Change color randomly
}
}</p><p> closegraph();
return 0;
}

Explanation:
1. initgraph(&gd, &gm, "C:\\Turboc3\\BGI"); initializes the graphics mode.
2. getmaxx() and getmaxy() return the maximum X and Y coordinates of the screen.
3. The while loop continues until a key is pressed (kbhit() checks if a key is pressed).
4. setcolor(color) sets the drawing color.
5. circle(x, y, radius) draws a circle.
6. delay(50) introduces a delay of 50 milliseconds for animation.
7. cleardevice() clears the screen in each iteration.
8. x += 5 moves the circle to the right in each iteration.
9. If the circle goes beyond the screen, it resets to the left, and the color changes randomly.
Make sure to adjust the path in initgraph according to your system's graphics library
location.
Compile and run this code in an environment that supports graphics, such as Turbo C. The
program will create a window with a moving circle, changing color when it reaches the right
edge.
Example-
Program to draw animation using increasing circles filled with different colors and patterns.
#include<graphics.h>
#include<conio.h>
void main()
{
intgd=DETECT, gm, i, x, y;
initgraph(&gd, &gm, "C:\\TC\\BGI");
x=getmaxx()/3;
y=getmaxx()/3;

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

setbkcolor(WHITE);
setcolor(BLUE);
for(i=1;i<=8;i++)
{
setfillstyle(i,i);
delay(20);
circle(x, y, i*20);
floodfill(x-2+i*20,y,BLUE);
}
getch();
closegraph();
}

Output

Analysis :
1.

2.

Department of Civil Engineering


Government College of Engineering, Karad Programming for Problem Solving Lab

3.

4.

5.

List of similar programs: Assignment No. 12


1.Write a program to make screen saver in that display different size circles filled with
different colors and at random places.
2.Write a Program to implement Digital Clock.
3.Write a Program to implement Bouncing Ball in vertical direction.

Program:

List of questions:

1. What is animation?
2. What is text animation in c?
3. What is computer animation?

Conclusion:

Department of Civil Engineering

You might also like