C Programming Code Examples
C > Arrays and Matrices Code Examples
Construct a Balanced Binary Tree using Sorted Array
/* Construct a Balanced Binary Tree using Sorted Array */
/*
* 40
* / \
* 20 60
* / \ \
* 10 30 80
* \
* 90
* (Given Binary Search Tree)
*/
#include <stdio.h>
#include <stdlib.h>
struct btnode
{
int value;
struct btnode *l;
struct btnode *r;
};
typedef struct btnode N;
N* bst(int arr[], int first, int last);
N* new(int val);
void display(N *temp);
int main()
{
int arr[] = {10, 20, 30, 40, 60, 80, 90};
N *root = (N*)malloc(sizeof(N));
int n = sizeof(arr) / sizeof(arr[0]), x;
printf("Given sorted array is\n");
for (x = 0;x < n;x++)
printf("%d\t", arr[x]);
root = bst(arr, 0, n - 1);
printf("\n The preorder traversal of binary search tree is as follows\n");
display(root);
printf("\n");
return 0;
}
/* To create a new node */
N* new(int val)
{
N* node = (N*)malloc(sizeof(N));
node->value = val;
node->l = NULL;
node->r = NULL;
return node;
}
/* To create a balanced binary search tree */
N* bst(int arr[], int first, int last)
{
int mid;
N* temp = (N*)malloc(sizeof(N));
if (first > last)
return NULL;
mid = (first + last) / 2;
temp = new(arr[mid]);
temp->l = bst(arr, first, mid - 1);
temp->r = bst(arr, mid + 1, last);
return temp;
}
/* To display the preorder */
void display(N *temp)
{
printf("%d->", temp->value);
if (temp->l != NULL)
display(temp->l);
if (temp->r != NULL)
display(temp->r);
}
The sizeof() operator is commonly used in C. It determines the size of the expression or the data type specified in the number of char-sized storage units. The sizeof() operator contains a single operand which can be either an expression or a data typecast where the cast is data type enclosed within parenthesis. The data type cannot only be primitive data types such as integer or floating data types, but it can also be pointer data types and compound data types such as unions and structs.
An array is a collection of data items, all of the same type, accessed using a common name. A one-dimensional array is like a list; A two dimensional array is like a table; The C language places no limits on the number of dimensions in an array, though specific implementations may. Some texts refer to one-dimensional arrays as vectors, two-dimensional arrays as matrices, and use the general term arrays when the number of dimensions is unspecified or unimportant.
Allocate memory block. Allocates a block of size bytes of memory, returning a pointer to the beginning of the block. The content of the newly allocated block of memory is not initialized, remaining with indeterminate values. If size is zero, the return value depends on the particular library implementation (it may or may not be a null pointer), but the returned pointer shall not be dereferenced. The "malloc" or "memory allocation" method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. It doesn't Iniatialize memory at execution time so that it has initializes each block with the default garbage value initially.
The for loop is used in the case where we need to execute some part of the code until the given condition is satisfied. The for loop is also called as a per-tested loop. It is better to use for loop if the number of iteration is known in advance. The for-loop statement is a very specialized while loop, which increases the readability of a program. It is frequently used to traverse the data structures like the array and linked list.
In C, the "main" function is treated the same as every function, it has a return type (and in some cases accepts inputs via parameters). The only difference is that the main function is "called" by the operating system when the user runs the program. Thus the main function is always the first code executed when a program starts. main() function is a user defined, body of the function is defined by the programmer or we can say main() is programmer/user implemented function, whose prototype is predefined in the compiler. Hence we can say that main() in c programming is user defined as well as predefined because it's prototype is predefined. main() is a system (compiler) declared function whose defined by the user, which is invoked automatically by the operating system when program is being executed.
An array is defined as the collection of similar type of data items stored at contiguous memory locations. Arrays are the derived data type in C programming language which can store the primitive type of data such as int, char, double, float, etc. It also has the capability to store the collection of derived data types, such as pointers, structure, etc. The array is the simplest data structure where each data element can be randomly accessed by using its index number.
#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program. Here are the two types of file that can be included using #include:
The if-else statement is used to perform two operations for a single condition. The if-else statement is an extension to the if statement using which, we can perform two different operations, i.e., one is for the correctness of that condition, and the other is for the incorrectness of the condition. Here, we must notice that if and else block cannot be executed simiulteneously. Using if-else statement is always preferable since it always invokes an otherwise case with every if condition.
Writes the C string pointed by format to the standard output (stdout). If format includes format specifiers (subsequences beginning with %), the additional arguments following format are formatted and inserted in the resulting string replacing their respective specifiers. printf format string refers to a control parameter used by a class of functions in the input/output libraries of C programming language. The string is written in a simple template language: characters are usually copied literally into the function's output, but format specifiers, which start with a % character, indicate the location and method to translate a piece of data (such as a number) to characters. "printf" is the name of one of the main C output functions, and stands for "print formatted". printf format strings are complementary to scanf format strings, which provide formatted input (parsing). In both cases these provide simple functionality and fixed format compared to more sophisticated and flexible template engines or parsers,
The typedef is a keyword used in C programming to provide some meaningful names to the already existing variable in the C program. It behaves similarly as we define the alias for the commands. In short, we can say that this keyword is used to redefine the name of an already existing variable.
C Programming code gives all details of a Triangle given the lengths of its sides. Enter the lengths of the three sides of the triangle. S is the semiperimeter of the triangle. D is...
C programming language Snake game. Use arrow keys to direct the snake. Avoid the head of snake not to hit any part of snake. Pick beats untill you win the game. Press