c Programming Lab Record 23-24
c Programming Lab Record 23-24
Vi Text Editor:
Vi is an old but popular text editor for Linux and other Unix systems. It works differently than
most modern text editors. Instead of just typing directly, Vi has different “modes” for different
tasks. One mode is for moving the cursor around and making edits. Another mode is for inserting
new text. There are also modes for running commands. While Vi can be tricky to learn at first
with all its modes and keyboard shortcuts, many experienced programmers love using Vi because
it allows them to edit files very quickly and efficiently without using a mouse or menus once they
get the hang of it. Vi is extremely lightweight and available on virtually every Unix system,
making it a reliable choice.
Navigation in Vi Editor:
• Go to normal mode first by hitting Esc key
• Use h,j,k,l keys to move cursor left, down, up, right
• Or use arrow keys
• Word movement with w (next word) or b (prev word)
• Go to start/end of lines with 0 or $
Vim Editor :
Vim is a popular text editor program used on Linux and other Unix operating systems. It is an
improved and updated version of the old vi editor. While vim looks basic, it is actually a very
powerful tool for editing files efficiently, especially for programmers and developers. What
makes vim unique is that it has different “modes” for different tasks like navigating files, editing
text, and running commands. This modal approach with keyboard shortcuts allows very fast and
precise text editing once you learn it. Though vim has a learning curve at first, many Linux users
prefer it over regular text editors because it provides more control and capabilities through its
modes and key combinations. Vim also supports adding extra features through plugins.
Emacs Editor:
Emacs is a popular text editor choice on Linux systems. It comes pre-installed or can be easily
installed via package managers on most Linux distributions. Emacs integrates smoothly with the
command-line interface of Linux, making it well-suited for terminal-based editing and remote use
over SSH. The customizability of Emacs through its own Lisp language allows tapping into
numerous community extensions tailored for Linux users’ needs like coding and system
administration. Although it has a steep learning curve initially, Emacs’ broad capabilities and
ability to extensively personalize the editing environment make it a powerful tool for Linux
power users willing to invest time in mastering it.
B. Exposure to Turbo C:
Turbo C was an integrated development environment (IDE) for programming in the C language. It
was developed by Borland and first introduced in 1987. At the time, Turbo C was known for its
compact size, comprehensive manual, fast compile speed and low price. It had many similarities to
an earlier Borland product, Turbo Pascal, such as an IDE, a low price and a fast compiler, but was
not as successful because of competition in the C compiler market.
Turbo C was a software development tool for writing programs in the C language. As an IDE, it
included a source code editor, a fast compiler, a linker and an offline help file for reference. Version
2 included a built-in debugger. Turbo C was a follow-up product to Borland’s Turbo Pascal, which
had gained widespread use in educational institutions because the Pascal language was suited for
teaching programming to students. Although Turbo C was initially developed by a different
company, it shared a lot of features with Turbo Pascal, namely, the look-and-feel of the interface
The first version was released on May 13, 1987, and it offered the first-ever edit-compile-run
environment for software development on IBM PCs. Turbo C was not originally developed by
Borland but was bought from Bob Jervis and was initially called Wizard C. Turbo Pascal did not
have pull-down menus before this time, and it was only on its fourth version that it received a face
lift to look like Turbo C.
Borland as a company no longer develops and sells these products, but Turbo C still lives on as a
free download from various online repositories, although it is really an old technology without real
technical support and is no longer viable for modern software development. Turbo C eventually
evolved into Turbo C++, then into Borland C++ and, finally, into C++ Builder.
Turbo C features:
• Inline assembly with full access to the C language symbolic structures and names — This
allowed programmers to write some assembly language codes right into their programs
without the need for a separate assembler.
• Support for all memory models — This had to do with the segmented memory architecture
used by 16-bit processors of that era, where each segment was limited to 64 kilobytes (Kb).
The models were called tiny, small, medium, large and huge, which determined the size of
the data used by a program, as well as the size of the program itself. For example, with the
tiny model, both the data and the program must fit within a single 64-Kb segment. In the
small model, the data and the program each used a different 64-Kb segment. So in order to
create a program larger than 64 Kb or one that manipulates data larger than 64 Kb, the
medium, large and huge memory models had to be used. In contrast, 32-bit processors used
a flat memory model and did not have this limitation.
• Speed or size optimization — The compiler could be configured to produce an executable
program that was either fast or small in size, but not both.
• Constant folding — This feature allowed the Turbo C compiler to evaluate constant
expressions during compile time rather than during run time.
C. Explore to Hacker Rank or any other Online coding platform and compiler environment.
What Is HackerRank Used For?
For students and those learning coding or programming, HackerRank is an excellent tool for
practicing new skills and developing proficiency in programming languages. Employers also use
HackerRank to analyze candidates’ coding abilities before investing in interviews.
ROLL NO.: ADITYA COLLEGE OF ENGINEERING (A) PAGE | 5
DEPARTMENT OF H &Bs COMPUTER PROGRAMMING LAB
HackerRank Tests for Candidates
When applying for software engineering or related computer science jobs, you may need to
complete a HackerRank test as part of your application or interview process.
From an employer standpoint, these tests “provide a standardized and objective way to evaluate
coding proficiency, problem-solving abilities, and algorithmic knowledge,” says Joseph Harisson,
CEO of IT Companies Network.
Companies can also determine minimum scores for HackerRank challenges, so those without the
required skills are weeded out before progressing.
The platform allows employers to “tailor the assessment process and identify candidates with the
right technical expertise,” says Harisson.
In a tech career hiring process, the employer may ask you to complete a challenge on HackerRank
in subject areas like:
• Algorithms
• Data structures
• Mathematics
• Artificial intelligence (AI) and machine learning (ML)
• C and C++
• Java
• Python
• Ruby
• SQL
• Databases and data storage
• Linux
• Functional programming
D. “Hello World” in C
#include <stdio.h>
int main() {
// printf() displays the string inside quotation
printf("Hello, World!");
return 0;
}
Output:
Hello, World!
• The #include is a preprocessor command that tells the compiler to include the contents
of stdio.h (standard input and output) file in the program.
• The stdio.h file contains functions such as scanf() and printf() to take input and display
output respectively.
• If you use the printf() function without writing #include <stdio.h>, the program will not
compile.
• The execution of a C program starts from the main() function.
• printf() is a library function to send formatted output to the screen. In this
program, printf() displays Hello, World! text on the screen.
• The return 0; statement is the "Exit status" of the program. In simple terms, the program
ends with this statement.
E. Write a simple program to read int, float, char and string using scanf() and display using
printf() in all the above given platforms.
/* C program to Print Integer, Char, and Float value */
#include <stdio.h>
int main()
{
int Integer;
char Character;
float InputFloat;
char string;
printf(" Please Enter a Character : ");
scanf("%c", &Character);
printf(" Please Enter an Integer Value : ");
scanf("%d", &Integer);
printf(" Please Enter Float Value : ");
scanf("%f", &InputFloat);
printf(" Please Enter String : ");
scanf("%s", &string);
printf(" \n The Character that you Entered is : %c", Character);
printf(" \n The Integer Value that you Entered is : %d", Integer);
• Bitwise OR Operator
• Bitwise AND Operator
• Unary Operator (Binary One’s complement operator)
• Bitwise XOR Operator
• Binary Right Shift Operator
• Binary Left Shift Operator
#include <stdio.h>
main() {
unsigned int p = 60; /* 60 = 0011 1100 */
unsigned int q = 13; /* 13 = 0000 1101 */
int r = 0;
r = p | q; /* 61 = 0011 1101 */
printf(“Line 1 – The value of r is %d\n”, r );
r = p & q; /* 12 = 0000 1100 */
printf(“Line 2 – The value of r is %d\n”, r );
r = ~p; /*-61 = 1100 0011 */
printf(“Line 3 – The value of r is %d\n”, r );
int main()
{
float fh,cl;
int choice;
if(choice ==1){
printf("\nEnter temperature in Fahrenheit: ");
scanf("%f",&fh);
cl= (fh - 32) / 1.8;
printf("Temperature in Celsius: %.2f",cl);
}
Output:
First Run:
1: Convert temperature from Fahrenheit to Celsius.
2: Convert temperature from Celsius to Fahrenheit.
Enter your choice (1, 2): 1
Second Run:
1: Convert temperature from Fahrenheit to Celsius.
2: Convert temperature from Celsius to Fahrenheit.
Enter your choice (1, 2): 2
Third Run:
1: Convert temperature from Fahrenheit to Celsius.
2: Convert temperature from Celsius to Fahrenheit.
Enter your choice (1, 2): 3
#include<stdio.h>
main()
{
long p=1000,n=10,r=2;
clrscr();
printf("simple interest %ld", p*n*r/100);
getch();
}
Output:
Simple interest 200
Output:
Enter the value: 16
(a) Root value of given of given number:4 Find the area of circle, square, rectangle and
triangle
#include<stdio.h>
#include<math.h>
main(){
int choice;
printf("Enter 1 to find area of Triangle\n 2 for finding area of Square\n 3 for finding area of
Circle\n 4 for finding area of Rectangle\n 5 for Parallelogram");
scanf("%d",&choice);
switch(choice) {
case 1: {
int a,b,c;
float s,area;
printf("Enter sides of triangle");
(c)Take marks of 5 subjects in integers, find the total in integer and average in float
#include<stdio.h>
main( )
{
int t, h, e, m, sc, so, to;
float avg;
clrscr( );
printf("Enter the six subject marks:\n");
scanf("%d %d %d %d %d %d", &t, &h, &e, &m,
&sc, &so);
to=t + h + e + m + sc + so;
avg=to/6;
printf("Total marks: %d", to);
printf("Average marks: %f", avg);
getch( );
The conditional statements (also known as decision control structures) such as if, if else, switch,
etc. are used for decision-making purposes in C programs.
They are also known as Decision-Making Statements and are used to evaluate one or more
conditions and make the decision whether to execute a set of statements or not. These decision-
making statements in programming languages decide the direction of the flow of program
execution.
#include<stdio.h>
main()
{
int pr,pvr,tu,sc;
float uc;
clrscr();
printf("Enter the present Reading:");
scanf("%d",&pr);
“for” Loop in C
Objective: Learn the usage of the for loop
In programming, a loop is used to repeat a block of code until the specified condition is met.
for loop
while loop
do...while loop
We will learn about for loop in this tutorial. In the next tutorial, we will learn about while and
do...while loop.
for Loop
The syntax of the for loop is:
#include<stdio.h>
main()
{
int n,c=0,i=2;
clrscr();
printf("Enter the number:");
scanf("%d",&n);
while(i<n)
{
if(n%i==0)
c=c+1;
i++;
}
if(c==0)
printf("Given number prime number");
else
printf("Given number not prime number");
getch();
}
Output:
Enter thye any integer number: 7
Given number prime number
while (originalNum != 0) {
// remainder contains the last digit
remainder = originalNum % 10;
Output:
Enter a three-digit integer: 371
371 is an Armstrong number.
#include <stdio.h>
int main()
{
int n;
printf("Enter the number of rows");
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
{
printf("* ");
}
printf("\n");
}
return 0;
}
Output:
#include <stdio.h>
int main()
{
int no_row, c = 1, blk, i, j;
printf("Input number of rows: ");
scanf("%d", &no_row);
for (i = 0; i < no_row; i++) {
Output:
Input number of rows: 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr; //declaration of integer pointer
int limit; //to store array limit
int i; //loop counter
int sum; //to store sum of all elements
//free memory
free(ptr); //hey, don't forget to free dynamically allocated memory.
return 0;
Output:
Enter limit of the array: 5
Enter element 01: 100
Enter element 02: 200
Enter element 03: 300
Enter element 04: 400
Enter element 05: 500
#include<stdio.h>
int main()
{
int n, arr[n], i;
printf("Enter the size of the array: ");
scanf("%d", &n);
printf("Enter the elements: ");
for(i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
int rev[n], j = 0;
for(i = n-1; i >= 0; i--)
{
rev[j] = arr[i];
j++;
}
printf("The Reversed array: ");
for(i = 0; i < n; i++)
{
printf("%d ", rev[i]);
}
}
#include<stdio.h>
main()
{
int a[50],i,n,large,small;
clrscr();
printf("Enter how many elements enter into
array:");
scanf("%d",&n);
printf("Enter %d Integer elements:\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
large=a[0];
small=a[0];
for(i=1;i<n;i++)
{
if(large<a[i])
large=a[i];
else if(small>a[i])
small=a[i];
}
printf("\nLargest number in array:%d",large);
printf("\nSmallest number in array:%d",small);
getch();
}
Output:
Enter how many elements enter into array:4
Enter 4 integer elements:
10
#include<stdio.h>
#define size 5
int main()
{
int arr[size] = {1, 20, 5, 78, 30};
int element, pos, i;
arr[pos] = element;
return 0;
}
Output:
Input
int arr[5] = {10, 20, 30, 40, 50}
Element = 100 position = 2.
Output
{10, 20, 100, 30, 40, 50}
#include <stdio.h>
int main()
{
int arr[] = {1, 2, 3, 4, 2, 7, 8, 8, 3};
int length = sizeof(arr)/sizeof(arr[0]);
printf("Duplicate elements in given array: \n");
for(int i = 0; i < length; i++) {
for(int j = i + 1; j < length; j++) {
if(arr[i] == arr[j])
printf("%d\n", arr[j]);
}
}
return 0;
}
Output:
#include <stdio.h>
int main()
{
int array[100], n, c, d, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0 ; c < n - 1; c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use '<' instead of '>' */
{
Output:
#include <stdio.h>
int main() {
int m, n, i, j;
printf("Enter the number of rows and columns of the matrices: ");
scanf("%d%d", &m, &n);
int a[m][n], b[m][n], c[m][n];
printf("Enter the elements of matrix A: \n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &a[i][j]);
}
}
printf("Enter the elements of matrix B: \n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &b[i][j]);
}
}
// add the matrices
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
c[i][j] = a[i][j] + b[i][j];
}
}
// print the result
printf("The sum of the two matrices is: \n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("%d ", c[i][j]);
}
printf("\n");
}
return 0;
}
Output:
Enter the number of rows and columns of the matrices: 2 2
Enter the elements of matrix A:
12
34
Enter the elements of matrix B:
#include<stdio.h>
#include<stdlib.h>
int main(){
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
system("cls");
printf("enter the number of row=");
scanf("%d",&r);
printf("enter the number of column=");
scanf("%d",&c);
printf("enter the first matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter the second matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
}
}
#include<stdio.h>
int main(){
int m, n;
printf("Enter the number of rows: ");
scanf("%d", &m);
printf("Enter the number of columns: ");
scanf("%d", &n);
int matrix[10^5][10^5];
printf("Enter the elements of the matrix:\n");
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
scanf("%d", &matrix[i][j]);
}
}
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
printf("The transposed matrix is:\n");
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
#include <stdio.h>
int main()
{
int i, j, rows, columns, trace = 0;
printf("Enter Matrix Rows and Columns = ");
scanf("%d %d", &rows, &columns);
int Tra_arr[rows][columns];
printf("Please Enter the Matrix Items = \n");
i = 0;
while(i < rows)
{
j = 0;
while(j < columns)
{
scanf("%d", &Tra_arr[i][j]);
j++;
}
i++;
}
i = 0;
while(i < rows)
Output:
Enter Matrix Rows and Columns = 3 3
Please Enter the Matrix Items =
10 20 30
40 50 60
70 80 90
The Trace Of the Matrix = 150
#include <stdio.h>
int main() {
int arr1[10][10], i, j, n;
float determinant = 0;
printf("\n\nDisplay the lower triangular of a given matrix :\n");
printf("Input the size of the square matrix : ");
scanf("%d", &n);
printf("Input elements in the matrix :\n");
for (i = 0; i < n; i++) {
1 2 3
0 5 6
0 0 9
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
char *s;
s = malloc(1024 * sizeof(char));
scanf("%[^\n]", s);
*c = '\n';
printf("%s", s);
return 0;
Output:
Learning C is fun
Learning
is
fun
(b) Count number of alphabets (lowercase, uppercase, consonants, vowels) and digits
#include <stdio.h>
int main()
{
char line[150];
int vowels, consonant, digit, space;
Output:
Enter a line of string: C++ 20 is the latest version of C++ yet.
Vowels: 9
Consonants: 16
Digits: 2
White spaces: 8
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
int i;
return 0;
}
Output:
Please Enter any String: PREPinsta
Toggoled string: prepINSTA
#include <stdio.h>
#include <string.h>
void solve(char *s){
int freq[10] = {0};
for(int i = 0; i < strlen(s); i++){
if(s[i] >= '0' && s[i] <= '9'){
freq[s[i] - '0']++ ;
}
}
Output:
(Number 2, Freq 1)
(Number 3, Freq 1)
(Number 5, Freq 2)
(Number 6, Freq 3)
(Number 8, Freq 2)
(Number 9, Freq 1)
(e) Find string length, concatenate two strings, reverse a string using built-in and without built-
in string functions
#include<stdio.h>
#include<conio.h>
void main()
{
char arr[30],s1[10],s2[10],s3[10];
int opt,i=0,j,len=0;
//clrscr();
printf("Enter any option\n\n");
printf("1: Find out length of the string\n");
printf("2: Concatenate of the two string\n");
Advantage of functions in C
Functions in C serve an extremely useful feature and provides the following advantages:
The functions decrease the iteration of the same statements in a program. So, they decrease the
program’s size.
The function improves code readability by offering modularity to the program.
Functions can be called multiple times from different parts of a program, promoting code
reusability.
They make programs easy to understand and manage by breaking a large program into smaller
pieces.
Types of Functions in C
There are 2 types of functions in C programming:
Library Functions:
They are also known as built-in functions. They are directly usable; no need to define them. The
examples of these types of functions in C are printf(), scanf(), puts(), gets(), floor(), ceil(), etc.
User-defined functions:
The functions which the programmer creates are called user-defined functions. The user-defined
functions in C should be declared and defined before being used. These functions can be improved
and altered as per the programmer’s need. They can be used multiple times. So, they decrease the
code’s complexity.
Header Files for Library Functions in C Programming
The header files in C contain a set of predefined standard library functions and other entities. They
are included in a program using #include <header_filename.h>. These files provide the necessary
declarations and definitions for the C standard library.
The example of a header file for library functions in C is “#include <stdio.h>”. It includes the
standard input/output functions.
Return Value
A C function doesn't need to return a value from the function. If you don't want to return value from
the function, you must use void for the return type.
Here is one of the function in C programming examples that demonstrates the use of a function
without a return value.
#include <stdio.h>
In the above example, the sum takes two integer values a and b. It calculates the sum and stores the
result in variable c. Subsequently, the function returns the result.
The main function prompts the user to enter two numbers. The sum function is called in which the
entered numbers are passed as arguments. The value returned from the sum function is assigned to
the addition variable, which is finally printed to the console.
Different aspects of function calling
Function calling in C incorporates various aspects. They are discussed below.
i. Function Declaration:
It mentions the name of the function, the types of its parameters (if exist), and its return type.
For example,
int add(int p, int q);
ii. Function Definition:
This aspect represents the actual implementation of the function. It contains the function body that
includes the statements to be executed.
For example,
int add(int m, int n)
{
return m + n;
}
iii. Function Parameters:
Functions in C can accept zero or more parameters (also known as arguments). These parameters
are used to pass values to that function.
iv. Return Values:
Functions can return a value to the caller through the return statement.
v. Calling Conventions:
Calling conventions specify the conventions and rules for the way function calls are invoked and
the way parameters are passed.
vi. Function Call:
In the above program, the defined function, i.e., printhelloMessage(), neither has arguments nor a
return value. It simply prints the message written in the printf function.
Example for Function with argument and without return value
#include <stdio.h>
// Function declaration
void printSum(int m, int n);
// Function definition
void printSum(int m, int n)
{
In the above program, the defined function printSum accepts two arguments, i.e., m and n. It
calculates the sum of the values of these arguments. The printf function in the main body calls this
function, and finally, the program prints the sum of the numbers.
Recursive Functions in C Programming
The functions in C are recursive if they can call themselves until the exit condition is fulfilled.
#include <stdio.h>
// The following recursive function calculates the Fibonacci sequence
int fibonacci(int m)
{
if (m == 0)
{
return 0;
}
else if (m == 1)
{
return 1;
int main() {
int num;
return 0;
}
Output:
Please enter a number to calculate the Fibonacci sequence: 16
Fibonacci sequence of 16 is 987
In the above program, the ‘fibonacci’ function generates the Fibonacci series up to the given
number using recursion.
Inline Functions in C Programming
When you use functions in C, the pointer for execution flow transfers to the function definition after
the function call. So, you need an additional pointer that jumps to the definition and returns. The
use of inline functions helps prevent the use of an extra pointer.
Inline functions are functions wherein rather than calling the function, we substitute it with the
program code. Hence, the pointer doesn’t have to transfer back to the definition. To make an inline
function, you must use the keyword inline before a function.
The syntax of an inline function is:
inline function_name (){
//function definition
The given program uses an inline function in C to calculate the minimum of two numbers. The
program prompts the user to enter two numbers, calculates the minimum using the inline function,
and then displays the result.
(b)Fibonacci Numbers using recursion
Objective: Complete the recursive function
#include <stdio.h>
// Recursive function to calculate Fibonacci numbersint fibonacci(int n) {
if (n <= 1)
{
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
Output:
Enter the number of terms in the Fibonacci sequence:5
Fibonacci Sequence:
0
1
1
2
3
Output:
Enter the Number to Find Factorial :5
Factorial of 5 is 120
Output:
Enter the number: 2345
Sum of digits in 2345 is 14
Output:
Enter any two numbers to find lcm: 12
30
LCM of 12 and 30 = 60
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
//Complete the following function.
int find_nth_term(int n, int a, int b, int c)
{
//Write your code here.
(a) Pointers in C
Basic functionalities of pointers in C
A function pointer in C is a variable that stores the address of a function. It allows you to refer to a
function by using its pointer and later call the function using that function pointer. This provides
flexibility in calling functions dynamically and can be useful in scenarios where you want to select
and call different functions based on certain conditions or requirements.
The function pointers in C are declared using the asterisk (*) operator to obtain the value saved in
an address.
Advantages of Function Pointers
A function pointer in C is useful to generate function calls to which they point. Hence, the
programmers can pass them as arguments. The function pointers enhance the code’s readability.
You can access many identical functions using a single line of code.
Other prominent advantages of function pointer in C include passing functions as parameters to
other functions. Therefore, you can create generic functions which can be used with any function
provided that it possesses the right signature.
Syntax of Function Pointer in C
Here is the function pointer syntax in C.
return type (*ptr_name)(type1, type2...);
Let’s look at an example:
int (*ip) (int);
*ip is a pointer in the above declaration. It points to a function that returns an int value and also
accepts an integer value as an argument.
Functions Using Pointer Variables
In C, you can pass pointers as function arguments and return pointers from the function. If you want
to pass pointers in the function, you just need to declare the function parameter as a pointer type.
Here’s a C program demonstrating functions using pointer variables.
#include <stdio.h>
void increment(int *numb);
int main()
{
int numb = 10;
printf("The number before increment is: num = %d\n", numb);
#include <stdio.h>
// C program to swap two integers through pointers
void swap(int* x, int* y) {
int temp = *x;
*x = *y;
*y = temp;
}
Calling a function using a pointer is the same as calling a function using the function’s name.
#include <stdio.h>
int sum = a + b;
int main()
return 0;
Output:
In the above program, the add function accepts two integers as arguments, computes their sum, and
displays the output. The declaration of addPtr function pointers happens with the parameter types
and return type that match the functions they would point to.
addPtr = add command assigns the add function’s address to the addPtr function pointer. AddPtr(7,
8) calls the add function through the addPtr function pointer (with the input arguments).
Output:
Enter 3 Strings:
Ball Apple Cat
Original array: Ball Apple Cat
Sorted Array: Apple Ball Cat
(e) Swap two numbers using functions and pointers - call by value and reference
(i)call by reference
#include <stdio.h>swap (int *, int *);int main(){
Output:
int temp;
temp = a;
a = b;
b = temp;
int main(void)
scanf("%d %d",&first,&second);
printf("\n After swap function called 1st number is %d and 2nd number is %d", first ,second);
return 0;
Output:
int main()
{
// Memory allocated
printf("Memory successfully allocated using "
"malloc.\n");
return 0;
}
Output:
Enter size of elements:5
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5,
Output:
Town with the most number of packages is B
Town with the most number of packages is A
A:
0:
a
b
1:
c
e
f
h
B:
0:
D
Out Put:
#include <stdio.h>
union test {
// Bit-field member x with 3 bits
unsigned int x : 3;
// Bit-field member y with 3 bits
unsigned int y : 3;
// Regular integer member z
int z;
};
int main()
{
// Declare a variable t of type union test
union test t;
// Assign the value 5 to x (3 bits)
t.x = 5;
// Assign the value 4 to y (3 bits)
t.y = 4;
// Assign the value 1 to z (32 bits)
t.z = 1;
// Print the values of x, y, and z
printf("t.x = %d, t.y = %d, t.z = %d", t.x, t.y, t.z);
return 0;
}
Output:
t.x = 1, t.y = 1, t.z = 1
int main() {
FILE *file;
char buffer[100];
if (file == NULL) {
return 1;
fclose(file);
if (file == NULL) {
return 2;
fclose(file);
return 0;
b)write into text and read text from binary file using fread() and fwrite()
#include <stdio.h>
int main() {
FILE *sourceFile, *destinationFile;
char buffer[1024]; // Buffer to store data
if (sourceFile == NULL) {
return 1;
if (destinationFile == NULL) {
fclose(sourceFile);
return 2;
size_t bytesRead;
#include <stdio.h>
int main() {
char ch;
if (sourceFile == NULL) {
return 1;
if (destinationFile == NULL) {
fclose(sourceFile);
return 2;
fputc(ch, destinationFile);
fclose(sourceFile);
fclose(destinationFile);
return 0;
d)Merge two files into the third file using command line arguments
#include <stdio.h>
int main(int argc, char *argv[]) {
return 1;
char ch;
if (sourceFile1 == NULL) {
return 2;
if (sourceFile2 == NULL) {
fclose(sourceFile1);
return 3;
if (destinationFile == NULL) {
fclose(sourceFile1);
fclose(sourceFile2);
return 4;
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct triangle
Input:
3
7 24 25
5 12 13
345
Output:
345
5 12 13
7 24 25
e)//Permutation of strings
#include <stdio.h>
#include <string.h>
// Function to swap characters at positions i and j in a string
void swap(char *x, char *y) {
char temp = *x;
*x = *y;
*y = temp;
}
// Function to generate permutations of a string
void generatePermutations(char *str, int start, int end) {
if (start == end) {
printf("%s\n", str);