//C Program to hibernate Windows #includevoid main() { system("shutdown /h"); }
Search This Blog
C Program to Hibernate Windows
Do you want to hibernate your Windows computer from c? This is a c program to hibernate Windows operating System. If you execute this c program, it will hibernate your Windows computer instantly. The following is the c code to hibernate Windows:
C Program to Run Applications to Open a File in Windows
In this post, we will see how to run an executable to open a file. This will tell you open a file with specified application. This can be used like the open with option in operating systems. To open a file, most applications, are launched with the path to the file as command line argument (command line parameter). The following c program will open paint with a command-line argument. mspaint command opens paint. Or you can use "C:\\Windows\\System 32\\mspaint.exe". The exepected command-line argument to paint is the path to an image file. Then the paint application opens that file as image if possible.
#includeThe above c program will open the image flower.jpg using paint application in Windowsvoid main() { system("C:\\Windows\\System32\\mspaint.exe \"C:\\Users\\Shareef\\Desktop\\flower.jpg\""); }
C Program to Launch or Execute an Application With Command Line Parameters
In this post, we will see how to run an executable with command line arguments. This will tell you how to execute any application with command-line arguments using c code. The following c program will open paint with a command-line argument. mspaint command open paint. Or you can use "C:\\Windows\\System 32\\mspaint.exe". The exepected command-line argument to paint is the path to an image file. Then the paint application opene that file as image if possible.
//How to run applications with command line arguments in c #includevoid main() { system("C:\\Windows\\System32\\mspaint.exe \"C:\\Users\\Shareef\\Desktop\\flower.jpg\""); }
C Program to Schedule a Shutdown - How to Schedule Shutdown in C
You can schedule shutdown in Windows or Linux using C program. We will see how to schedule a shutdown using a c program. To schedule a shutdown in Windows, we execute the Windows command shutdown /s /t sec (where sec is time delay before shutdown in seconds). In Linux, we execute the command shutdown -h +600. The c programs to schedule a shutdown in Windows and Linux are given separately.
C Program to Shutdown Computer - How to Shutdown Computer Using C Code
Computer can be shutdown using c program. But the commands are different in Windows and Linux. The system() function in c can be used to execute system commands ( Windows command or Linux command ). To shutdown the computer using c program, we execute the appropriate shutdown command using the system() function.
How to Execute Windows Commands in C
You may have used Windows commands like ipconfig, netstat, type, set, mkdir, cd etc in cmd (DOS Prompt or Command Prompt). You can execute these commands from a C program. This post will tell you how to execute Windows commands (cmd commands) from c program. To execute different Windows commands, you can use the system() function c language. The system() function is used to invoke command processor to execute a given command. The command which is to be executed is passed as argument to the function. An example c program with system() function is shown below.
C Program to Logoff or Signout From Windows
You can logoff (also called logout or sign out) from a windows computer using c program. This can be done by executing a command. You just have to execute the command shutdown /l which executes shutdown.exe with command line parameter /l to force logout from Windows. The system() function in c can be used to execute any system commands. Therefore, the following simple c program when executed, will logout you from Windows instantly.
#include<stdio.h> void main() { system("shutdown /l"); }
Digital Clock C Program
This is a c program to display a digital clock showing correct time. It reads time at 1 second interval and displays it on the screen. To know how to get date and time in C, see this post: How to Get Time and Date in C - C Program to Read and Display Time and Date
#include<stdio.h> #include<graphics.h> #include<time.h> int gd=DETECT,gm,x,y; void main() { time_t now; struct tm *timeinfo; initgraph(&gd,&gm,"..\\BGI\\"); x=getmaxx()/2-80; y=getmaxy()/2-20; while(!kbhit()) { time(&now); timeinfo=localtime(&now); printf("%2d : %2d : %2d",timeinfo->tm_hour,timeinfo->tm_min,timeinfo->tm_sec); delay(1000); cleardevice(); } getch(); }
Dynamic Memory Allocation in C - Explanation With Examples
In static memory allocation, we know how much memory (bytes) is going to be used before execution of the program. Dynamic memory allocation is essential where the amount of memory the needed by the program depends on the input of the user or any other input obtained during execution time. That is why it is called dynamic memory allocation.
Consider an example of students progress report (for the sake of simplicity). The number of students are different in different classes. There fore, we have to read the number of students from the user (data entry operator). For each student, we need an integer for register number, a few integers to store scores in subjects, a few characters to store address and so on. In this case, the total amount of memory needed depends on the number of students in a class. There fore, the amount of memory that should be allocated for the program should be decided based on the input. In such cases we use dynamic memory allocation.
C programming language allows dynamic memory allocation. Most of modern programming languages use dynamic memory allocation. Java is an example. Unlike C, there is not a concept of pointers in Java because all variables are actually pointers.
The above shown prototype of malloc function tells that it always return a pointer to 'void' data type. That is, the pointer can be type-casted to int pointer, char pointer or to any other data type. malloc functions takes a parameter which is the amount of memory (number of bytes) to be allocated. It is recommended to specify the size using sizeof operator. We will see a few examples of dynamic memory allocation using malloc function.
The first parameter pointer is the pointer to the memory block allocated earlier. The next argument size is the new (updated) size. It size is greater than the older size, additional memory will be allocated to get size number of bytes allocated in total. If it is less than older size, a part of memory will be deallocated which is equal to the difference between initial size and new size. If first parameter is NULL, a fresh block with specified size will be allocated.
In the above example a structure named student is used. Each structure variable has a roll number and name. Memory to store for 5 student structure variables are allocated using calloc. The pointer arithmetic for pointers to structures is also demonstrated in above program.
Consider an example of students progress report (for the sake of simplicity). The number of students are different in different classes. There fore, we have to read the number of students from the user (data entry operator). For each student, we need an integer for register number, a few integers to store scores in subjects, a few characters to store address and so on. In this case, the total amount of memory needed depends on the number of students in a class. There fore, the amount of memory that should be allocated for the program should be decided based on the input. In such cases we use dynamic memory allocation.
C programming language allows dynamic memory allocation. Most of modern programming languages use dynamic memory allocation. Java is an example. Unlike C, there is not a concept of pointers in Java because all variables are actually pointers.
Functions for Dynamic Memory Allocation in C
The functions used for dynamic memory allocation or deallocation are malloc, realloc, calloc and free. These functions are defined in the header file stdlib.h- malloc
- This function is used to allocated specified number of bytes.
- realloc
- Used to increase or decrease size of a block of memory. Allocation or Deallocation of bytes is performed if necessary.
- calloc
- Allocates specified number of bytes and also intialises all bytes to zero. This function allows to specify how many blocks of specified size should be allocated.
- free
- Deallocates and releases the specified block of memory.
Malloc function
First, we will see the syntax of malloc function. Then it will be easier to explain. Syntax is as follows:void * malloc(int sizeInBytes);
The above shown prototype of malloc function tells that it always return a pointer to 'void' data type. That is, the pointer can be type-casted to int pointer, char pointer or to any other data type. malloc functions takes a parameter which is the amount of memory (number of bytes) to be allocated. It is recommended to specify the size using sizeof operator. We will see a few examples of dynamic memory allocation using malloc function.
int *p=malloc(10*sizeof(char));
- Allocates memory to accommodate 10 characters.
int *p=malloc(20*sizeof(int));
- Allocates memory to accommodate 20 integers.
int *p=malloc(sizeof(float));
- Allocates memory to accommodate a float.
int *p=malloc(10*sizeof(struct student));
- Allocates memory to accommodate 10 instances of structure named student. This is how to store derived datatypes (user defined data types) like structures dynamically in c.
Realloc Function
Realloc function is used either to shrink or to expand an already allocated memory. It is called after allocation of memory using malloc or calloc function. Suppose we initially allocated memory for 10000 characters dynamically. Later, during the of execution of program, we find that only 5000 characters need to be stored. Therefore, we are not going to use the rest. To avoid memory wastage, we may deallocate the remaining 5000 character spaces trailing being the used 5000. The following code will shrink the initially allocated 10000 chars to 5000 chars by deallocating the remaining.void * realloc(void *pointer,size_t size)
The first parameter pointer is the pointer to the memory block allocated earlier. The next argument size is the new (updated) size. It size is greater than the older size, additional memory will be allocated to get size number of bytes allocated in total. If it is less than older size, a part of memory will be deallocated which is equal to the difference between initial size and new size. If first parameter is NULL, a fresh block with specified size will be allocated.
char *ptr; //Initial allocation ptr = (char *) malloc(150); //Reallocating memory to 50 char ptr = (char *) realloc(ptr, 50);
Calloc Function
Calloc function is not much significantly different from malloc. The differences between malloc and calloc are:
- Calloc lets you to specify the number of variables (of same data type) and space needed by each data type by taking two parameters.
- When allocated using malloc, the memory block may contain junk data (garbage values) but calloc initializes every allocated byte to zero.
The following code fragment shows example use of calloc with structure:
#include<stdlib.h> struct student { int rollno; char name[30]; }; int main() { struct student *list,*temp; list=(struct student *)calloc(5,sizeof(struct student)); for(temp=list;temp-list<5;temp++) { printf("Enter roll number and name of student\n"); scanf("%d%s",&temp->rollno,&temp->name); } printf("\nThe students are:\n"); for(temp=list;temp-list<5;temp++) { printf("Roll number: %d Name: %s\n",temp->rollno,temp->name); }
free(list);
return 0; }
Output
Enter roll number and name of student 1 matthew Enter roll number and name of student 2 mathews Enter roll number and name of student 3 shareef Enter roll number and name of student 4 muneer Enter roll number and name of student 5
nihal The students are: Roll number: 1 Name: matthew Roll number: 2 Name: mathews Roll number: 3 Name: shareef Roll number: 4 Name: muneer Roll number: 5 Name: nihal
In the above example a structure named student is used. Each structure variable has a roll number and name. Memory to store for 5 student structure variables are allocated using calloc. The pointer arithmetic for pointers to structures is also demonstrated in above program.
Free Function
The free function is used to free (deallocate) an already allocated block of memory. When your program no longer needs the dynamically allocated block of memory, the free function should be called to return the memory occupied to the free store. In the above example program, the following line of code deallocated the allocated block of memory.
free(list);
The free function takes the pointer to the block of memory which is allocated dynamically as parameter and frees or deallocates the block so that it can be used later.
Making of Tetris Game in C
Block types in tetris |
To make the tetris game, we first make a two dimensional array. An element in this integer array is a single block (one of the four blocks in each block type) in the game. We set all the elements to zero initially to show that the matrix is empty. We may call each element a cell. So to represent a Z block, we need four cells. In the matrix, to represent a falling block (eg: a Z block) we set corresponding elements' values to 1. We move these 1's in the 2d integer array downwards to simulate falling. Then when it reaches bottom, these 1's are changed to 2's. This is to denote that these cell cannot be moved further. Again, we start another random block from the top (first row).
Bresenham's Line Drawing Algorithm Implementation in C - Generalized Algorithm
Bresenham's line drawing algorithm is an efficient algorithm to draw any line. Unlike DDA algorithm, it uses only integer incremental calculations during the process. This saves much of the CPU time. I am posting a generalized Bresenham's line drawing algorithm (an algorithm that can draw any line in any quadrant with any slope). The main function in this program draws lines of almost all slopes by drawing radial lines for a circle. The entered endpoints of the line are marked in red color. The rest of the line is drawn in the default stroke color in BGI graphics. You can change it by calling setcolor() function.
Program is given below:
Output:
Program is given below:
C Program to Animate a Man Drawing Water From Well
This is a c program to animate a man drawing water from well. This is computer graphics lab experiment. The program uses graphics library in c (graphics.h). The output is as follows:
The program is as follows:
The program is as follows:
C Program for Polygon Clipping by Another Polygon - Computer Graphics Lab Program
Polygon clipping is one of the classic problem in computer graphics lab. Generally, polygons or whatever objects, are clipped by a rectangular clipping windows. But, this one is a little more challenging graphics lab experiment in which we have to clip polygon with another polygon. That is the clipping windows is actually another polygon. The following c program implements polygon clipping with another polygon. The program clips any polygon with the clipping polygon, given both should be convex polygons.
Bresenhams Circle Drawing Algorithm Implementation in C
Bresenham's circle drawing algorithm is one of the basic algorithms in computer graphics. Bresenham's circle drawing algorithm helps to draw circles with minimal calculations. Here is a simple c program that implements Bresenham's circle drawing algorithm.
The program is as follows:
The program is as follows:
C Program to Implement Midpoint Circle Drawing Algorithm
Midpoint circle drawing algorithm is another basic algorithms in computer graphics. Midpoint circle drawing algorithm is used to draw circles with minimal calculations. Here is a simple c program that implements Midpoint circle drawing algorithm.
How to Get Time and Date in C - C Program to Read and Display Time and Date
In this post, we will discuss how to read system time (current time) and date in c. To get system time and date, we use the time.h header file. It contains functions related to time and date. The function time() reads the current time and stores in the variable given as parameter. For example, if we call time(now), then the variable now is assigned the current date and time value. This parameter should be of type time_t. A sample code is:
time_t now; time ( &now );
Note that we should pass the reference to a variable of type time_t. But, the value stored by the function time() contains all information including date and time. So, the value appears to be an unintelligible random number. There fore, to extract hours, minutes, seconds, year, month, day of month etc from this value, we should convert into an object of structure struct tm. The function localtime() converts the value for us. This conversion to date and time can be done as follows:
C Program to Display Analog Clock Showing Correct Time - Computer Graphics Program
This is a c program which reads the current time from system and shows an analog clock that shows correct time. The clock hand ticks and the three hands (hour hand, minute hand, second hand) are used to to show correct time. This real-time analog clock c program uses graphics.h library to display the clock and time.h library to get current time. The program output is as follows:
C Program to Draw Rainbow - Computer Graphics Pogram
This is a simple computer graphics lab program in c language to display a rainbow. Since BGI (Borland Graphics Interface) supports only 16 colors, the rainbow cannot be shown in correct colors (VIBGYOR). This is because, colors like violet, indigo and orange are not available in BGI. There fore, we just use some available color instead. The following is the program.
Rotation of Wheel - C Program for Computer Graphics Lab
In computer graphics experiments, we need to rotate objects like wheels while doing animation. This is a simple c program that shows rotation of a wheel. A circle is drawn and four radial lines are drawn at 90 degree separation. These lines are drawn from center to a point on circle which depends on the value of theta, a variable. As the value of theta changes, the end points of the radial lines changes. Therefore, increasing the value of theta in a loop give counter clockwise rotaion and decreasing gives clockwise rotation.
The program is as follows:
The program is as follows:
C Program to Draw Malayalam Letter 'Dha' (เดง) Using Bezier Curves
This is a c program to draw Malayalam letter เดง using Bezier Curves. The program draws the letter
เดง using four different Bezier curves. For understandability, individual curves are shown in different colors. The control points for each curve are set in the program and a function bezier() is called with different set of control points twice.
เดง using Bezier Curves |
C Program to Draw Malayalam Letter 'Tha' (เดค) Using Bezier Curves
This is a c program to draw malayalam letter เดค using Bezier Curves. The program draws the letter
เดค using four different Bezier curves. For understandability, individual curves are shown in different colors. The control points for each curve are set in the program and a function bezier() is called wth different set of control points four times.
เดค using bezier curves |
C Program to Draw Bezier Curve - Graphics Lab Program
This is a c program to draw a bezier curve. You can draw a bezier curve by giving control points. The control points' co-ordinates are stored in arrays x[] and y[]. You can draw different curves by combining multiple bezier curves. We will see such examples in some other posts. Here, this program has a function named bezier which draws the curve using an array of control points declared globally.
C Program to Draw Fern Leaf using Fractals - Computer Graphics Experiment
Fern is a plant with leaves that follow a pattern. A whole fern plant can be drawn using simply lines. Drawing fern is a simple example for fractals in computer graphics. The following program draws a fern plant using the idea of fractals. This is a computer graphics lab experiment.
Rotation and Revolution of Two Wheels following a 'D' Shaped Path - Computer Graphics Experiment
This is a computer graphics lab experiment. The question was to animate both rotation and revolution of two wheels in opposite direction. Both the wheels move in a path in a of shape 'D'. If one moves in clockwise direction, the other moves in counter clockwise direction. The output of the program is as follows:
The program is as follows:
The program is as follows:
Keyboard Controlled Car Animation in C - Computer Graphics Lab Program
This is a computer graphics lab program. This is an animation program in which a car can be moved using the arrow keys on keyboard. The car should move forward when right arrow key is pressed and backward when left arrow key is pressed. The car accelerates as the right arrow key is pressed. When it is released the car decelerates. The program uses the graphics library graphics.h. This program works well in the turbo c compiler with Borland graphics interface (BGI). The output of the program is as follows:
The program is as follows:
The program is as follows:
Man Rowing Boat Animation - Computer Graphics Lab Animation Experiment
This is a computer graphics lab program. This is an animation program. The experiment is to animate a scene of a man rowing boat in a river on a rainy day. The man wears a hat also. The
program uses the graphics library graphics.h. This program works well in the turbo c compiler with Borland graphics interface (BGI). The output of the program is as follows:
The program is as follows:
The program is as follows:
C Program for Animated Solution of Tower of Hanoi Puzzle Problem
This is a c program to solve towers of Hanoi puzzle problem with graphical demonstration. This c program demonstrates solution for tower of Hanoi puzzle with given number of disks. Tower of Hanoi is a mathematical game or puzzle. It is also called tower of Brahma or Lucas' tower. There are three towers (or rods) and a number of disks of different diameters. The program lets you enter the number of disks. As the number of disks increase, the difficulty of puzzle also increase. The disks have hole at center so that it can slide on to the rods. Initially all disks are stacked on the first tower, say tower A, such that no disk is placed over a smaller disk. To win the puzzle you have to move all those disks from tower A (first tower) to tower C (third tower). But there are a few rules to solve the puzzle. They are:
C Program to Solve Tower of Hanoi Puzzle
This is a c program to solve towers of Hanoi puzzle problem. This simple c program give solution for tower of Hanoi problem with any
number of disks. Tower of Hanoi is a mathematical game or puzzle. It is also called tower of Brahma or Lucas' tower. There are three towers
(or rods) and a number of disks of different diameters. Initially, The disks have hole at center so that it can slide on to the rods.
initially all disks are stacked on the first tower, say tower A, such that no disk is placed over a smaller disk. The goal or
objective is to move all these disks from tower A (first tower) to tower C (third tower). But you should obey the following rules.
The rules of towers of Hanoi puzzle are:
C Program for Reflection Transformation for Computer Graphics Lab
Reflection is one of the 2d transformation operations in computer graphics. Here i present a c program to implement reflection. The reflection transformation can be applied on any polygon given by user using this c program. Reflection of points is done which results is reflection of lines or polygons drawn from the points. The reflection transformation is sometimes called flipping or mirroring. Reflection of a polygon about horizontal axis is called vertical flip and reflection about vertical axis is called vertical flip. Whatever we call, flipping or reflecting it is producing mirror image about an axis. The following c program performs reflection transformation on given polygon about both axes.
C Program for Shear Transformation - Shear Transformation in 2D Computer Graphics
Shear transformation or shearing is one of the 2d transformations in computer graphics. Here i present a c program for shear transformation of polygons. The shear transformation works as follows:
For shearing along X axis, shearfactor* (y coordinate) is added with x co-ordinates of all points. That is:
Similarly, to shear along Y axis, we add shearfactor* (x coordinate) to y co-ordinates of all points.
For shearing along X axis, shearfactor* (y coordinate) is added with x co-ordinates of all points. That is:
newx=oldx+shearfactor*oldy
Similarly, to shear along Y axis, we add shearfactor* (x coordinate) to y co-ordinates of all points.
newy=oldy+shearfactor*oldx
C Program for Scaling 2D transformation - Scaling Polygons in Computer Graphics
This is a c program for scaling transformation in computer graphics. Scaling is one of the important 2d transformations in computer graphics. The program will tell you how to scale lines or polygons. This CG lab program in c language using the graphics library reads the number of sides of polygon, co-ordinates of its vertices and the scale factors in horizontal and vertical directions. It displays the original polygon and scaled polygon in different colors in same screen. More Computer graphics lab problems are available under related posts heading.
C Program for Rotation of Polygon - 2D Transformation in Computer Graphics
This is a c program for rotation transformation in computer graphics. Rotation is one of the important 2d transformations in computer graphics. The program will tell you how to rotate points or polygon around a point (the pivot point). This CG lab program in c language using the graphics library reads the number of sides of polygon, co-ordinates of its vertices, the pivot point for rotation, and angle of rotation. It displays the original polygon and rotated polygon in different colors in same screen. More Computer graphics lab problems are available under related posts heading.
C Program for Translation 2D Transformation in Computer Graphics
This is a c program for translation transformation in computer graphics. Translation (or shifting) is a very basic 2d transformation operation in computer graphics. Translation or shifting is done by adding the distance to shifted to the co-ordinates. For example, if we want to shift a polygon 50 units (pixels) horizontally, we just have to add 50 to x co-ordinates of all vertices of the polygon. Similarly, if it is translate only vertically by 100 unit, add 100 to y co-ordinates of all vertices. This CG lab program in c language using the graphics library reads the number of sides of polygon, co-ordinates of its vertices and the translation distance along both axes. It displays the original polygon and translated polygon in different colors in same screen. This is only a very simple and basic Computer graphics lab problem.
2D Transformations C Program - Computer Graphics Lab 2D Transformation
The main two dimensional transformation operations in computer graphics are: translation or shifting, scaling, rotation, reflection (or flipping) and shearing. Here in this c program, we can do all these transformations on any polygon. Rotation can be done about any pivot point. Reflection includes reflection about horizontal axis (flip horizontal) and reflection about vertical axis (flip vertical). Similarly, shear transformation is also done about horizontal axis (x-axis) and vertical axis (y-axis). The input to the program are number of sides of polygon and its vertices.
Two Stroke Engine Piston Movement Animation C Program - CG Lab Program
This program simulates the motion of the components of a two stroke engine. It shows the movement of piston, connecting rod and crank by animating them in c. The program uses the graphics library (grapics.h) to simulate the piston movement in two stroke engine. This is a computer graphics lab (CG lab) problem. The program is given below. The program uses sin and cos functions to simulate the crank. Also it uses the equation to find the distance between to points.
Output:
Program
#include<stdio.h> #include<graphics.h> #include<math.h> #include<stdlib.h> void main() { int gd=DETECT,gm; int tt,midx,midy,radius=40,rodlen=150,deg=0,jointx,jointy,px; float radian,sqrodlen,t; initgraph(&gd,&gm,"C:\\TURBOC3\\BGI\\"); midx=getmaxx()/2; midy=getmaxy()/2; sqrodlen=rodlen*rodlen; while(!kbhit()) { circle(midx,midy,radius); radian=(float)deg*3.14f/180; jointx=midx+radius*sin(radian); jointy=midy+radius*cos(radian); line(midx,midy,jointx,jointy); t=pow(jointy-midy,2); tt=(int)sqrt(sqrodlen-t); px=jointx-tt; line(jointx,jointy,px,midy); rectangle(px-30,midy-10,px+20,midy+10); rectangle(px-45,midy-35,px-30,midy+35); rectangle(midx-240,midy-35,midx-90,midy+35); deg+=10; delay(80); cleardevice(); } }
Program to Display Multiplication Table of All Numbers From 1 to 10
This is a C program to display multiplication tables of all number from 1 to 10. To see c program to display multiplication table of given number only, see this program:
Program to Display Multiplication Table of Given Number
Program to Display Multiplication Table of Given Number
#include<stdio.h> int main() { int i,j; for(i=1;i<=10;i++){ for(j=1;j<=10;j++) printf("%1d*%1d=%2d ",i,j,i*j); printf("\n"); } return 0; }
Output:
1*1= 1 1*2= 2 1*3= 3 1*4= 4 1*5= 5 1*6= 6 1*7= 7 1*8= 8 1*9= 9 1*10=10 2*1= 2 2*2= 4 2*3= 6 2*4= 8 2*5=10 2*6=12 2*7=14 2*8=16 2*9=18 2*10=20 3*1= 3 3*2= 6 3*3= 9 3*4=12 3*5=15 3*6=18 3*7=21 3*8=24 3*9=27 3*10=30 4*1= 4 4*2= 8 4*3=12 4*4=16 4*5=20 4*6=24 4*7=28 4*8=32 4*9=36 4*10=40 5*1= 5 5*2=10 5*3=15 5*4=20 5*5=25 5*6=30 5*7=35 5*8=40 5*9=45 5*10=50 6*1= 6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36 6*7=42 6*8=48 6*9=54 6*10=60 7*1= 7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49 7*8=56 7*9=63 7*10=70 8*1= 8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64 8*9=72 8*10=80 9*1= 9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81 9*10=90 10*1=10 10*2=20 10*3=30 10*4=40 10*5=50 10*6=60 10*7=70 10*8=80 10*9=90 10*10=100
Program to Display Multiplication Table of Given Number
This is a c program to display multiplication table of given number. For program to display multiplication table of all numbers from 1 to 10, see this post:
Program to display multiplication table of all numbers from 1 to 10
1 * 5 = 5
2 * 5 = 10
3 * 5 = 15
4 * 5 = 20
5 * 5 = 25
6 * 5 = 30
7 * 5 = 35
8 * 5 = 40
9 * 5 = 45
10 * 5 = 50
#include <stdio .h> void main() { int n, i; printf("Enter the number:"); scanf("%d",&n); for(i=1; i<=10; ++i) printf("%d * %d = %d \n", i, n, n*i); }
Output:
Enter the number:51 * 5 = 5
2 * 5 = 10
3 * 5 = 15
4 * 5 = 20
5 * 5 = 25
6 * 5 = 30
7 * 5 = 35
8 * 5 = 40
9 * 5 = 45
10 * 5 = 50
C Program for Matrix Multiplication
This is a c program for Matrix Multiplication. To understand how it works, you should first know how matrix multiplication is done mathematically.
#include <stdio.h> void main() { int m1[10][10],i,j,k,m2[10][10],prod[10][10],r1,c1,r2,c2; printf("Enter number of rows and columns of first matrix:\n"); scanf("%d%d",&r1,&c1); printf("Enter number of rows and columns of second matrix:\n"); scanf("%d%d",&r2,&c2); if(r2==c1) { printf("Enter elements of First matrix (row wise):\n"); for(i=0;i<r1;i++) for(j=0;j<c1;j++) scanf("%d",&m1[i][j]); printf("Matrix1 is :\n"); for(i=0;i<r1;i++) { for(j=0;j<c1;j++) printf("%d ",m1[i][j]); printf("\n"); } printf("Enter elements of Second matrix (row wise):\n"); for(i=0;i<r2;i++) for(j=0;j<c2;j++) scanf("%d",&m2[i][j]); printf("Matrix2 is:\n"); for(i=0;i<r2;i++) { for(j=0;j<c2;j++) printf("%d ",m2[i][j]); printf("\n"); } printf("Product of the Matrices (M1 x M2):\n"); for(i=0;i<r1;i++) { for(j=0;j<c2;j++) { prod[i][j]=0; for(k=0;k<r1;k++) prod[i][j]+=m1[i][k]*m2[k][j]; printf("%d\ ",prod[i][j]); } printf("\n"); } } else { printf("Matrices can't be multiplied.\n"); printf("No. of columns of first matrix and no of rows of second are different."); } }
Program to Find Power of a Number
This is a c program to calculate power of a given number. The inputs are the number and its exponent (power). For example, if you give m and n, the result is m^n.
#include<stdio.h> int main() { int m, n, i,p=1; printf("Enter the number and its power (exponent)\n"); scanf("%d%d",&m,&n); for( i = 0 ; i < n ; i++ ) p*=m; printf("%d raised to %d is: %d",m,n,p); }
Output:
Enter the number and its power (exponent) 2 3 2 raised to 3 is: 8Program to Find Transpose of a Matrix
This is a c program to find the transpose of a matrix. Finding transpose of a matrix is simple like displaying the matrix. You just have to interchange i and j at the matrix indices.
#include<stdio.h> int main() { int m, n, i, j; int mat[10][10], trans[10][10]; printf("Enter the number of rows and columns of matrix\n"); scanf("%d%d",&m,&n); printf("\nEnter the elements of matrix \n"); for( i = 0 ; i < m ; i++ ) { for( j = 0 ; j < n ; j++ ) scanf("%d", &mat[i][j] ); } for( i = 0 ; i<m ; i++ ) { for( j = 0 ; j < n ; j++ ) trans[j][i] = mat[i][j]; } printf("Transpose is:\n "); for( i = 0 ; i < n ; i++ ) { printf("\n"); for( j = 0 ; j < m ; j++ ) printf("%d\t ", trans[i][j] ); } }
C Program to Find Inverse of a Matrix
This is a c program to find the inverse of matrix. If M is the matrix and M-1 is its inverse, M x M-1 gives I (identity matrix). Inverse of a matrix M is:
adjoint(M) / det(M)
If determinant is zero, the matrix is not invertible. Adjoint of matrix M is transpose of cofactor matrix of M.
The c program to find inverse of matrix is as follows:
adjoint(M) / det(M)
If determinant is zero, the matrix is not invertible. Adjoint of matrix M is transpose of cofactor matrix of M.
The c program to find inverse of matrix is as follows:
#include<stdio.h> #include<math.h> float detrminant(float[][], float); void cofactors(float[][], float); void trans(float[][], float[][], float); main() { float a[25][25], n, d; int i, j; printf("Enter the order of the matrix:\n"); scanf("%f", &n); printf("Enter the elemnts into the matrix:\n"); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) scanf("%f", &a[i][j]); } d = detrminant(a, n); printf("\nTHE DETERMINANT IS=%2f", d); if (d == 0) printf("\nMATRIX IS NOT INVERSIBLE\n"); else cofactors(a, n); } float detrminant(float a[25][25], float k) { float s = 1, det = 0, b[25][25]; int i, j, m, n, c; if (k == 1) return (a[0][0]); else { det = 0; for (c = 0; c < k; c++) { m = 0; n = 0; for (i = 0; i < k; i++) { for (j = 0; j < k; j++) { b[i][j] = 0; if (i != 0 && j != c) { b[m][n] = a[i][j]; if (n < (k - 2)) n++; else { n = 0; m++; } } } } det = det + s * (a[0][c] * detrminant(b, k - 1)); s = -1 * s; } } return (det); } void cofactors(float num[25][25], float f) { float b[25][25], fac[25][25]; int p, q, m, n, i, j; for (q = 0; q < f; q++) { for (p = 0; p < f; p++) { m = 0; n = 0; for (i = 0; i < f; i++) { for (j = 0; j < f; j++) { b[i][j] = 0; if (i != q && j != p) { b[m][n] = num[i][j]; if (n < (f - 2)) n++; else { n = 0; m++; } } } } fac[q][p] = pow(-1, q + p) * detrminant(b, f - 1); } } trans(num, fac, f); } void trans(float num[25][25], float fac[25][25], float r) { int i, j; float b[25][25], inv[25][25], d; for (i = 0; i < r; i++) { for (j = 0; j < r; j++) b[i][j] = fac[j][i]; } d = detrminant(num, r); inv[i][j] = 0; for (i = 0; i < r; i++) { for (j = 0; j < r; j++) inv[i][j] = b[i][j] / d; } printf("\nTHE INVERSE OF THE MATRIX:\n"); for (i = 0; i < r; i++) { for (j = 0; j < r; j++) printf("\ %2f", inv[i][j]); printf("\n"); } }
C Program to Check Perfect Number
This is a c program to check whether a given number is a perfect number or not. But, what is a perfect number? If the sum of all proper divisors of a number is equal to the number itself, it is a perfect number. Proper divisors of a number means all its divisors except the number itself. A perfect number is a positive integer which is equal to sum of its proper divisors. An example is 6. 6 = 1 + 2 + 3. 28 is also an example for perfect number (1+2+4+7+14=28).
The following program checks a given number and tells whether it is a perfect number or not.#include<stdio.h> int main() { int n,i=1,sum=0; printf("Enter a number:"); scanf("%d",&n); while(i<n) { if(n%i==0) sum=sum+i; i++; } if(sum==n) printf("%d is a perfect number",i); else printf("%d is not a perfect number",i); return 0; }
How to Get Random Number in C
C Language has functions to generate random numbers. It is not actually random number. Computer cannot generate real random number. Rather they produce pseudo random number. We will see later in another post how pseudo random number generator work. In this post, we will see how to use pseudo random number generation functions in C.
The function rand() is used to get random number. The random numbers generated by the function depend on a an initial 'seed'. We may use time as seed here. We will give current time as initial seed by calling srand() function. Calling time(NULL) will return current time. It is in time.h library. Thus srand(time(NULL)) will set initial seed as current time. As we call rand(), we will get different random numbers. The random numbers start from zero (inclusive). To set a maximum value for random number, we may use the % operator.
rand()%10 returns random number from 0 to 9 (inclusive).
rand()%50 returns random number from 0 to 49 (inclusive).
rand()%51 returns random number from 0 to 50 (inclusive).
rand()%101 returns random number from 0 to 100 (inclusive).
Therefore we may say,
rand()%max returns random number from 0 to max-1.
To get random number from 50 to 99 (inclusive):
use 50+rand()%(100-50)
In general, to get a random number from min to max (including min and max) use the following code:
The function rand() is used to get random number. The random numbers generated by the function depend on a an initial 'seed'. We may use time as seed here. We will give current time as initial seed by calling srand() function. Calling time(NULL) will return current time. It is in time.h library. Thus srand(time(NULL)) will set initial seed as current time. As we call rand(), we will get different random numbers. The random numbers start from zero (inclusive). To set a maximum value for random number, we may use the % operator.
rand()%10 returns random number from 0 to 9 (inclusive).
rand()%50 returns random number from 0 to 49 (inclusive).
rand()%51 returns random number from 0 to 50 (inclusive).
rand()%101 returns random number from 0 to 100 (inclusive).
Therefore we may say,
rand()%max returns random number from 0 to max-1.
To get random number from 50 to 99 (inclusive):
use 50+rand()%(100-50)
In general, to get a random number from min to max (including min and max) use the following code:
min+rand()%(max+1-min)
#include<stdio.h> #include<stdlib.h> #include<time.h> main() { int min,max,rnum,i; printf("Enter the minimum and maximum value of random number"); scanf("%d%d",&min,&max); printf("Five random numbers from %d to %d are :\n",min,max); srand(time(NULL)); for(i=0;i<5;i++) printf("%d, ",min+rand()%(max+1-min)); getch(); }
Program to List All Prime Numbers Less Than Given Number
This is a c program to list all prime numbers less than a given number. Within a loop it checks each number less than the given number, whether it is prime or not.
Program to Check Whether a Number is Prime or Not
This is a c program to check whether a given number is prime or not. To check whether a number 'n' is prime or not, it is enough to check whether it is divisible by any number less than or equal to square root of n. If there is any number i less than or equal to square root of n which divides n completely, then it is not prime. Otherwise it is prime.
Program to Swap Numbers with Bitwise (EXOR) Operators
Here is a c program to swap two numbers. This method of swapping does not use a third (temporary) variable. Instead, swapping is done by bitwise operation. We perform bitwise EXOR operations on the two numbers. The program is as follows:
#include<stdio.h>
void main()
{ int x,y; x=200; y=140; printf("\nBefore swapping x=%d,y=%d",x,y); x=x^y; y=x^y; x=x^y; printf("\nAfter swapping x=%d y=%d",x,y); }
Array Rearrangement Without Another Array - Zoho Programming Round Question
Question:
You are given two integer arrays. The first one is a set of integers which you should rearrange and produce an output array based on the second array. The second array, we call it Order array, is an array which directs the rearrangement by specifying the required position of each element in given array. You should rearrange the elements just as specified by the order array without using any additional arrays. You should write a c program to rearrange the number array but without using another array. An example is as follows:number array: 46 80 10 8 7 2 11 16 17 43
order array : 5 2 0 6 8 7 1 3 4 9
output : 2 10 46 11 17 16 80 8 7 43
Problem Explanation:
order[0]=5 means the current element at index 5 in the given number array should be at index 0 in the desired array. Similarly order[1]=2 means the current element at index 2 in the given number array (10) should come at index 1 in the desired array.Thus, the question is to write a c program to rearrange the given array without using another array to produce the desired array as specified by the order array.
This was one of the questions asked in a programming test conducted as a part of recruitment process of Zoho corporation, an IT firm. This is one of the tough c programming questions asked in second hands on coding round.
Before answering the question, you must know that it is possible to produce the desired output array without actually performing the rearrangement. It is not so difficult.The following code fragment can do it.
for(i=0;i<10;i++)
printf("%d ",nums[order[i]]);
As emphasized in the question, the array should be rearranged, but your are not allowed to use any additional arrays.
Answer:
Actually, this can't be done without additional allocation of memory. But, to answer this question, we should avoid explicit use of additional arrays. So, we can make use of recursion. In fact, for each call of a recursive function, memory is allocated in stack for its local variables. We make use of recursion to exploit the stack. I would first write the program, then explain it.#include<stdio.h> int nums[]={ 46,80,10,8,7,2,11,16,17,43}; int order[]={5,2,0,6,8,7,1,3,4,9}; int i; void rec(int index) { int num; num=nums[order[index]]; if(index<9) rec(index+1); nums[index]=num; } void main() { printf("rearranging\n"); i=0; rec(i); printf("rearranged:\n"); for(i=0;i<10;i++) printf("%d ",nums[i]); }
The parameter index in each recursion stores the index (position) and local variable num stores the desired number at that position. Thus value of parameter 'index' varies from 0 to 9 (here) and corresponding number at the index is also held in variable num. Thus, after the last call of recursive function, the whole array (index and the number at that index) get stored in stack. Only after this, the num is placed at its index.
C Program to Convert Between Hexadecimal, Octal, Binary and Decimal Numbers
This program deals with four number systems. They are:
The following program lets you convert between the four number systems; decimal, binary, octal and hexadecimal number systems.
- Decimal (base 10)
- Binary (base 2)
- Octal (base 8)
- Hexadecimal (base 16)
Here i post a program for following operations:
- Decimal to binary conversion
- Decimal to Octal conversion
- Decimal to Hexadecimal conversion
- Binary to Decimal conversion
- Binary to Octal conversion
- Binary to Hexadecimal conversion
- Octal to Decimal conversion
- Octal to Binary conversion
- Octal to Hexadecimal conversion
- Hexadecimal to Decimal conversion
- Hexadecimal to Binary conversion
- Hexadecimal to Octal conversion
Octal to Decimal Converter Program - Program to Convert from Octal to Decimal
This is a c program to convert any Octal number to decimal number system. Octal number system represents numbers using digits 0 to 7. The decimal number system is the commonly used number system which uses digits 0 to 9. The following program performs conversion from octal to decimal.
Program to Convert Hexadecimal to Decimal - Hexadecimal Conversion Program
Hexadecimal number system is base 16 number system in which the digits used are 0 to 9 and A to F. Here is a c program to convert hexadecimal number to decimal number system.
Program to Convert Binary to Decimal - Binary to Decimal Converter Program
This is a c program to convert a binary number to decimal number. The input (binary number) should contain only zeros and ones. Binary number system represents numbers using only two digits; 0 and 1. The following is a binary to decimal converter program in C.
Program to Convert Decimal to Binary - Binary Converter Program
This is a C program to convert decimal numbers to Binary numbers. Binary number system is the base 2 number system. The digits used in this number system are 0 and 1 only. The program is as follows:
Program to Convert Decimal to Octal Number - Decimal to Octal converter
This is a program to convert a number in decimal (base 10) number system to octal number system. In octal number system, numbers are represented with base 8. That is, the digits are 0 to 7. The following program converts decimal numbers to octal.
Program to Convert Decimal Number to Hexadecimal Number
This program is to convert a number in decimal number system (base 10) to a hexadecimal number (base 16). I have wrote a function reversestring to reverse a string. You may use strrev function instead if available. The program is as follows:
C Program for Quick Sorting - Quick Sort Program in to Sort Numbers
Quick sort is one of the most efficient sorting algorithms. Here i post a C program to implement Quick sorting. This program is to sort given numbers is ascending order. To sort in descending order using quick sort, only slight changes are needed in program. Changes needed for sorting in descending order are marked in the program as comments.
Output:
Enter size of the array: 5
Enter 5 elements:
3
8
0
1
2
Sorted elements: 0 1 2 3 8
#include<stdio.h> void quicksort(int [10],int,int); int main() { int x[20],size,i; printf("Enter size of the array: "); scanf("%d",&size); printf("Enter %d elements: ",size); for(i=0;i<size;i++) scanf("%d",&x[i]); quicksort(x,0,size-1); printf("Sorted elements: "); for(i=0;i<size;i++) printf(" %d",x[i]); return 0; } void quicksort(int x[10],int first,int last) { int pivot,j,temp,i; if(first<last) { pivot=first; i=first; j=last; while(i<j) { while(x[i]<=x[pivot]&&i<last)//for descending, use >= instead of <= i++; while(x[j]>x[pivot])//for descending, use < instead of >= j--; if(i<j) { temp=x[i]; x[i]=x[j]; x[j]=temp; } } temp=x[pivot]; x[pivot]=x[j]; x[j]=temp; quicksort(x,first,j-1); quicksort(x,j+1,last); } }
Output:
Enter size of the array: 5
Enter 5 elements:
3
8
0
1
2
Sorted elements: 0 1 2 3 8
Algorithm and C Program to Find Candidate Key from Functional Dependencies
First of all, we will see the algorithm to find candidate keys from functional dependencies. The
input is functional dependencies.
Algorithm:
1. Find the attributes that are neither on the left and right side
2. Find attributes that are only on the right side
3. Find attributes that are only on the left side
4. Combine the attributes on step 1 and 3
5. Test if the closures of attributes on step 4 constitutes all the attributes. If yes it is a candidate key.
6. If not, find the relation exteriors, that is the attributes not included in step 4 and step 2.
7. Now test the closures of attributes on step 4 + one attribute in step 6 one at a time. All those combinations are candidate keys if their closures constitute all the attributes.
C Program:
#include<stdio.h> #include<string.h> #include<conio.h> struct fd { int left[8],right[8]; int lcount,rcount; }f[10]; int attrcount,closcount=0,fdcount,closure[10]; char attr[10][25]; int nolnor[8],ronly[8],lonly[8],merg1n3[8],exteriors[8]; void getclosure(); void get_nolnor(); void get_ronly(); void get_lonly(); void get_merg1n3(); int iscomplete(); void getclosure() { int i,j,k,l=0,issubset,found; do { for(i=0;i<=fdcount;i++)//Checking each functional dependancy { issubset=1; for(j=0;j<f[i].lcount;j++)//select each attr in leftside { found=0; for(k=0;k<closcount;k++) //checking with each element of closure { if(closure[k]==f[i].left[j]) { found=1; break; } } if(found==0) { issubset=0; break; } } if(issubset==1) { for(k=0;k<f[i].rcount;k++) { found=0; for(j=0;j<closcount;j++) { if(closure[j]==f[i].right[k]) found=1; } if(found==0) { closure[closcount]=f[i].right [k]; closcount++; } } } } l++; }while(l<attrcount); } void get_nolnor() { int i,found,j,k,l=0; for(i=0;i<attrcount;i++)//take an attribute { found=0; for(j=0;j<=fdcount;j++) //take an fd { for(k=0;k<f[j].lcount;k++) //check in left { if(i==f[j].left[k]) { found=1; break; } } if(found==1) //stop if found. break; for(k=0;k<f[j].rcount;k++) //check in right { if(i==f[j].right[k]) { found=1; break; } } if(found==1) //stop if found. break; } if(found==0) { nolnor[l]=i; l++; } } nolnor[l]=222; } void get_ronly() { int rpresent,lpresent,i,j,k,l=0; for(i=0;i<attrcount;i++)//take an atrribute { rpresent=0; for(j=0;j<=fdcount;j++)//take an fd { for(k=0;k<f[j].rcount;k++) { if(i==f[j].right[k]) { rpresent=1; break; } } if(rpresent==1) break; } lpresent=0; if(rpresent==1) { for(j=0;j<=fdcount;j++)//take an fd { for(k=0;k<f[j].lcount;k++) { if(i==f[j].left[k]) { lpresent=1; break; } } if(lpresent==1) break; } } if(lpresent==0&&rpresent==1) ronly[l++]=i; } ronly[l]=222; } void get_lonly() { int rpresent,lpresent,i,j,k,l=0; for(i=0;i<attrcount;i++)//take an atrribute { lpresent=0; for(j=0;j<=fdcount;j++)//take an fd { for(k=0;k<f[j].lcount;k++) //looking in leftside { if(i==f[j].left[k]) { lpresent=1; break; } } if(lpresent==1) break; } rpresent=0; if(lpresent==1) { for(j=0;j<=fdcount;j++)//take an fd { for(k=0;k<f[j].rcount;k++)//checking in right side { if(i==f[j].right[k]) { rpresent=1; break; } } if (rpresent==1) break; } } if(lpresent==1&&rpresent==0) lonly[l++]=i; } lonly[l]=222; } void get_merg1n3() { /* combine lonly and nolnor */ int i,j; for(i=0,j=0;lonly[j]!=222;i++,j++) merg1n3[i]=lonly[j]; for(j=0;nolnor[j]!=222;i++,j++) merg1n3[i]=nolnor[j]; merg1n3[i]=222; } int compare(char temp[25]) { int i; for(i=0;i<attrcount;i++) { if(strcmp(temp,attr[i])==0) return i; } return 0; } int iscomplete() { if(closcount!=attrcount) return 0; else return 1; } void main() { int i,j,k,attcode,found; char schema[100],temp[45],temp1[50]; for(i=0;i<10;i++) { f[i].lcount=0; f[i].rcount=0; } printf("\nEnter the schema\n"); scanf("%s",schema); attrcount=0; for(i=0;schema[i]!='(';i++); do { j=0; i++; while(schema[i]! =','&&schema[i]!=')') { temp [j]=schema[i]; j++; i++; } temp[j]='\0'; strcpy(attr [attrcount],temp); attrcount++; }while(schema[i]==','); fdcount=-1; printf("\nEnter the functional dependancies\nEnter 0 to stop\n"); for(i=0;i<10;i++) { scanf("%s",temp1); if(strcmp(temp1,"0")==0) break; fdcount++; j=0; if(temp1[0]=='{'||temp1[0]=='(') j++; do { if(temp1[j]==',') j++; k=0; while(temp1[j]!=','&&temp1[j]!=')'&&temp1[j]! ='}'&&temp1[j]!='-') { temp[k]=temp1[j]; k++; j++; } temp[k]='\0'; attcode=compare(temp); f[fdcount].left[f[fdcount].lcount]=attcode; f[fdcount].lcount++; }while(temp1[j]==','); if(temp1[j]==')'||temp1[j]=='}') j+=3; else if(temp1[j]=='-') j+=2; if(temp1[j]=='{'||temp1[j]=='(') j++; do { if(temp1[j]==',') j++; k=0; while(temp1[j]!=','&&temp1[j]!=')'&&temp1[j]! ='}'&&temp1[j]!='\0') { temp[k]=temp1[j]; k++; j++; } temp[k]='\0'; attcode=compare(temp); f[fdcount].right[f[fdcount].rcount]=attcode; f[fdcount].rcount++; }while(temp1[j]==','); } /**************Step1************** 1. Find the attributes that are neither on the left and right side*/ get_nolnor(); /**************Step2************* 2. Find attributes that are only on the right side*/ get_ronly(); /**************Step3************* 3. Find attributes that are only on the left side*/ get_lonly(); /**************Step4************* 4. Combine the attributes on step 1 and 3*/ get_merg1n3(); //combine nolnor and lonly /**************Step5************* 5. Test if the closures of attributes on step 4 are all the attributes*/ closcount=0; for(i=0;merg1n3[i]!=222;i++) { closure[closcount++]=merg1n3[i]; } getclosure(); i=iscomplete();//check whether closure of merg1n3 is complete if(i==1) { printf("\nThe candidate key is:\n{"); for(i=0;merg1n3[i]!=222;i++) { printf("%s,",attr[merg1n3[i]]); } printf("\b "); printf("}"); } else { /************** Step 6 ************** 6. Find the relation exteriors, that is the attrbutes included not in 4 and not in 2 included not in (ronly & merg1n3) */ k=0; for(i=0;i<attrcount;i++) { found=0; for(j=0;ronly[j]!=222;j++) { if(i==ronly[j]) { found=1; break; } } if(found==0) { for(j=0;merg1n3[j]!=222;j++) { if(i==merg1n3[j]) { found=1; break; } } } if(found==0) { exteriors[k++]=i; } } exteriors[k]=222; printf("Candidate Keys:"); /************** Step 6 ************** 7. Now test the closures of attributes on step 4 + one attribute in step 6 one at a time. */ for(k=0;exteriors [k]!=222;k++) { closcount=0; for (i=0;merg1n3[i]!=222;i++) { closure [closcount++]=merg1n3[i]; } closure [closcount++]=exteriors[k]; getclosure(); i=iscomplete();//check whether closure of this instance of this step is complete if(i==1) { printf("\n{"); for(i=0;merg1n3[i]!=222;i++) { printf("%s,",attr[merg1n3[i]]); } printf("%s}",attr[exteriors[k]]); } } } getch(); }
Sorting Numbers based on Weights - Zoho Programming Test question
You are given a set of numbers like <10, 36, 54,89,12>. You should find sum of weights
based on the following conditions:
<10,its_weight>,<36,its weight><89,its weight>
The program should display the numbers in increasing order of their their weights.
- 5 if a perfect square
- 4 if multiple of 4 and divisible by 6
- 3 if even number
<10,its_weight>,<36,its weight><89,its weight>
The program should display the numbers in increasing order of their their weights.
#include<stdio.h> #include<math.h> int getWeight(int n) { int w=0; float root=sqrt(n); if(root==ceil(root)) w+=5; if(n%4==0&&n%6==0) w+=4; if(n%2==0) w+=3; return w; } void main() { int nums[15]; int ws[15]; int i,j,t,n; printf("Enter number of numbers"); scanf("%d",&n); printf("\nEnter numbers"); for(i=0;i<n;i++) scanf("%d",&nums[i]); for(i=0;i<n;i++) ws[i]=getWeight(nums[i]); printf("\nBefore sorting:\n"); for(i=0;i<n;i++) printf("%d:%d\t",nums[i],ws[i]); for(i=0;i<n;i++) for(j=0;j<n-i-1;j++) if(ws[j]>ws[j+1]) { t=ws[j+1]; ws[j+1]=ws[j]; ws[j]=t; t=nums[j+1]; nums[j+1]=nums[j]; nums[j]=t; } printf("\nSorted:\n"); for(i=0;i<n;i++) printf("%d:%d\t",nums[i],ws[i]); }
C Program to Validate Sudoku - Checking Correctness of Sudoku
Here we shall see a c program to validate sudoku a sudoku. The c program i have written here checks the correctness of a sudoku. The programs can be used to check sudoku solution for 9x9 sudoku. First of all, we should know what are the constraints.
To test the program, you may try the following inputs. You may copy paste a line from below sudoku solutions to the program. (Each line is a correct solution)
- Each row should contain all numbers from 1 to 9 (inclusive)
- Each column should contain all numbers from 1 to 9 (inclusive)
- The 3x3 squares should also contain all numbers from 1 to 9 (inclusive)
#include<stdio.h> #include<stdlib.h> #include<unistd.h> void report(char *s,int i,int j) { printf("\nThe sudoku is INCORRECT"); printf("\nin %s. Row:%d,Column:%d",s,i+1,j+1); getch(); exit(0); } void main() { int i,j,a[9][9]; char c; int si,sj,flag; printf("\nEnter the sudoku"); /* Going to read sudoku matrix (9x9). Since numbers 1 to 9 are single digit, it is enough to read them as char. To convert them from their ascii to int, subtract ascii of '0' from the character. */ for(i=0;i<9;i++) for(j=0;j<9;j++) { scanf("%c",&c); a[i][j]=c-'0'; } /*++++++++++++++++++ checking rows +++++++++++++++++++ we check each cell in each row. We start with a flag 0x0000. if 1 is found zeroth bit of flag is set. if 2 is found, first bit is set and so on. If all digits 1 to 9 are present, flag's value will be 0x01FF. If flag is 0x01FF after traversing a row, the row has all numbers 1 to 9. So, it is correct. If the flag is not 0x01FF after traversing a row, the row is incorrectly filled. Then we call report() function */ for(i=0;i<9;i++) { flag=0x0000; for(j=0;j<9;j++) flag|=1<<(a[i][j]-1); if(flag!=0x01FF) report("row",i,j-1); } /*++++++++++++++++++ checking columns +++++++++++++++++++ Just like row checking. The flag is for a column. */ for(j=0;j<9;j++) { flag=0x0000; for(i=0;i<9;i++) flag|=1<<(a[i][j]-1); if(flag!=0x01FF) report("col",i-1,j); } /*++++++++++++++++++ checking Squares (3x3) +++++++++++++++++++ Just like row checking. The flag is for a square. */ for(si=0;si<3;si++) { for(sj=0;sj<3;sj++) { flag=0x0000; for(i=0;i<3;i++) { for(j=0;j<3;j++) flag|=1<<(a[si*3+i][sj*3+j]-1);
} if(flag!=0x01FF) report("square",si*3+i-1,sj*3+j-1); } } printf("\nThe sudoku is correct"); }
To test the program, you may try the following inputs. You may copy paste a line from below sudoku solutions to the program. (Each line is a correct solution)
123456789759183426648297315374915268896372154512864973931528647265749831487631592 123456789857923164964817235386241597275639841491578623538764912642195378719382456 123456789759283614486971253342768591891542367567319428935127846278694135614835972 123456789849173256765298431586941372291735648437862915352617894978524163614389527 123456789784913652569827134316598247845271963297634815652149378938765421471382596 123456789496817235587329461864275193359184627712693854631942578978561342245738916 123456789746198532859732146298314675374569821615287394967845213481623957532971468 123456789867239145954781362392567418416928573578143926745692831281375694639814257 123456789475981362869327541654813927791642853382795614938164275516279438247538196 123456789968137524457892136892374651716285493534619872685943217279561348341728965 123456789645987312897312645972863451536124897418579236364291578289735164751648923
Program to Find Number of Grandchildren - Zoho Programming Test Question
Here we will see a c program to find number of grandchildren, great grandchildren great-great grandchildren and so-on of a given person. In this program, the input is a table with two columns, 'Child' and 'Father'. Then we enter a name whose number grandchildren, great grandchildren etc is to be calculated. We do not have to count children. An example is:
Given a two dimensional array of strings like
Where in each row, the first string is “child”, second string is “Father”. And given “ronaldo” we have to find his no of grandchildren. Here “ronaldo” has total 3 grandchildren (2 grandchildren: wayne and shaw ; a great grandchild luke). So our output should be 3.
Given a two dimensional array of strings like
<”luke”, “shaw”> <”wayne”, “rooney”> <”rooney”, “ronaldo”> <”shaw”, “rooney”>
Where in each row, the first string is “child”, second string is “Father”. And given “ronaldo” we have to find his no of grandchildren. Here “ronaldo” has total 3 grandchildren (2 grandchildren: wayne and shaw ; a great grandchild luke). So our output should be 3.
#include<stdio.h> #include<string.h> int n; char name[20]; struct reln{ char child[20]; char father[20]; }r[10]; int count=0; void countChildren(char name[]) { int j; for(j=0;j<n;j++) { if(strcmp(name,r[j].father)==0) { count++; countChildren(r[j].child); } } } void main() { int i; printf("\nEnter the number of inputs: "); scanf("%d",&n); for(i=0;i<n;i++) { scanf("%s",r[i].child); scanf("%s",r[i].father); } printf("\nEnter name of the one whose no. of grandchildren is needed: "); scanf("%s",name); for(i=0;i<n;i++) { if(strcmp(r[i].father,name)==0) countChildren(r[i].child); } printf("\nNo .of grandchildren of %s=%d",name,count); }
Program to Display String with Odd Number of Letters in the shape of letter 'X' - Zoho Programming Test Question
One of the previous questions in the programming round of Zoho recruitment process was to write a C program to display any string with odd number of letters as follows, in the shape of letter 'X'.
Print the word with odd number of letters as
Print the word with odd number of letters as
P M R A O R G O R R A P M
#include<stdio.h> #include<string.h> #include<stdlib.h> void main() { int n,i,j,k,l; char str[20]; printf("Enter a string with odd number of letters."); scanf("%s",str); if((n=strlen(str))%2==0) { printf("\nNot odd"); exit(0); } for(i=0;i<n;i++) { printf("\n"); for(j=0;j<n;j++) { if(i==j||j==n-1-i) printf("%c",str[j]); else printf(" "); } } }
C Program to Burst Consecutively Repeated Numbers From Array - Zoho Programming Round Question
This was one of the programming round (hands on coding) questions in recruitment process of Zoho, an IT company. The question is to write a c program to remove all consecutive repetition of numbers in given array. We should also keep in mind that, if we remove one set of consecutive repeated number, this removal may cause another repetition as illustrated in following example.
example array: 2 3 5 3 8 8 8 3 3 5 3 1 2
Solving: 2 3 5 3 8 8 8 3 3 5 3 1 2 -> 2 3 5 3 3 3 5 3 1 2 -> 2 3 5 5 3 1 2 -> 2 3 3 1 2 -> 2 1 2
output: 2 1 2
I hope that you understood how the removal of consecutive appearance of numbers should be. I hope the program will explain you more.
#include<stdio.h> void main() { int a[20],i,j,k,n; printf("Enter Number of elements"); scanf("%d",&n); printf("Enter elements"); for(i=0;i<n;i++) scanf("%d",&a[i]); i=0; for(;i<n-1;) { j=1; while(i+j<n&&a[i+j]==a[i]) j++; if(j==1) { i++; continue; } for(k=0;k<n-(i+j);k++) a[i+k]=a[i+j+k]; n-=j; if(i>0) i--; } printf("Output:\n"); for(i=0;i<n;i++) printf("%d",a[i]); getch(); }
Algorithm and C Program to Find Closure From Functional Dependencies
In this post we will see how to find closure of an attribute or a set of attributes. Before learning how to get closure, we should first know what is a closure. Closure of a given set C is the set of attributes that are functionally determined by the set C under the set of functional dependencies F. There can be closure for any set. Every attribute in the set whose closure is to be found out, will be a member of its closure set C+ also. Consider an example:
Macro Preprocessor for C Using C - Simulation of Macro Processor in C Language
You might have used macros in different languages. In C language, we use #define preprocessor directive for macros. Macro preprocessor expands macro calls (macro invocation) using the macro definition. In this post, we will see a c program to simulate macro preprocessing. This program implements a macro preprocessor for c using c. The program obtains macro definition and parameters from #define directives and replaces every macro call with macro definition with formal parameters substituted with actual ones.
The input to the program is a c program named input.c which should located in the same directory of this program. The output of this program will be displayed in screen and also an output file is generated with name output.c which is located in the same directory. The following is the macro preprocessor program. Below that, i have added a sample input program and corresponding output (with expanded macros).
The input to the program is a c program named input.c which should located in the same directory of this program. The output of this program will be displayed in screen and also an output file is generated with name output.c which is located in the same directory. The following is the macro preprocessor program. Below that, i have added a sample input program and corresponding output (with expanded macros).
Macro Preprocessor Program
#include<stdio.h> #include<string.h> #include<stdlib.h> struct argItem { char name[15]; int argCount; char args[10][15]; char def[100]; }MacroTab[10]; char ch,*sourceCode; char *output,*line; int MacroCount=0,MacroUsed=0; int indexof(char *subString,int fromIndex,char *MainString) { int Mainlength,subLength,i,j,retIndex=-1; Mainlength=strlen(MainString); subLength=strlen(subString); if(Mainlength<1||subLength<1||Mainlength-fromIndex<subLength) return(-1); for(i=fromIndex;Mainlength-i>=subLength;i++) { if(*(MainString+i)==*(subString)) { retIndex=i; for(j=0;j<subLength;j++) { if(*(MainString+i+j)!=*(subString+j)) { retIndex=-1; break; } } if(retIndex!=-1) return retIndex; } } return (-1); } char * subString(char *MainString,int fromIndex,int toIndex) { int Mainlength,j; char *subStr; Mainlength=strlen(MainString); if(fromIndex<0||fromIndex>=Mainlength||toIndex<fromIndex||toIndex>=Mainlength) { return(NULL); } subStr=(char *)malloc(1000*sizeof(char)); for(j=0;j<=toIndex-fromIndex;j++) *(subStr+j)=*(MainString+fromIndex+j); *(subStr+j)='\0'; return(subStr); } char * replace(char *MainString,char *victim,char *newComer) { int Mainlength,victimLength,newComerLength,MainI,OutI,j,found; char *output; Mainlength=strlen(MainString); victimLength=strlen(victim); newComerLength=strlen(newComer); if(Mainlength<victimLength||victimLength<1||newComerLength<1) { return(NULL); } output=(char *)malloc(1000*sizeof(char)); OutI=0; for(MainI=0;MainI<Mainlength;MainI++) { if(*(MainString+MainI)!=*(victim)) { *(output+OutI)=*(MainString+MainI); OutI++; } else { found=1; if(Mainlength-MainI<victimLength) found=0; else { for(j=1;j<victimLength;j++) { if(*(MainString+MainI+j)!=*(victim+j)) { found=0; break; } } } if(found==0) { *(output+OutI)=*(MainString+MainI); OutI++; } else { for(j=0;j<newComerLength;j++) { *(output+OutI)=*(newComer+j); OutI++; } MainI+=victimLength-1; } } } *(output+OutI)='\0'; return(output); } char* NextLine() { int i=0,end=0,j,k; char *ret; if(strlen(sourceCode)<1) return(NULL); i=indexof("\n",0,sourceCode); if(i==-1) { i=strlen(sourceCode); end=1; } ret=subString(sourceCode,0,i); sourceCode=sourceCode+i+1-end; return(ret); } void scan() { int i,j,k,l; char temp[30]; i=indexof("#define",0,sourceCode); if(i>0) { printf("\nMacros found in source code"); MacroUsed=1; i=0; while(indexof("#define",i,sourceCode)>0) { i=indexof("#define",i,sourceCode)+1; j=indexof(" ",i,sourceCode)+1; k=indexof("(",j,sourceCode)-1; strcpy(MacroTab[MacroCount].name,subString(sourceCode,j,k)); strcpy(temp,subString(sourceCode,k+2,indexof(")",k+2,sourceCode)-1)); i=indexof(")",k+2,sourceCode); k=0; for(j=0;temp[j]!='\0';j++) { if(temp[j]==',') { strcpy(MacroTab[MacroCount].args[MacroTab[MacroCount].argCount],subString(temp,k,j-1)); k=j+1; MacroTab[MacroCount].argCount++; } } strcpy(MacroTab[MacroCount].args[MacroTab[MacroCount].argCount],subString(temp,k,j-1)); MacroTab[MacroCount].argCount++; strcpy(MacroTab[MacroCount].def,subString(sourceCode,i+2,indexof("\n",i+2,sourceCode)-1)); MacroCount++; } } else { MacroUsed=0; } } void main() { FILE *input,*outfile; int i=0,t,u,j,k,l; char *tempDef,var[15]; input=fopen("input.c","r"); tempDef=(char*)malloc(200*sizeof(char)); sourceCode=(char*)malloc(1500*sizeof(char)); while((ch=getc(input))!=EOF) { sourceCode[i++]=ch; } sourceCode[i]='\0'; printf("%s",sourceCode); fclose(input); scan(); output=(char*)malloc(1200*sizeof(char)); *output='\0'; if(MacroUsed==1) { for(l=0;l<MacroCount;l++) { printf("\nMacro Name:%s, Macro def:%s, args: ",MacroTab[l].name,MacroTab[l].def); for(i=0;i<MacroTab[l].argCount;i++) printf("%s ",MacroTab[l].args[i]); } while((line=NextLine(sourceCode))!=NULL) { if(indexof("#define",0,line)!=-1) continue; for(i=0;i<MacroCount;i++) { t=indexof(MacroTab[i].name,0,line); if(t!=-1) { t=0; while((t=indexof(MacroTab[i].name,t,line))!=-1) { strcpy(tempDef,MacroTab[i].def); u=indexof("(",t,line)+1; j=0; while((k=indexof(",",u,line))!=-1) { strcpy(var,subString(line,u,k-1)); tempDef=replace(tempDef,MacroTab[i].args[j],var); u=k+1; j++; } k=indexof(")",u,line)-1; strcpy(var,subString(line,u,k)); tempDef=replace(tempDef,MacroTab[i].args[j],var); j=indexof(")",t,line); line=replace(line,subString(line,t,j),tempDef); t=t+strlen(MacroTab[i].name); } } } strcat(output,line); if(indexof("\n",0,line)<0) strcat(output,"\n"); } } else { strcpy(output,sourceCode); } outfile=fopen("output.c","w"); l=0; printf("\nCode After macro preprocessing:\n"); while(l<strlen(output)) { putc(*(output+l),outfile); printf("%c",*(output+l)); l++; } fclose(outfile); }
Sample Input Program (input.c)
#include<stdio.h> #define cube(x) x*x*x #define min(x,y) (x<y)?x:y void main() { printf("\nCube of 4=%d",cube(4)); printf("\nMin of 3 and 4 =%d",min(3,4)); printf("\nMin of 10 and 15 =%d",min(15,10)); }
Corresponding Output (output.c)
#include<stdio.h> void main() { printf("\nCube of 4=%d",4*4*4); printf("\nMin of 3 and 4 =%d",(3<4)?3:4); printf("\nMin of 10 and 15 =%d",(15<10)?15:10); }
C Program To Find Largest Interval of Integers For Which All Numbers In It Are Present In Given Array
This is a question asked in technical interview or programming round by the IT company Zoho during its recruitment process. The question is:
Write a program to find the largest interval (of integers) such that all the integers in the interval are present in the given array.
The input to the program is an integer array. The output is an integer interval (two integers as lower bound and upper bound of interval). All the elements in between the bounds (including the bounds) should be present in the array. Also, it should not be possible to find any other larger interval with all the numbers in it present in the array.
We first sort the given array in ascending order. Let
The program is as follows:
Write a program to find the largest interval (of integers) such that all the integers in the interval are present in the given array.
The input to the program is an integer array. The output is an integer interval (two integers as lower bound and upper bound of interval). All the elements in between the bounds (including the bounds) should be present in the array. Also, it should not be possible to find any other larger interval with all the numbers in it present in the array.
We first sort the given array in ascending order. Let
tlb= lower bound of temporary interval (interval in consideration)We copy first element (a[0]) to all above variables. Then traverse the array from second element (a[1]) to its end. If the current element is equal to the previous element plus one, then the temporary upper bound (tub) is set to the current element. Otherwise, if (tub-tlb)>(upper_bound-lower_bound), temporary bounds are copied to the largest bounds and tlb and tub are set to current element.
tub= upper bound of temporary interval
upper_bound=upper bound of largest interval
lower_bound=lower bound of largest interval
The program is as follows:
#include<stdio.h> void main() { int i,j,t,a[20],n,lower_bound,upper_bound,tlb,tub; printf("\nEnter number of elements:"); scanf("%d",&n); printf("\nEnter elements:"); for(i=0;i<n;i++) scanf("%d",&a[i]); for(i=0;i<n-1;i++) { for(j=0;j<n-i-1;j++) { if(a[j]>a[j+1]) { t=a[j]; a[j]=a[j+1]; a[j+1]=t; } } } lower_bound=upper_bound=tlb=tub=a[0]; for(i=1;i<n;i++) { if(a[i]==a[i-1]+1) { tub=a[i]; } else { if(tub-tlb>upper_bound-lower_bound) { upper_bound=tub; lower_bound=tlb; } tlb=a[i]; tub=a[i]; } } if(tub-tlb>upper_bound-lower_bound) { upper_bound=tub; lower_bound=tlb; } printf("\nLargest interval with all its elements present in array:[%d,%d]",lower_bound,upper_bound); }
C Program to Replace All Occurrences of a Substring with Another String
After the c programs to replace first occurrence of substring and last occurrence of substring, i am posting a c program to replace all the occurrences of a given substring inside the original string.
You may also see:
C Program to Replace First Occurrence of a Substring With Another String
C Program to Replace Last Occurrence of a Substring With Another String
Here also, i have written a function which takes three parameters (the main string, the substring to be replaced and the substring to replace with). The function return a string with all the occurrences of the substring replaced with the specified string. The program uses pointer for manipulating the strings. The program is as follows:
You may also see:
C Program to Replace First Occurrence of a Substring With Another String
C Program to Replace Last Occurrence of a Substring With Another String
Here also, i have written a function which takes three parameters (the main string, the substring to be replaced and the substring to replace with). The function return a string with all the occurrences of the substring replaced with the specified string. The program uses pointer for manipulating the strings. The program is as follows:
#include<stdio.h> #include<string.h> char* replaceAll(char* mainstr,char * substr,char* newstr) { int lenmain,lensub,i,j,lennew,startindex=-1,limit,c; lenmain=strlen(mainstr); lensub=strlen(substr); lennew=strlen(newstr); char *result=(char*)malloc(sizeof(char)*(lenmain+200)); for(c=0,i=0;i<lenmain;i++) { if(lenmain-i>=lensub&&*(mainstr+i)==*(substr)) { startindex=i; for(j=1;j<lensub;j++) if(*(mainstr+i+j)!=*(substr+j)) { startindex=-1; break; } if(startindex!=-1) { for(j=0;j<lennew;j++,c++) { *(result+c)=*(newstr+j); } i=i+lensub-1; } else { *(result+c)=*(mainstr+i); c++; } } else { *(result+c)=*(mainstr+i); c++; } } *(result+c)='\0'; return result; } void main() { char a[300],sub[50],news[50]; printf("\nEnter original:"); gets(a); printf("\nEnter sub string to be replaced:"); gets(sub); printf("\nEnter new string to replace with:"); gets(news); printf("\nresult:"); puts(replaceAll(a,sub,news)); }
Subscribe to:
Posts (Atom)