ME Lab Manual
ME Lab Manual
Experiment No .1
Outcome: Students can execute a simple C program language and get familiarized with
programming environment.
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 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.
• 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.
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.
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.
1. Turbo C++
2. Eclipse
3. Code Blocks
4. Dev C++
5. NetBeans
Analysis:
1.
2.
3.
4.
5.
Programs:
1. Write a C program to display your personal details.
Output:
Conclusion:
Experiment No.2
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.
If the test expression is true, then the true block statements are executed; otherwise
the false block statement will be executed.
When a series of decisions are involved, we may have to use more than one if….else
statements, in nested form as follows.
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.
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:
Note: A label can be anywhere in the program, either before or after the goto label;
statement.
Analysi
s:
1.
2.
3.
4.
5.
Program:
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:
Experiment No.3
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-
Syntax-
for (initialize expression; test expression; update expression)
{
//
// body of for loop
//
}
Example:
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;
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;
}
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;
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
return 0;
}
Output-
Hello World
Analysis :
1.
2.
3.
4.
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:
Experiment No. 4
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.
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:
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:
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
}
Example –
Function without argument and return value
#include<stdio.h>
void printName();
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-
24
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-
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);
}
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.
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;
}
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:
Recursion Case: Contains the recursive call(s) and divides the problem into smaller
subproblems.
Base condition: n == 0
Advantages:
Disadvantages:
Analysis
1.
2.
3.
4.
5.
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:
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;
}
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:
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.
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
Arr[2][2]=5
Arr[3][0]=4
Arr[3][1]=5
Arr[3][2]=6
Analysis
1.
2.
3.
4.
5.
Program:
List of questions:
1. Explain 1-D array.
2. Write short note on 2-D array
Conclusion:
Experiment No. 6
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".
If you follow the rule of array initialization then you can write the above statement as
follows:
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.
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
Analysis :
1.
2.
3.
4.
5.
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:
Experiment No. 7
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.
struct tag_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.
0 20 24 26
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.
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];
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];
// 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.
4.
5.
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
Experiment No. 8
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);
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.
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:
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>
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.
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.
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:
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));
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.
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'.
Analysis :
1.
2.
3.
4.
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:
Experiment No.10
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
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.
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.
Mode Description
//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);
Analysis :
1.
2.
3.
4.
5.
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:
Experiment No.11
Outcome: Student will able to perform graphics program to draw different objects.
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 :
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-
Graphics programming in C has a wide range of applications. Here are some examples:
• 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.
• Cross-platform compatibility
Analysis :
1.
2.
3.
4.
5.
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:
Experiment No.12
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.
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.
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();
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;
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.
3.
4.
5.
Program:
List of questions:
1. What is animation?
2. What is text animation in c?
3. What is computer animation?
Conclusion: