Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes


C Programming Code Examples

C > Beginners Lab Assignments Code Examples

Find the Nearest Common Ancestor in the Given set of Nodes

/* Find the Nearest Common Ancestor in the Given set of Nodes This C Program prints all the elements of Nth level in single line. */ #include <stdio.h> #include <stdlib.h> /* Structure of binary tree node */ struct btnode { int value; struct btnode *l; struct btnode *r; }; void createbinary(); node* add(int val); int height(node *); int nearest_common_ancestor(node*, int, int); typedef struct btnode node; node *root = NULL, *ptr; int main() { int c, x1, x2; createbinary(); printf("\nEnter nodes having common ancestor"); scanf("%d %d", &x1, &x2); c = nearestcommonancestor(root, x1, x2); if (c == -1) { printf("No common ancestor"); } else { printf("The common ancestor is %d", c); } } /* * constructing the following binary tree * 50 * / \ * 20 30 * / \ * 70 80 * / \ \ *10 40 60 */ void createbinary() { root = add(50); root->l = add(20); root->r = add(30); root->l->l = add(70); root->l->r = add(80); root->l->l->l = add(10); root->l->l->r = add(40); root->l->r->r = add(60); } /*Add node to binary tree */ node* add(int val) { ptr = (node*)malloc(sizeof(node)); if (ptr == NULL) { printf("Memory was not allocated"); return; } ptr->value = val; ptr->l = NULL; ptr->r = NULL; return ptr; } /*height of the binary tree */ int height(node *n) { int lheight, rheight; if (n != NULL) { lheight = height(n->l); rheight = height(n->r); if (lheight > rheight) return(lheight + 1); else return(rheight + 1); } } /*Finds the nearest common ancestor */ int nearestcommonancestor(node *temp, int x1, int x2) { int h, i, j, k; node *prev; /*If any one the inputted node is root then no common ancestor */ if (x1 == root->value || x2 == root->value) { return - 1; } h = height(root); for (i = 1;i < h;i++) { if (temp->l->value == x1 || temp->r->value == x1 || temp ->l->value == x2 || temp->r->value == x2) { prev = temp; for (j = 1, temp = root;j < h;j++) { if (temp != NULL) { if (temp->r->value == x2 || temp->r->value == x1 || temp->l->value == x1 || temp->l->value == x2) { /* * If the parent of x1 and parent of x2 are same then the value of parent is returned */ if (prev->value == temp->value) return prev->value; /* * otherwise from parents of two nodes is traversed upward if any node matches with other's node parent then that is * considered as common ancestor */ else for (k = 0, prev = temp;k < h;k++) { if (temp->l->value == prev->l->value) return temp->value; else temp = temp->l; } } } temp = temp->l; } } temp = temp->l; } }

The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities. The if...else ladder allows you to check between multiple test expressions and execute different statements. In C/C++ if-else-if ladder helps user decide from among multiple options. The C/C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.

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 expression containing logical operator returns either 0 or 1 depending upon whether expression results true or false. Logical operators are commonly used in decision making in C programming. These operators are used to perform logical operations and used with conditional statements like C if-else statements.

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,

Read formatted data from stdin. Reads data from stdin and stores them according to the parameter format into the locations pointed by the additional arguments. The additional arguments should point to already allocated objects of the type specified by their corresponding format specifier within the format string. In C programming, scanf() is one of the commonly used function to take input from the user. The scanf() function reads formatted input from the standard input such as keyboards. The scanf() function enables the programmer to accept formatted inputs to the application or production code. Moreover, by using this function, the users can provide dynamic input values to the application.

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.

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.

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.

C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements inside another loop. Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for example, you can define 'while' loop inside a 'for' loop.

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.

#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:





Reads a number of objects by size and stores them in buf. C programming code returns the number of items actually read. Get open a file and read. If there is an error give a message.




Prints the Fibonacci of a given number using recursion. In fibonacci series, each number is the sum of the two preceding numbers. 0, 1, 1, 2, 3, 5, 8, ... The following program returns

Program to find electricity bill using if else in C. Input unit consumed by customer in some variable say unit and if unit consumed less or equal to 50 units. Then amt = unit * 0.50. Unit


Program code enter Month number between 1-12 and print number of days in month using If Else. Input month number from user. Store it in a variable say month and for each month