C – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Sun, 10 Mar 2024 17:05:13 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg C – Programmerbay https://programmerbay.com 32 32 C Program to Sort an array using Selection Sort in Ascending Order https://programmerbay.com/program-to-sort-an-array-using-selection-sort/ https://programmerbay.com/program-to-sort-an-array-using-selection-sort/#respond Sun, 03 Mar 2024 17:20:38 +0000 https://www.programmerbay.com/?p=2879 The program sorts uses Selection Sort technique to sort the given array. There are bunch of sorting mechanisms such as Bubble sort, Insertion sort and more to achieve this functionality. In this, we’ll be only focusing Selection Sort .

Selection Sort

Selection sort is a sorting technique wherein at each iteration, a minimum element is selected from an unsorted array and compared with all other remaining elements. if an element is found that is smaller than already assumed minimum element,  swapping would be performed.

It divides an array into two parts. One that is already sorted and another one which is still unsorted that need to be arranged.

From unsorted sublist, the algorithm finds the minimum element and adds on to sorted category. It ends when we get a single consolidated sorted sublist.

Pseudocode

FOR i=0 to Array.Length
minimum = i
FOR j=0 to Array.Length
if A[min]< A[j])
Swap A[min] with A[j]
End IF
END FOR
END FOR

C program to sort an array using Selection Sort in Ascending Order

#include<conio.h>
#include<stdio.h>
#define size 5
void main()
{
int arr[size],i,j,temp,min;
printf("Please enter elements: \n "); 
for(i=0;i<=size-1;i++)
{
scanf("%d",&arr[i]);
}

for(i=0;i<=size-1;i++)
{
min= i;
for(j=0;j<=size-1;j++)
{
if(arr[min]<arr[j]){
temp = arr[j];
arr[j] =arr[min];
arr[min] = temp;
}
}
}

printf(" \n Entered Elements :");

for(i=0;i<=size-1;i++)
{
printf("\n %d ",arr[i]);
} 
getch();

}

Output:

Screenshot from 2024 03 10 22 22 03

 

How does Selection Sort work?

Screenshot from 2024 03 10 22 28 33

 

Lastly, it is an inefficient algorithm for the large dataset as it requires O(n2) comparisons in all cases worst, average and best case. It is simple and occasionally has an upper hand over other complicated algorithms.

]]>
https://programmerbay.com/program-to-sort-an-array-using-selection-sort/feed/ 0
C Program to Draw a Hut https://programmerbay.com/c-program-to-draw-a-hut/ https://programmerbay.com/c-program-to-draw-a-hut/#respond Thu, 29 Feb 2024 17:23:26 +0000 https://www.programmerbay.com/?p=1886 C supports a header file named “graphics.h” which enables us to draw various figures. In this, we’ll be using line and rectangle function of that particular header file to draw a hut.

C Program to draw a hut in computer graphics

Program:

#include<graphics.h>
#include<stdio.h>
#include<conio.h>
void main(){
int gd=DETECT,gm;
initgraph(&gd,&gm,"C:\\TURBOC3\\BGI");
printf("\t\t ********* HUT ********");
line(150,100,50,200);
line(150,100,350,100); 
line(150,100,300,200);
line(300,200,500,200);
line(350,100,500,200);
line(50,200,300,200);
rectangle(50,400,300,200);
rectangle(300,200,500,400);
rectangle(130,250,230,400);

getch();
closegraph();

}

Output:

Hut

]]>
https://programmerbay.com/c-program-to-draw-a-hut/feed/ 0
C Program to Wish Happy New Year https://programmerbay.com/c-program-to-wish-happy-new-year/ https://programmerbay.com/c-program-to-wish-happy-new-year/#respond Thu, 15 Feb 2024 08:35:33 +0000 https://www.programmerbay.com/?p=2284 The program uses C graphics header file capabilities to create the illusion of fireworks and show a Happy New Year message. We hope you achieve all your goals this year.

C Program to wish Happy New Year 2025

Program:

#include<stdio.h>
#include<conio.h>
#include<graphics.h>
void shoot();
void shootagain();
void area();
void explode(int,int,int);
void main()
{
int gm,gd=DETECT;
initgraph(&gd,&gm,"C:\\TURBOC3\\BGI");
shoot();
getch();
closegraph();
}
void shoot()
{
int i=0;
int x=0,y=480,x1=15,y1=460;
while(i<350)
{
area();
line(x+i,y-i,x1+i,y1-i);
delay(50);
i=i+10;
cleardevice();
}
explode(x+350,y-350,5);
shootagain();
}


void shootagain()
{
int i=0;
int x=600,y=480,x1=585,y1=460;
while(i<250)
{
setcolor(15);
area();
line(x-i,y-i,x1-i,y1-i);
delay(30);
i=i+10;
cleardevice();
}
explode(x-300,y-300,5);
}

void explode(int x,int y,int r)
{
int k,j,interval=0;
for(k=0;k<2;k++)
{
interval=interval+50;
for(j=0;j<interval;j++)
{
area();
setcolor(BLACK);
setcolor(rand()/15);
// horizontal left and right
circle(x+j,y,r+k);
circle(x-j,y,r+k);
//vertical up and down
circle(x,y+j,r+k);
circle(x,y-j,r+k);
//slighten down
circle(x+j,y+j,r+k);
circle(x-j,y-j,r+k);
//slighten up
circle(x-j,y+j,r+k);
circle(x+j,y-j,r+k);
delay(30);
cleardevice();
}
}
}
void area()
{
//Area
setcolor(15);
line(0,350,600,350);
rectangle(0,350,100,150);
rectangle(40,350,60,300);
rectangle(10,170,30,200);
rectangle(70,170,90,200);
rectangle(10,230,30,260);
rectangle(70,230,90,260);

rectangle(100,350,180,250);
line(100,250,140,180);
line(180,250,140,180);
rectangle(110,280,130,300);
rectangle(150,280,170,300);
rectangle(130,350,160,330);

rectangle(180,350,350,300);
rectangle(190,310,220,330);
rectangle(340,310,310,330);

rectangle(370,350,440,150);
rectangle(385,350,405,300);
rectangle(380,170,400,200);
rectangle(410,170,430,200);
rectangle(380,230,400,260);
rectangle(410,230,430,260);
settextstyle(BOLD_FONT,HORIZ_DIR,1);
outtextxy(110,50,"HAPPY NEW YEAR");
}

 

Output:

happynewyear

]]>
https://programmerbay.com/c-program-to-wish-happy-new-year/feed/ 0
Difference Between Delete and free() in C++ https://programmerbay.com/free-vs-delete-in-c/ https://programmerbay.com/free-vs-delete-in-c/#respond Sun, 04 Sep 2022 07:50:46 +0000 https://programmerbay.com/?p=7848 In this article, we’ll be discussing the meaning of the delete operator and free() function in C++ and the differences between them.

Both delete and free() are used for releasing the memory allocated at runtime. The main difference between them is, the delete operator deallocates memory for objects which are dynamically allocated through new keyword, whereas, the free() function deallocates memory that is dynamically allocated through malloc, calloc or realloc function.

Difference Between Delete and free() in C++

Basisfreedelete
Refers to A Library functionAn operator
Ideal forDeallocating memory occupied using malloc,calloc and realloc functionReleasing memory which is allocated using new keyword
OverridingNot PossiblePossible
Execution speedslowfast

free() function in C++ :

The main job of the free function is to release the memory which is allocated at the runtime. The free() function can be used in both C as well as C++ programming language.

It releases dynamically allocated memory created by calloc,realloc and calloc functions and provides extra reusable heap memory that can be used later. It takes pointer whose memory to be released as an argument.

void free(void *ptr)

delete operator in C++

The delete operator also has the same job like free function, that is, to release the memory which is allotted at the runtime. The delete operator is most commonly used in C++ programming.

It can defined as an operator which is used to release the memory allocated by new keyword such as objects and arrays. In C++, when delete is used with an object, it first calls the destructor of that particular object and then after deallocates the memory occupied by it. However, in the case of free(), no destructor is called of the respective object.

delete obj;

Key Differences between Delete and free() in C++

  1. The free function is basically a library function which resides in the stdlib.h header file, while delete, on the other hand, is an operator which is most commonly used in C++ programming.
  2. In the free() function, there is no call made to the destructor after the release of the runtime allocated memory. On the other hand, in case of delete operator, there is a call made to the destructor before the release of the allocated memory.
  3. In case of the free() function, as we all know that this is a function and thus it requires to get its declaration from the header file which makes it slower. In case of delete operator, as it is an operator and we all know that an operator is faster paced than a function.

 

]]>
https://programmerbay.com/free-vs-delete-in-c/feed/ 0
C Program to Calculate Average, Geometric and Harmonic Mean https://programmerbay.com/c-program-that-calculates-the-average-geometric-and-harmonic-mean/ https://programmerbay.com/c-program-that-calculates-the-average-geometric-and-harmonic-mean/#respond Thu, 25 Aug 2022 07:05:22 +0000 https://programmerbay.com/?p=5357 The C programs calculate geometric mean, average mean, and harmonic mean using their respective formulas. It simply applies these formula on the given input to calculate and print the result.

In this, we are using following formula directly in the code:

Geometric Mean :Geometric meanAverage : arthimatic meanHarmonic mean :Harmonic mean

Example 1. Program to calculate arithmetic mean in C

Program:

#include<stdio.h>


int main ()
{
  int i, size;
  float arr[10], arithmeticMean;
  float sum = 0;
  printf ("Please enter the number of elements = ");
  scanf ("%d", &size);
  printf ("Now, enter the elements \n");
  for (i = 0; i < size; i++)
    {
      printf ("Element %d : ", i + 1);
      scanf ("%f", &arr[i]);
    }
    
  for (i = 0; i < size; i++)
    {
      sum = sum + arr[i];
    }
    
  arithmeticMean = (float) (sum / size);

  printf
    ("\n Average or Arithmetic Mean = %.2f", arithmeticMean);

  return 0;
}

Output

Please enter the number of elements = 9
Now, enter the elements 
Element 1 : 1
Element 2 : 2
Element 3 : 3
Element 4 : 4 
Element 5 : 5
Element 6 : 6
Element 7 : 7
Element 8 : 8
Element 9 : 9

 Average or Arithmetic Mean = 5.00

Example 2. Program to calculate Harmonic mean in C

Program:

#include<stdio.h>


int main (){
  int i, size;
  float arr[10], oneNthValue = 0;
  float harmonicMean;
  printf ("Please enter the number of elements = ");
  scanf ("%d", &size);
  printf ("Now, enter the elements \n");
  for (i = 0; i < size; i++) {
      printf ("Element %d : ", i + 1);
      scanf ("%f", &arr[i]);
    }

  for (i = 0; i < size; i++) {
      oneNthValue = oneNthValue + 1 / arr[i];
    }

  harmonicMean = (float) size / oneNthValue;

  printf ("\n Harmonic mean= %.2f ", harmonicMean);

  return 0;
}

Output:

Please enter the number of elements = 5
Now, enter the elements 
Element 1 : 2
Element 2 : 4
Element 3 : 6
Element 4 : 8
Element 5 : 10

 Harmonic mean= 4.38

Example 3. Program to calculate Geometric mean in C

Program: 

#include<stdio.h>
#include<math.h>


int main ()
{
  int i, size;
  double product = 1, root;
  float arr[10], oneNthValue = 0;
  float geometricMean;
  printf ("Please enter the number of elements = ");
  scanf ("%d", &size);
  printf ("Now, enter the elements \n");
  for (i = 0; i < size; i++)
    {
      printf ("Element %d : ", i + 1);
      scanf ("%f", &arr[i]);
    }
    
  for (i = 0; i < size; i++)
    {
      product = (double) product *arr[i];
    }
    
  root = (double) 1 / size;
  geometricMean = (float) pow (product, root);

  printf("Geometric mean = %.2f", geometricMean);

  return 0;
}

Output:

Please enter the number of elements = 5
Now, enter the elements 
Element 1 : 12
Element 2 : 23
Element 3 : 14
Element 4 : 11
Element 5 : 17
Geometric mean = 14.85

Write a program that reads a series of n numbers and calculates the average, geometric and harmonic mean of n elements in an array in C 

Program:

#include<stdio.h>
#include<math.h>

/*
C program to calculate arithmetic mean, harmonic mean and geometric mean

*/
int main ()
{
  int i, size;
  double product = 1, root;
  float arr[10], oneNthValue = 0;
  float harmonicMean, averageMean, geometricMean;
  float sum = 0;
  printf ("Please enter the number of elements = ");
  scanf ("%d", &size);
  printf ("Now, enter the elements \n");
  for (i = 0; i < size; i++)
    {
      printf ("Element %d : ", i + 1);
      scanf ("%f", &arr[i]);
    }
    
  for (i = 0; i < size; i++)
    {
      oneNthValue = oneNthValue + 1 / arr[i];
      sum = sum + arr[i];
      product = (double) product *arr[i];
    }
    
  root = (double) 1 / size;
  harmonicMean = (float) size / oneNthValue;
  averageMean = (float) (sum / size);
  geometricMean = (float) pow (product, root);

  printf
    ("\n Harmonic mean= %.2f \n Arithmetic mean = %.2f \n Geometric mean = %.2f",
     harmonicMean, averageMean, geometricMean);

  return 0;
}

 

Output:

Please enter the number of elements = 5 
Now, enter the elements 
Element 1 : 21 
Element 2 : 3 
Element 3 : 45 
Element 4 : 76 
Element 5 : 89 
Harmonic mean= 11.69 
Arithmetic mean = 46.80 
Geometric mean = 28.61

Explanation:

  1. Getting input array  from a user
  2. Then, applying formula on the given set of elements , that would output average, geometric and harmonic mean

]]>
https://programmerbay.com/c-program-that-calculates-the-average-geometric-and-harmonic-mean/feed/ 0
C Program to Find ASCII Value of a Character https://programmerbay.com/c-program-to-print-the-integer-equivalent-of-uppercase-letters-lowercase-letters/ https://programmerbay.com/c-program-to-print-the-integer-equivalent-of-uppercase-letters-lowercase-letters/#respond Thu, 25 Aug 2022 06:56:53 +0000 https://programmerbay.com/?p=5354 The program accepts a character as an input and prints its corresponding ASCII value on output screen.

The ASCII values are ranging from 0 to 128 that cover numbers from 0 to 9, uppercase letters and lowercase letters from a to z and some special characters are also the part of this system.

For example, ASCII value of 0 is 48.

C program to find ASCII value of character

or

Write a program which prints the integer equivalent of uppercase letters, lowercase letters, digits and some special symbols.

Program:

#include <stdio.h>
int main()
{
char value;
printf("Enter a Value = ");
scanf("%c", &value);
printf("integer value of %c = %d\n", value, value);
return 0;
}

Output:

In case of number

Enter a Value = 0
ASCII integer value of 0 = 48

In case of uppercase letter

Enter a Value = A
ASCII integer value of A = 65

In case of lowercase letter

Enter a Value = a
ASCII integer value of a = 97

In case of special character

Enter a Value = @
ASCII integer value of @ = 64

Explanation:

  1. Getting letter as an input from the user
  2. printing its corresponding ASCII and character values on output screen
  3. %d format specifier represents integer for printing ASCII value and %c represents character for printing the input character.

]]>
https://programmerbay.com/c-program-to-print-the-integer-equivalent-of-uppercase-letters-lowercase-letters/feed/ 0
C program to draw arc from 135 to 270 degree using Arc() function https://programmerbay.com/c-program-to-draw-an-arc-from-135-to-270-degree/ https://programmerbay.com/c-program-to-draw-an-arc-from-135-to-270-degree/#respond Thu, 25 Aug 2022 04:44:05 +0000 https://programmerbay.com/?p=5335 Here, we will be using arc() function that is supported by graphics.h header file.

It takes 5 arguments. First two arguments are the coordinates of a circle, its successive two arguments are starting angle and end angle and last one represents the radius of the circle.

The angle value of arc() function can be ranged from 0 to 360 degree.

Syntax:

void arc(coordinateX,coordinateY,startingAngle,closingAngle,radius)

Program to draw an arc from 135 to 270 degree in C

Program:

#include<conio.h>
#include<graphics.h>
#include<stdio.h>
#include<dos.h>
int main()
{
        int gd=DETECT,gm=0;
        initgraph(&gd,&gm,"c:\\tc\\bgi");
       arc(100, 100, 135, 270, 100);
       getch();
       closegraph();
}

Output:

arc function

]]>
https://programmerbay.com/c-program-to-draw-an-arc-from-135-to-270-degree/feed/ 0
C Program To Check whether Triangle is Equilateral, Isosceles or Scalene https://programmerbay.com/c-program-to-classify-a-triangle/ https://programmerbay.com/c-program-to-classify-a-triangle/#respond Sun, 21 Aug 2022 16:33:46 +0000 https://programmerbay.com/?p=5308 The program determines the type of triangle based on the input provided by a user.

A triangle can be broadly classified according to the length of its sides and the angle between the sides.
Based on the sides, there are three types of triangle
1. Equilateral Triangle
2. Isosceles Triangle
3. Scalene Triangle

Based on the angles, there are also 3 types:
1. Acute triangle
2. Right triangle
3. Obtuse triangle

In this article, we’ll be discussing triangles that are classified based on sides, and implementing the same in the program.

type of triangle

  1. Equilateral Triangle: A triangle in which all sides are of the same length
  2. Isosceles Triangle: A triangle in which exactly two sides are equal
  3. Scalene Triangle: A triangle in which all sides are having different length

Approach to determine the type of a triangle

  1. Read the length of a triangle for the user
  2. If side1, side2 and side3 are equal to each other, then
    • print a message the triangle is an equilateral triangle
  3.  If any two from side1, side2 or side3 are having the same length, then
    • print message the triangle is isosceles triangle
  4.  If all three sides are different in length, then
    • print message the triangle is a scalene triangle

C Program To Check whether Triangle is Equilateral, Isosceles or Scalene

The program also implies Triangle Inequality Theorem to validate whether the given sides can be a triangle or not.

Program:

#include<conio.h>
#include<stdio.h>
#include<math.h>
void
main ()
{
  int a, b, c, flag = -1;
  printf (" Enter the values of a, b and c : = ");
  scanf ("%d %d %d", &a, &b, &c);
  if ((a >= 0 && a <= 10) && (b >= 0 && b <= 10) && (c >= 0 && c <= 10)){
 
 // Triangle Inequality Theorem : every side's length should be shorter than sum of other two side
      if (((a + b) > c) && ((b + c) > a) && ((c + a) > b)){
    flag = 1;
    if ((a == b) && (b == c))
      printf ("\n It is an Equilatral Triangle");
    else if ((a == b) || (b == c) || (c == a))
      printf ("\n It is an isosceles Triangle");
    else
      printf ("\n It is a Scalene Triangle");
      }
    }
    
  if (flag == -1)
    printf ("Given side inputs, can't be a triangle ");
    
  getch ();
}

 

Testing Result of the Program

Not a Triangle

 Enter the values of a, b and c : = 11 5 5
Given side inputs, can't be a triangle 

Equilateral triangle

Enter the values of a, b and c : = 4 4 4

It is an Equilateral Triangle

Isosceles Triangle

Enter the values of a, b and c : = 2 3 2

It is an isosceles Triangle

 

]]>
https://programmerbay.com/c-program-to-classify-a-triangle/feed/ 0
Program to Print Histogram in C https://programmerbay.com/c-program-to-create-histogram/ https://programmerbay.com/c-program-to-create-histogram/#respond Sat, 20 Aug 2022 09:55:04 +0000 https://programmerbay.com/?p=5379 The program accepts an array as input and prints a histogram. It uses srand() method for random data creation ranging from 0 to 20 elements.

We need to generate a frequency array for 100 numbers between 0-19. Further, we need to create, add data and print a corresponding histogram for same.

Program to Print Histogram in C

Program:

/******************************************************************************

    Program to print histogram from given array in C                

*******************************************************************************/
#include<stdio.h>
#include <stdlib.h>
#include<time.h>
int main ()
{

  int arr[100], i, barSize, p, count;

  // Variables that are being used for printing histogram 

  int firstBar = 0, secBar = 0, thirdBar = 0, fourthBar = 0, lowerRange =
    0, upperRange = 5;

  // srand for creating random values between 0 to 20 

  srand (time (0));
  for (i = 0; i < 100; i++){
      arr[i] = rand () % 20;
    }


// printing autogenerated array elements on output screen    
      printf ("Array values for the histogram :: \n");

  for (i = 0; i < 100; i++){
      printf ("%d  ", arr[i]);
    }


// printing histogram in C  by spliting bar in intervals of 5 i.e 0-5, 5-10
  for (i = 0; i < 100; i++){
      if (arr[i] < 5){
    firstBar = firstBar + 1;
  }
      else if ((arr[i] < 10) && (arr[i] > 5)){
    secBar = secBar + 1;
  }
      else if ((arr[i] < 15) && (arr[i] > 10)){
    thirdBar = thirdBar + 1;
  }
      else{
    fourthBar = fourthBar + 1;
  }
    }
    
    // Printing histogram in C
    
  printf ("\n\n*************** HISTOGRAM ***************\n\n");
  i = 1;
  barSize = firstBar;
  
  while (i <= 4){
      printf ("\n     |\n%2d-%2d|", lowerRange, upperRange);
      p = 1;
      while (p <= barSize){
    printf ("*");
    p++;
  }
  
      printf ("\n     |\n");
      if (i == 2)
  barSize = secBar;
      if (i == 3)
       barSize = thirdBar;
      if (i == 4)
       barSize = fourthBar;
         lowerRange = lowerRange + 5;
         upperRange = upperRange + 5;
         i++;
    }
  return 0;
}

 

Output:

Random data inputs are generated first:-

Array values for the histogram :: 
6  18  0  9  16  16  17  6  3  10  6  18  13  6  5  15  7  5  17  9  15  6  16  7  15  14  0  0  12  8  12  18  18  12  7  14  0  17  0  15  7  19  13  12  5  10  0  4  15  17  14  2  15  10  9  10  17  2  2  1  2  14  0  0  18  19  14  19  16  6  14  15  5  8  0  2  10  0  19  6  17  13  0  13  15  2  15  4  4  18  6  6  4  18  6  3  9  12  14  18

Plotted to Histogram:

*************** HISTOGRAM ***************


     |
 0- 5|************************
     |

     |
 5-10|************************
     |

     |
10-15|********************
     |

     |
15-20|****************
     |

Explanation:

  1. We have generated frequency data, with values ranging from 0 to 19
  2. To create a histogram, we have used intervals 0-5,5- 10, 10-15, 15-20 with 5 class size
  3. In order to create 4 bars, we have used 4 variables named, firstBar, secBar, thirdBar, and fourthBar
  4. While iterating frequency data, if the value lies between 0 to 5, count it as 1 and add it to the first bar
  5. Similarly, if it ranges from 5 to 10, then add 1 to secBar variable
  6. Lastly, we have printed the histogram on the output screen

]]>
https://programmerbay.com/c-program-to-create-histogram/feed/ 0
C Program to Convert Minutes into Hours and Minutes https://programmerbay.com/c-program-to-convert-minutes-into-hours/ https://programmerbay.com/c-program-to-convert-minutes-into-hours/#respond Sat, 20 Aug 2022 08:15:45 +0000 https://programmerbay.com/?p=5362 The program converts minute to hours & minute format and prints the result on the output screen. It uses basic formula for converting the given minute input to the respective hours.

hours = minute / 60

Write a program that takes minutes as input and converts it into hours and minutes.

Program:

#include<stdio.h>
int main()
{
int minute;
printf("\n\n\tEnter minutes = ");
scanf("%d",&minute);
printf("\n\t Entered minutes = %d minutes \n\t Which is equivalent to = %d hours and %d minutes",minute,minute/60,minute%60);
return 0;
}

Output:

minute to hour

 

Explanation:

  1. Getting input from a user
  2. Then, simply dividing it by 60, that would give quotient as hours and remainder(using modulo operator) as minutes

]]>
https://programmerbay.com/c-program-to-convert-minutes-into-hours/feed/ 0