C++ Program to Multiply two Numbers

Here is a C++ program to multiply two numbers using * arithmetic operator. In this program, we are going to perform basic arithmetic operation of multiplying two integers using multiplication(*) operation.

Multiplication is one of the five fundamental arithmetic operators supported by C++ programming language, which are addition(+), subtraction(-), multiplication(*), division(/) and modulus(%). Multiplication operator multiplies both operands and returns the result.

C++ Program to Generate Random Numbers

In this C++ program, we generate N random numbers between 1 to 1000 using rand function. This program takes N as input from user and print N space separated random numbers on screen.

C++ Program for Input and Output of Integer

Here is a C++ program for input and output of integers. In this program, we will learn about taking an integer input from user using cin and then printing an integer on screen using cout. To perform any input and output operation in a C++ program, we have to include iostream header in program. Here is a C++ program for input and output of integer.

C++ Class Constructor and Destructor

Constructor and destructor functions are essential components of object-oriented programming in C++. Constructors initialize objects when they are created, and destructors clean up resources before an object is destroyed. This tutorial explores the concepts, types, and best practices associated with constructor and destructor functions in C++.

C++ Constructor Function

A constructor is a special member function of a class that is automatically called when an object of the class is created. Its primary purpose is to initialize the object's data members and set up the object's state.

The declaration of a constructor function is similar to any other member function except the name of the function must match the class name and without any return type not even void.

Constructor functions are mainly used for initialization of member variables and for doing some pre-processing. If we don't define any constructor function then C++ compiler automatically created a default constructor.

C++ Classes and Objects

Object Oriented Programming

Object-oriented programming (OOP) is a programming paradigm that revolves around the concept of "objects," which are instances of classes. In C++, OOP is a fundamental feature that facilitates the organization, reuse, and maintenance of code. Classes serve as blueprints for creating objects, encapsulating data and behavior into a single unit. The key principles of OOP in C++ include encapsulation, inheritance, and polymorphism.

Encapsulation involves bundling data and methods that operate on that data within a single class, preventing direct access to internal details and enhancing modularity. Inheritance allows the creation of new classes based on existing ones, promoting code reuse and extensibility. Polymorphism enables the use of a common interface to interact with objects of different types, fostering flexibility in handling diverse data structures.

By employing OOP in C++, developers can achieve modularity, code organization, and enhanced readability. The paradigm supports the creation of well-structured, scalable, and maintainable software systems. Through classes and objects, C++ programmers can design solutions that align with real-world entities and efficiently address complex programming challenges.

C++ programming language was earlier known as C with classes. C++ is an extension of C with support for object oriented programming paradigm. Classes and objects forms the backbone of object oriented programming. The class is one of the defining ideas of object-oriented programming.

C++ Pointers to Structure and Passing Structure to Function

In C++, the pointers to a structure variable in very similar to the pointer to any in-built data type variable. A pointer to a structure in C++ is a variable that stores the memory address of a structure. This combination allows for dynamic memory allocation, efficient data manipulation, and provides a mechanism for working with complex data structures.

C++ Structures

Structure in C++ programming language groups logically related information of different data types under a single name.

A structure variable can store multiple variables of different data types. Each variable declared in structure is called member. All member variables of a structure are stored in contiguous memory locations.

C++ Pointers and Arrays

Relationship between Array and Pointers

In C++, pointer arithmetic involves manipulating the memory addresses held by pointers. Unlike other languages, C++ allows direct manipulation of pointers, providing unparalleled control over memory. Pointer arithmetic is primarily applied to pointers pointing to arrays, enabling efficient traversal and manipulation.

Pointer arithmetic involves adding or subtracting integers to/from pointers, resulting in a new memory address. The size of the data type to which the pointer points determines the actual memory offset.

  • The name of the array is a const pointer to the beginning of the array. It contains the address of first array element.

C++ Pointers

A pointer in C++ allows us to directly access data stored at a particular memory location. Pointers are one of the most powerful feature of C++ programming language. Once you master the use of pointers, you will use them everywhere to make the code more efficient and faster. In C++, some operations can be performed more efficiently using pointers like dynamic data structures like linked list and trees,dynamic memory allocation, pass arguments to a function as Call by Reference, access array elements etc.

C++ Strings

Strings are a fundamental data type, serving as the building blocks for text manipulation and processing. In C++, a string is a sequence of characters, enclosed within double quotation marks. C++ supports two types of String representations:

  • C Strings (terminated by a null character('\0'))
  • Objects of string class (C++ Library provides a string class)

C++ Multidimensional Arrays

C++ programming language supports multi dimensional Arrays. Multidimensional arrays can be described as "arrays of arrays". A multidimensional array in C++ is an array of arrays, extending the concept of a one-dimensional array to handle more complex data structures.

The most common type of multidimensional array is the two-dimensional array, often used to represent matrices. These arrays offer a structured and powerful way to represent complex data structures, such as matrices and grids. For Example, a two dimensional array:

C++ Accessing Array Elements

In C++, We can access array element using array name and subscript/index written inside pair of square brackets [].

C++ Arrays

Array in C++ is a collection of fixed size data belongings to the same data type. An array is a data structure provided in C++ which can store a number of variables of same data type in sequence. These similar elements could be of type int, float, double, char etc. All array elements are stored in the contiguous memory locations.

C++ Function Overloading

Function overloading in C++ allows us to write multiple functions having same name, so long as they have different parameters; either because their number of parameters are different or because any of their parameters are of a different data type. You can not overload a function declarations that differ only by return type.

This feature provides a way to create functions that perform similar tasks for different types or numbers of parameters. The compiler determines which function to call based on the number and types of arguments provided during the function call.

C++ Storage Class

The Storage class in C++ defines the scope, life-time and where to store a variable in C++ program. These specifiers precede the type that they modify. There are four storage classes defined in C++ programming language

C++ Calling a Function and Return Statement

Calling a function in C++ programming language

After writing a function in C++, we should call this function to perform the task defined inside function body. We cannot execute the code defined inside function's body unless we call it from another function.

C++ Functions

Functions in C++ language are building blocks of a C++ program. A function is a sequence of statements to perform a specific task and it can be called by other functions. A function may take some input and perform a logical unit of task and may return the response to calling function.
The function in C++ language is also known as subroutine, procedure or method. Functions are the building blocks of modular and reusable code, allowing us to organize our programs, enhance readability, and encapsulate logic.

C++ continue Statement

The continue statement in C++ is used to skip some statements inside the body of the loop and forces the next iteration of the loop. The continue statement skips the rest of the statements of loop body in the current iteration.
Most of the time, continue statement is used with conditional statement inside body of the loop. Use of continue statement, change the normal sequence of execution of statements inside loop.

C++ break Statement

The break statement in C++ is used to terminate loops and switch statement immediately when it appears. We sometimes want to terminate the loop immediately without checking the condition expression of loop. Most of the time, break statement is used with conditional statement inside body of the loop.

C++ goto Statement

The goto statement in C++ is used to transfer the control of program to some other part of the program. A goto statement used as unconditional jump to alter the normal sequence of execution of a program.

Often regarded as a forbidden fruit, the goto statement allows us to jump from one part of our code to another. In this tutorial, we'll explore the syntax, use cases, advantages, and potential pitfalls of the goto statement.

C++ do while Loop

The do while loop in C++ is similar to while loop with one important difference, the code block of do..while loop is executed once before the condition is checked. It checks its condition at the bottom of the loop, before allowing the execution of loop body for second time. The block of code is before the condition, so code will be executed at lease once.

C++ While Loop

The while loop in C++ used for repetitive execution of the statements until the given condition is true. Unlike for loop in C++, there is no initialization and update statements in while loop. The while loop is a fundamental construct in C++ that empowers you to execute a block of code repeatedly as long as a specified condition holds true.

C++ For Loop

The for loop in C++ is used to execute execute some statements repetitively until the given condition is true. The for loop is mainly used to perform repetitive tasks.

C++ Switch Case Statement

A switch statement in C++ allows a variable or value of an expression to be tested for equality against a list of possible case values and when match is found, the block of code associated with that case is executed. It is similar to if..else ladder statement, but the syntax of switch statement is more readable and easy to understand.

The switch-case statement in C++ is a control flow mechanism designed to handle multiple conditions based on the value of an expression. It provides an efficient and structured way to execute different blocks of code depending on the value of a variable. Think of it as a multi-destination roadmap for your program.

C++ If Else Statement

The if statement in C++ programming language is used to execute a block of code only if a condition is true. It is used to check the truthness of the expression (In C++, all non-zero values are considered as true and zero is considered as false).

C++ Operators

In C++, an operator is a symbol used to perform logical and mathematical operations in a C++ program. An expression ia a statement containing operators and variables. C++ operators connects constants and variables to form expressions.

C++ Constants and Literals

Introduction to Constants

In the realm of C++, a constant is a symbol representing a value that cannot be altered during the execution of a program. Constants offer a way to assign meaningful names to fixed values, making your code more readable and maintainable. Let's explore the various types of constants and how they can elevate your coding experience.

  • Named Constants : Named constants are declared using the const keyword.
    const int MAX_VALUE = 100;
    
    In this example, MAX_VALUE is a named constant with a value of 100. Once set, its value remains unchanged throughout the program.

  • Enumerations : Enumerations, or enums, are user-defined data types consisting of named integral constants.
    enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
    
    Here, Days is an enumeration with constants representing each day of the week. Constants bring clarity and maintainability to your code by replacing magic numbers with meaningful names.

Introduction to Literals

Literals, on the other hand, are the raw, constant values themselves. They are the building blocks of your program, representing data in its most straightforward form. Let's explore the different types of literals and how they contribute to the rich tapestry of C++. In C++, a constant can be of any basic data types like boolean, character constants, integer constant, strings etc.

For Example : true, 'A', 754, 123.5, "Hello World".

Boolean literals in C++

C++ supports two boolean literals "true" and "false". true and false are part of the C++ keywords.


Integer Constants in C++

Integer constants are whole numbers without any fractional part or exponential part. It can either be positive or negative, If no sign precedes then by default it is assumed to be positive. The range of integer constant depends on programming environment. For Example, In a 16-bit system range of integer literal is -32768 to 32767.
An integer constant can be a decimal, octal, or hexadecimal. A prefix specifies the base of number system.

Prefix Description Base Example
0x or 0X Hexadecimal Number 16 0x5C, 0x22
0 Octal Number 8 012C, 0243
Nothing Decimal Number 10 25, 100


You can also specify the type of integer constant by using a suffix character. It can be lowercase or uppercase and can be in any order.
  • L, l : Long
  • U, u : Unsigned
Examples of Integer Constants
  • Unsigned Integer Constant : 100U, 565U
  • Long Constant : 67L, -2398876L
  • Unsigned Long Constant : 55UL, 77652UL
  • Decimal Constants : 85, -54
  • Octal Constants : 0213, 045
  • Hexadecimal Constants : 0x4b, 0x2A

Character Constants in C++

Character constants are enclosed between a pair or single quote. C++, supports two type of character constants, wide character literal and narrow character literal. If a character literal starts with uppercase 'L' then it is a Wide character (for Example : L'a') and must be stored in a variable of type wchar_t otherwise it is a narrow character(for Example : 'a') and can be stored in variable of type char. The ASCII value of character constants are stored internally.

For Example : 'a', 'A', '1', '#' are character constants. C++ Backslash Character Constants

There are some characters which are impossible to enter into a string from keyboard like backspace, vertical tab, newline etc. C++ includes a set of backslash character which have special meaning in C++ programming language. The backslash character ('\') changes the interpretation of the characters by C++ compiler.

Escape Sequence Description
\” Double quote(")
\' Single quote(')
\\ Backslash Character(\)
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab
\a Alert or bell
\? Question mark
\0 Null character
C++ Program to print character constants
#include <iostream>
using namespace std;

int main() {    
    char c1 = 'E';
    wchar_t wc = L'E'; 
    
    cout << c1 << endl;
    cout << wc << endl;
    // Printing newline character
    cout << '\n';
    printf("Tech\nCrash\nCourse");
 
    return(0);
}

Output
E
69

Tech
Crash
Course

C++ Floating-point Constants

A floating point constant has a integer part, a decimal point, a fractional part and may contain an exponential part. Floating point literal may be positive or negative but must have a decimal point. You can also represent floating point literals in scientific notation.

For Example: 1234.5432, -100.001, 2.37E-3

C++ String Constants

p class="myParagraph"> A string constant in C++ is a set of characters enclosed between a pair of double quotes. A string literal is actually a character array. A string literal may contain any number of characters including alphanumeric characters, escape characters, graphical characters etc.

For Example
  • "" : Null String.
  • "A" : String literal having one characters.
  • "XYZ12.iyu" : String literal with multiple characters.
  • "XYZ jjuh\n" : String with spaces and escape characters.

Declaration of Constants in C++

We can define constants in C++ in two ways.
  1. Using const keyword.
  2. Using #define preprocessor directives.
We can use const keyword as a prefix of data type to declare a Constant. Here is the syntax for using const keyword.
const data_type variable_name = Constant;
For Example
    const float INTEREST_PERSENTAGE = 9;
#include Preprocessor Directive

We can use #define preprocessor directive to define a constant as per following syntax.

#define Constant_Identifier Value
For Example:
    #define INTEREST_PERSENTAGE 9

C++ Program to show use of #include preprocessor
#include <iostream>
#define PI 3.141

using namespace std;
 
int main() {    
    float radius;
     
    cout << "Enter Radius of Circle\n";
    cin >> radius;
    
    cout << "Circumference of Circle : " << 2*PI*radius;
     
    return 0;
}

Output
Enter Radius of Circle
5.0
Circumference of Circle : 31.41

Hexadecimal and Octal Constants

C++ provides not only decimal but also hexadecimal and octal representations for numeric constants. Let's explore how to express constants in these bases:
  • Hexadecimal Constants : Hexadecimal constants are prefixed with 0x or 0X and use digits 0-9 and letters A-F.
    int hexValue = 0xA3;
    
    Here, 0xA3 is a hexadecimal constant.

  • Octal Constants : Octal constants are prefixed with 0 and use digits 0-7.
    int octalValue = 075;
    
    In this example, 075 is an octal constant. Using hexadecimal and octal constants can be advantageous in certain scenarios, especially when dealing with low-level programming and bitwise operations.

Conclusion

You've successfully navigated the rich terrain of constants and literals in C++. From understanding the purpose of constants and their role in enhancing code readability to exploring the various types of literals and their nuances, you're now equipped with the knowledge to wield these tools effectively in your programming endeavors.

As you continue your programming journey, remember that constants and literals are not just elements of syntax; they are storytellers within your code, conveying meaning and precision. Use them wisely to craft code that not only functions flawlessly but also communicates clearly.


C++ Data Types

In C++ programming language, data type specifies the type of data a variable can store and how much memory is required to store this data. The data type of a variable also defines the format in which a data of particular type should be stored.

C++ Keywords and Identifiers

C++ Keywords

C++ keywords are the reserved words which are pre-defined in C++ programming language. We cannot use keywords as an identifier. Each keyword has a pre-defined meaning for C++ compiler. These words are the building blocks of the language, each serving a specific purpose in the syntax and structure of C++ programs.

C++ Basic Input and Output

In the world of programming, input and output are the essential mechanisms through which a program communicates with the external environment. Input refers to data provided to the program, while output is the result or response produced by the program.

In this tutorial we learn about basic input and output capabilities provided by C++ programming language. For Input and output, C++ programming language uses an abstraction called streams which are sequences of bytes. A stream is an abstract entity where a program can either write or read characters. It hides the hardware implementation and details from the C++ program.

C++ Comments

Comments are added in C++ program for documentation purpose. Comments are explanatory statements that we can in our code to make it easy to understand for anyone reading this source code. We can add comments anywhere and any number of times in our programs. Adding comments in your code is highly recommended and is considered as a good programming practice. Comment are ignored by C++ compilers.

They are meant for human readers, including yourself, your collaborators, or anyone who might work on your code in the future. Comments provide additional information about the code, explaining its purpose, logic, or any other relevant details.

C++ First Program Hello World

In this tutorial, we are going to learn about the basic structure of a C++ program. Let's first write a simple C++ program to print "Hello World" string on screen. This program is very useful to learn the basic syntax and semantics of the C++ language. It become the traditional first program that many people write while learning a new programming language.

Difference Between C and C++ Language

The major difference between C and C++ is that, C is a procedural language whereas C++ is an extension of C which also supports object oriented programming paradigm.

Programming languages play a pivotal role in shaping the digital landscape, and among the stalwarts, C and C++ have stood the test of time. Both have roots in the C language, yet they have evolved differently, catering to diverse needs in the realm of software development.

Following table highlights the major differences between C and C++ programming languages.

C++ Programming Language Tutorial

Chania

C++ Programming Tutorial

C++ is a powerful and versatile programming language that combines the features of both high-level and low-level programming. Initially developed as an extension of the C programming language, C++ introduces object-oriented programming concepts.

C++ remains a popular choice for programmers seeking a balance between control and productivity in software development. Our simple C++ programming tutorial will lead you through the process of learning C++ programming one step at a time.


Key Features of C++

  • Simple and Efficient Language : C++ is designed to be a simple and efficient programming language. It retains the low-level features of C while introducing high-level abstractions, making it suitable for both system-level programming and application development.

  • Object-Oriented Programming (OOP) : C++ supports object-oriented programming, a paradigm that promotes the use of classes and objects. This allows for the organization of code into modular and reusable components, enhancing code structure and maintainability.

  • Platform-Independent : C++ is a platform-independent language, meaning that code written in C++ can be compiled and executed on different platforms with minimal or no modifications. This portability is crucial for developing cross-platform applications.

  • Memory Management : C++ allows manual memory management, giving programmers control over memory allocation and deallocation. While this provides flexibility, it also requires careful handling to avoid memory leaks and other issues.

  • Rich Standard Template Library (STL) : C++ comes with a powerful Standard Template Library (STL) that provides a collection of generic classes and functions. The STL includes containers (like vectors and lists), algorithms, and iterators, simplifying complex data structures and operations.

  • Multi-Paradigm Programming : C++ supports multiple programming paradigms, including procedural, object-oriented, and generic programming. This versatility allows developers to choose the most suitable approach for a given task.

Uses of C++ Programming Language

C++ finds applications in various domains due to its flexibility and efficiency. Some of the key uses include
  • System Programming : C++ is widely used for system-level programming where direct hardware access and memory manipulation are essential. Operating systems, device drivers, and firmware development often involve C++.

  • Game Development : Many popular game engines and development frameworks, such as Unreal Engine and Unity, are built using C++. Game developers prefer C++ for its performance and ability to manage system resources efficiently.

  • Embedded Systems : In the field of embedded systems, where resources are often limited, C++ is a popular choice. It allows for close control over hardware and provides a high level of performance.

  • Application Development : C++ is commonly used in the development of desktop applications, especially when performance is a critical factor. Software applications ranging from graphic design tools to office suites often leverage C++.

  • Database Software : C++ is employed in the development of database management systems and software. Its efficiency and low-level capabilities make it suitable for handling large datasets and complex operations.

Advantages and Limitations of C++

Advantages
  • Performance : C++ is known for its high performance, making it suitable for resource-intensive tasks. Its close-to-the-hardware nature allows developers to optimize code for speed.

  • Object-Oriented Approach : The object-oriented features of C++, such as encapsulation and inheritance, contribute to code organization and reusability. This makes it easier to design and maintain large software systems.

  • Control Over Hardware : C++ allows low-level manipulation of hardware, providing developers with fine-grained control. This is crucial for tasks like system programming and embedded systems development.

  • Standard Template Library (STL) : The STL in C++ provides a rich set of pre-built classes and functions, saving development time and effort. It simplifies complex data structures and algorithms.

  • Portability : C++ code can be compiled and executed on different platforms with minimal changes. This portability is essential for software that needs to run across various operating systems.
Limitations
  • Manual Memory Management : While manual memory management provides flexibility, it also introduces the risk of memory leaks and other issues if not handled properly. This aspect requires careful attention from developers.

  • Lack of Garbage Collection : Unlike some modern languages, C++ does not have built-in garbage collection. Developers need to manage memory explicitly, which can lead to memory-related errors if not done correctly.

  • Complexity : C++ can be more complex than some other programming languages due to its extensive features. Novice programmers may find it challenging to learn and master.

  • Less Secure : C++ allows direct manipulation of memory, which can lead to security vulnerabilities if not implemented with care. Buffer overflows and other low-level errors are potential risks.

Object-Oriented Programming Features of C++

  • Classes and Objects : As mentioned earlier, C++ supports the concept of classes and objects, allowing for the encapsulation of data and methods into a single unit. This promotes code organization and reusability.

  • Inheritance : Inheritance is a fundamental OOP concept in C++. It enables the creation of a new class by inheriting properties and behaviors from an existing class. This fosters code reuse and establishes a hierarchical relationship between classes.

  • Encapsulation : Encapsulation involves bundling the data and methods that operate on that data into a single unit, i.e., a class. This feature helps in hiding the internal details of a class and exposing only what is necessary, contributing to code security and maintainability.

  • Polymorphism : Polymorphism in C++ allows objects of different types to be treated as objects of a common base type. This feature includes function overloading and operator overloading, enhancing code flexibility.

  • Abstraction : Abstraction allows the creation of simplified representations of complex systems. In C++, abstraction is achieved through classes and interfaces, enabling developers to focus on essential features while hiding unnecessary details.

  • Polymorphic Class : C++ supports the creation of polymorphic classes, allowing a base class pointer to point to objects of derived classes. This facilitates the implementation of generic algorithms that can work with objects of different types.

Conclusion

In conclusion, C++ is a versatile programming language with a rich set of features that make it suitable for a wide range of applications. Its support for both low-level programming and high-level abstractions, combined with object-oriented programming features, gives developers the tools they need to create efficient and maintainable software. While it has advantages such as high performance and flexibility, developers must be mindful of its complexities and the need for careful memory management. Understanding the features and uses of C++ provides a solid foundation for developers looking to harness the power of this language in their projects.


History of C++ Programming

C++ is a powerful and versatile programming language that has played a significant role in the evolution of software development. Born out of the C programming language, C++ was created to enhance the capabilities of C by introducing object-oriented programming features. In this tutorial, we'll delve into the fascinating history of C++, tracing its origins, key milestones, and the factors that contributed to its widespread adoption.

Program to Print all Pair of Numbers Whose Difference is K

  • Write a program to find a pair of number whose difference is equal to K
  • Algorithm to find a pair of array element whose difference is equal to given number.

Program to Find Next Greater Element for Every Array Element

  • Write a program to find next larger element of array
  • Algorithm to find next greater element using stack data structure and in O(n) time complexity.

Program to Find the Smallest Unsorted Subarray such that Sorting it Makes Whole Array Sorted

  • Write a program in C to find smallest unsorted array such that sorting this array makes whole array sorted.

Program to find Maximum Repeating Element of Array in O(n) Time

  • Write a program to find an element occurring maximum number of times in an array.
  • How to find maximum repeating element of an array in O(n) time and without using any extra memory space.

C Program to Sort an Array Containing 0, 1 and 2.

  • Write a program to sort an array containing only 0, 1 and 2.
  • Dutch flag algorithm to re arrange 0, 1 and 2 such that first all 0's then all 1's and at last all 2's.

C Program to Find Floor of a Number in Sorted Array

  • Write a program to find floor of a number in a sorted array.
  • Algorithm to find the largest number smaller than or equal to X in a sorted integer array.

C Program to Find Ceiling of a Number in Sorted Array

  • Write a program to find ceiling of a number in a sorted array.
  • Algorithm to find the smallest number greater than or equal to X in a sorted integer array.

Program to Find Union and Intersection of Two Sorted Arrays

  • Write a program to find union and intersection of two sorted integer array.
  • Algorithm to find union and intersection of two sorted array.

Program to Find Maximum Difference Between a Pair of Elements

  • Write a program to find maximum difference between elements such that larger element is after smaller element.

Program to Find Largest and Second Largest Element in an Array

  • Write a program to find maximum and second maximum element in an unsorted array.
  • Algorithm to find largest and second largest number in array without sorting it.

Program to Implement Two Stacks in an Array

  • Write a program to implement two stacks using a single array supporting push and pop operations for both stacks.

Program to find SubArray Whose Sum is Equal to Given Number

  • Write a program to find a sub array whose sum is S.

Program to Check One Array is Subset of Another Array

  • Write a program to check whether one array is subset of another array or not.

C Program to Find Four Elements Whose Sum is Equal to S

  • Write a program to find four numbers whose sum is equal to given number.
  • How to find four array elements whose sum id equal to S.

Maximize Profit by Selling and Buying Shares

  • Write a program to maximize the profit by buying and selling stocks.
  • Algorithm to gain maximum profit in share trading.

Program to Find Pythagorean Triplet in an Array

  • Write a program to find Pythagorean triplets in an array.
  • Algorithm to find pythagorean triplets in O(n2) time complexity.

C Program to Print Distinct Elements of Array

  • Write a program to print all distinct elements of an array.
  • How to find all distinct elements of an array in linear time complexity.

Program to Find a Pair Whose Sum is Equal to Given Number

  • Write a program to find pair of numbers in an array whose sum is K
  • Write a function to check whether a pair of numbers exists whose sum is K

Program to Rotate Array Using Block Swap Algorithm

  • Write a program to rotate an array using block swap algorithm.
  • Array rotation Block swap algorithm implementation.

Program to Find Common Elements of Three Sorted Array

  • Write a program to find common elements of three sorted array.
  • Linear time algorithm to find common elements of three sorted array.

Program to Count Number of Possible Triangles using Array Elements

  • Write a program to find the number of possible triangles from any three elements of array.
  • Count number of possible triangles from array elements using sorting.

Find Triplet Whose Sum is Equal to Given Number

  • Write a program to find three elements of given array whose sum is equal to K
  • Algorithm to find a triplet whose sum is equal to given number.

C Program to Move All Zeroes to the End of Array

  • Write a program to separate all zero's from all non-zero element of the array.
  • Algorithm to shift all zero's to the end of input array in linear time O(n) and in constant space O(1).

Program to Rearrange Positive and Negative Number Alternatively

  • Write a program to rearrange alternating positive and negative numbers in O(n) time and O(1) space.
  • Algorithm to rearrange positive and negative numbers alternatively.

C Program to Find a Pair Whose Sum is Closest to Zero

  • Write a program to find a pair whose sum is closest to zero.
  • Algorithm to find a pair of number whose sum is nearest to zero.

Program to find Pivot Element of a Sorted and Rotated Array

  • Write a program in C to find pivot element of a sorted and rotated array using binary search.

Program to Search an Element in a Sorted and Rotated Array

  • Write a program in C to search an element in a sorted array which is also rotated by an unknown position.

Program to Rotate an Array by N Positions

  • Write a program in C to rotate an array by K positions with and without using temporary array.

C Program to Find Missing Number in Array

  • Write a program in C to find missing number using XOR bitwise operator in linear time.

Program to Find Occurrences of a Number in Sorted Array

  • Write a program in C to find the count of a number in a sorted array.
  • Algorithm to find the number of occurrences in a sorted array.

C Program to Check Majority Element in a Sorted Array

  • Write a program in C to check whether a number K is a majority element in a sorted array or not.
  • How to check whether an element appears more than N/2 times in a sorted array of size N.

Reverse Array Elements Using Recursion

  • Write a program to reverse an array using recursion.
  • How to reverse an array using recursive algorithm.

Program to Merge One Sorted Array into Another Sorted Array

  • Write a program to merge to sorted array into one single sorted array.

C Program to Find Majority Element of Array

  • Write a program to find the majority element of an array.
  • C program to find majority element using Moore’s Voting Algorithm.

Find a Row of a Matrix Having Maximum Number of 1

  • Write a program to find a row having maximum number of 1's in a row wise sorted boolean matrix.

Program to Find a Sub Array Whose Sum is Zero

  • Write a program to find a sub array whose sum is equal to 0.

Find Largest Subarray with Equal Number of 0 and 1

  • Write a program to find biggest sub-array having equal number of 0 and 1.

Program to Find a Pair with Given Difference

  • Write a program to find pairs of numbers whose difference is K.

Find the Smallest Missing Positive Number in an Unsorted Array

  • Write a program to find smallest positive missing number in O(n) time and O(1) space.

Program to Find Duplicate Elements in Linear Time and Constant Space

  • Write a program to find duplicate elements of array using linear time algorithm and using constant extra memory.

Program to Separate 0 and 1 in an Array

  • Write a program to segregate 0 and 1 in linear time complexity.
  • How to separate 0 and 1 using Dutch Flag Algorithm.

Program to Find Maximum and Minimum Number of an Array using Tournament Method

  • Write a program to find maximum and minimum element of an array using tournament method.
  • Write a C program to find max and min element using linear search.

Program to Separate Even and Odd numbers of Array

  • Write a program to segregate even and odd numbers in linear time complexity.

Program to Find the Number Occurring Odd Number of Times

  • Write a program to find the an element occurring odd number of times in an array.
  • How to find the only element occurring odd number of times.

Print Nodes of Binary Tree Level Wise

  • Write a C program to perform level order traversal of a binary tree.
  • How to print nodes of a binary tree at same level in one line.

C Program to Find Maximum Width of Binary Tree

  • Write a C program to find the maximum width of a binary tree.

Print all Nodes of Binary Tree at Given Level

  • Write a C program to print all nodes of binary tree at given level.

C Program to Print Level of a Given Node in Binary Tree

  • Write a C program to print level of a node in binary tree.
  • Recursive function in C to find level of a given node in binary tree.

Program to Print Ancestors of a Node in Binary Tree

  • Write a C program to check if there exist a path from root to leaf whose sum is N.

Program to check if a binary tree is subtree of another binary tree

  • Write a C program to check if one binary tree is subtree of another binary tree using recursion.

Program to Check Children Sum Property in a Binary Tree

  • Write a C program to check if a binary tree satisfy Children Sum Property.

C Program to Check Whether a Binary Tree is Height Balanced or Not

  • Write a C program to check if a binary tree is height balanced.

C Program to Check Root to Leaf Path Sum Equal to a Given Number

  • Write a C program to check if there exist a path from root to leaf whose sum is N.

Program to Find Minimum Depth of a Binary Tree

  • Write a C program to find the minimum depth of a binary tree.
  • Write a function to find length of path from root to closest leaf node.

Print all Root to Leaf paths of a Binary Tree

  • Write a C program to print all root node to leaf node path of a given binary tree.

Program to Check Whether a Binary Tree is Sum Tree or Not

  • Write a C program to check if a binary tree is sum tree.

Program to Check Whether a Binary Tree is Complete Tree or Not

  • Write a C++ program to check whether a binary tree is complete tree.

Convert a Binary Tree to its Sum Tree

  • Write a C program to convert a binary tree to sum tree.
  • Write a recursive function in C to build a sum tree

Find Sum of All Left Leaf Nodes of Binary Tree

  • Write a C program to find the sum of all left leaf nodes of a given binary tree.
  • Write a recursive function in C to find all leaf nodes sum.

Print all Nodes of a Binary Tree Less Than N

  • Write a c program to print nodes of binary tree smaller than N

Program to Find Least Common Ancestor in a Binary Tree

  • Write a C program to find the least common Ancestor of two nodes.
  • Algorithm to find least common ancestor (LCA) of two nodes in a binary tree.

Print Level of All nodes in a Binary Tree

  • Write a program in C to print level of all nodes in a binary tree.
  • How to print level of nodes of binary tree using recursion.

Program to Clone a Binary Tree with Random Pointers

  • Write a program in C to clone a Binary tree having random pointer.
  • How to clone a binary tree with random pointer.

Program to Create a Mirror Image of a Binary Tree

  • Write a C program to create a mirror image of a binary tree.
  • How to convert a binary tree to it's mirror image.

C Program to Clone a Binary Tree

  • Write a program in C to Clone a binary tree.
  • Write a recursive function in C to create a duplicate binary tree.

Program to Find Minimum Node of Binary Tree

  • Write a C program to calculate minimum node of a binary tree.
  • Write a recursive function to find minimum value of tree.

Program to Find Maximum Node of Binary Tree

  • Write a program in C to find maximum node of binary tree.
  • Write a recursive function to find maximum element of tree.

Program to Find Diameter of a Binary Tree

  • Write a C program to find diameter of a binary tree.
  • Write a recursive function to calculate diameter of a binary tree.

C Program to Count Leaf Nodes in a Binary Tree

  • Write a program in C to count number of leaf nodes in a given binary tree.
  • Write a function to find number of leaf node using recursion.

C Program to Delete a Binary Tree using Recursion

  • Write a program in C to delete a binary tree using recursion.
  • How to delete all nodes of a binary tree.

Program to Check if Two Trees are Identical

  • Write a program in C to check if Two Trees are same.
  • How to compare two binary trees for equality.

Program to Find Maximum Depth or Height of a Binary Tree

  • Write a C program to find maximum depth of a binary tree.
  • Function to print height of a binary tree.

Program to Calculate Size of a Binary Tree

  • Write a C program to find the total number of nodes in a binary tree.
  • Function to print size of a binary tree.

Program to Find the Largest Element in a Doubly Linked List

  • Write a C program to find maximum element of a doubly linked list.
  • Function to print largest element of a doubly linked list.

C Program to Find Cycle in a Linked List

  • Write a C program to detect a loop in a linked list.
  • How to check whether a linked list contains a cycle.

Find Union and Intersection of Two Linked List

  • Write a C program to find union and intersection of two linked list.
  • Algorithm to find intersection and union of two singly linked list.

Program to Search an Element in Linked List using Loop and Recursion

  • Write a C program to search an element in a linked list using loop.
  • How to find an element in linked list using recursion.

Convert a Singly Linked List to Circular Linked List

  • Write a C program to convert a singly linked list to a circular linked list.
  • How to make a circular linked list from singly linked list.

C Program to Find Middle Node of a Linked List

  • Write a C program to print alternate nodes of given linked list.
  • Function to print alternate nodes of a linked list.

Program to Find Nth Node from the End of a Linked List

  • Write a C program to print Nth node from end of linked list.
  • Find Nth last node of linked list.

Program to Print Alternate Nodes of Linked List

  • Write a C program to print alternate nodes of given linked list.
  • Function to print alternate nodes of a linked list.

Program to Check if a Singly Linked List is Palindrome

  • C program to check whether a linked list is palindrome or not by reversing linked list.
  • Write a function to check palindrome linked list.

Program to Delete a Linked list

  • Write a C program to delete a singly linked list.
  • Write function in C to delete all nodes of a linked list.

Print a Linked List in Reverse Order using Recursion

  • Write a C program to read a linked list in reverse direction using recursion.

Merge Two Sorted Linked List

  • Write a C program to merge two sorted linked list into one linked list.

Program to Reverse a Linked List using Loop and Recursion

  • Write a C program to reverse a linked list using loop and recursion.

Delete a Node from a Singly Linked List

  • Write a C program to delete a node from a Singly linked list

Find Length of a Linked List (using Loop and Recursion)

  • Write a C program to find length of linked list using loop.
  • C program to count the number of nodes in a linked list using recursion.

Inserting a node after a given node in linked List

  • Write a C program to add a node after a given node in linked list.

Inserting a node at front and end of linked List

  • Write a C program to insert a node at front of singly linked list.
  • Write a C program to insert a node at the end of linked list.

C program to Check for balanced Parentheses in an Expression using Stack

  • Write a program in C to Check if Expression is correctly Parenthesized.

C Program to Check String is Palindrome using Stack

  • Write a program in C to check whether a String is Palindrome or not using Stack data structure.

C Program to Implement a Queue using Linked List

  • Write a program in C to implement a queue data structure using linked list.

C Program to Reverse a Stack using Recursion

  • Write a program in C to reverse a stack using recursion.

Data Structure Programs


Data Structures Programs in C

ARRAY C Program to read and print elements of an array C Program to find sum of all elements of an array C Program to find maximum elements in an array C program to insert an element in an array C program to delete an element from an array C program to delete duplicate elements from an array C Program to print unique elements of an unsorted array C program to find maximum and minimum element of an array C Program to create a duplicate array C program to find number of duplicate elements in an array C Program to find count of each element of an array C Program to sort elements of an array in increasing order Program to Find the Number Occurring Odd Number of Times Program to Separate Even and Odd numbers of Array Program to Find Maximum and Minimum Number of an Array using Tournament Method Program to Separate 0 and 1 in an Array Find Largest Subarray with Equal Number of 0 and 1 Program to Find a Pair with Given Difference Find the Smallest Missing Positive Number in an Unsorted Array Program to Find Duplicate Elements in Linear Time and Constant Space Find a Row of a Matrix Having Maximum Number of 1 Program to Find a Sub Array Whose Sum is Zero C Program to Find Majority Element of Array Program to Merge One Sorted Array into Another Sorted Array Reverse Array Elements Using Recursion C Program to Check Majority Element in a Sorted Array Program to Find Occurrences of a Number in Sorted Array C Program to Find Missing Number in Array Program to Rotate an Array by N Positions Program to Search an Element in a Sorted and Rotated Array Program to find Pivot Element of a Sorted and Rotated Array C Program to Find a Pair Whose Sum is Closest to Zero Program to Rearrange Positive and Negative Number Alternatively C Program to Move All Zeroes to the End of Array Find Triplet Whose Sum is Equal to Given Number Program to Count Number of Possible Triangles using Array Elements Program to Maximize Profit by Selling and Buying Shares Program to Rotate Array Using Block Swap Algorithm Program to Find a Pair Whose Sum is Equal to Given Number C Program to Print Distinct Elements of Array Program to Find Pythagorean Triplet in an Array Program to Find Common Elements of Three Sorted Array C Program to Find Four Elements Whose Sum is Equal to S Program to Check One Array is Subset of Another Array Program to find SubArray Whose Sum is Equal to Given Number Program to Implement Two Stacks in an Array Program to Find Largest and Second Largest Element in an Array Program to Find Maximum Difference Between a Pair of Elements Program to Find Union and Intersection of Two Sorted Arrays C Program to Find Ceiling of a Number in Sorted Array C Program to Find Floor of a Number in Sorted Array C Program to Sort an Array Containing 0, 1 and 2. Program to find Maximum Repeating Element of Array in O(n) Time.

C Program to Divide a String into Two Equal Strings

Here is a C program to divide a string in two equal sub strings. Given a string of length L, we have to split this string into two equal sub-strings.

  • If L is even, then length of the sub-strings will be L/2 and L/2.
  • If L is off, the length of sub-strings will be L/2 and (L/2)+1
For Example:
Input : "Internet" Output : "Inte" and "rnet"
Algorithm for split a string in two equal sub strings.
Let inputString be the string entered by user and leftHalf and rightHalf are two output sub-strings.
  1. Find length of the string using strlen function. Let it be L.
  2. Find the mid index of input string. (mid = L/2)
  3. Copy characters of inputString from index 0 to mid to leftHalf.
  4. Copy characters of inputString from index mid+1 to L-1 to rightHalf.

C program to split a string into two equal strings

In this program, we will first read a string as input from user using gets function. Then we find the length of input string(L) using strlen function of string.h header file. Now, we will create two sub-strings as explained above and print it on screen.

#include<stdio.h>
#include<string.h>

int main() {

    char inputString[100], leftHalf[100], rightHalf[100];
    int length, mid, i, k;
 
    printf("Enter a string\n");
    gets(inputString);

    length = strlen(inputString);
 
    mid = length/2;
    
    for(i = 0; i < mid; i++) {
        leftHalf[i]= inputString[i];
    }
    leftHalf[i] = '\0';
 
    for(i = mid, k = 0; i <= length; i++, k++) {
        rightHalf[k]= inputString[i];
    }
 
    printf("Left half : %s\n",leftHalf);
    printf("Right half : %s\n",rightHalf);

    return 0;
}
Output
Enter a string
TECHCRASHCOURSE
Left half : TECHCRA
Right half : SHCOURSE

Related Topics
C program to check if two strings are anagram
C program to remove extra spaces from string
C Program to find frequency of characters in a string
C program to sort characters of a string
C program to concatenate strings
C program to convert lowercase string to uppercase
C program to reverse a string
C program to swap two strings
C program to convert string to integer
List of all C programs

Java Program to Print Multiplication Table Triangle Pattern

Here is a java program to print a multiplication table triangle pattern.

Java program to Print Square Pattern of Star Character

Here is a Java program to print square pattern of '*' character.

Java Program to Print Diamond Pattern of Star Character

Here is a java program to print a diamond pattern of start character using loop.

Java Program to Print Right Triangle Pattern of Natural Numbers

Here is a java program to print a right triangle pattern of natural numbers using for loops.

Java Program to Print Inverted Pyramid Pattern of Stars

Here is a java program to print up-side down pyramid pattern of stars. In Reverse pyramid star pattern of N rows, ith row contains (i-1) space characters followed by (2*i - 1) star(*) characters. Check below mentioned inverted pyramid pattern of 4 rows.

Java Program to Print Pyramid Pattern of Stars

Here is a java program to print a pyramid pattern of star(*) character. In Pyramid star pattern, ith row contains (i-1) space characters followed by (2*i - 1) star(*) characters. Check below mentioned pyramid pattern of 5 rows.

Java Program to Print Inverted Right Triangle Star Pattern

Here is a Java program to print inverted(upside down)right angled triangle star pattern. An Inverted Right triangle star pattern of N rows contains (N-i+1) space separated '*' characters in ith row. Number of star characters in a row keeps on decreasing as as row number increases. In this program, we will use two for loops, outer for loop will print one row in every iteration whereas inner for loop will print (N-i+1) '*' characters for ith row.

Java Program to Print Right Triangle Star Pattern

Here is a Java program to print right angled triangle star pattern. A Right triangle star pattern contains N space separated '*' characters in Nth row. In this program, we will use two for loops, outer for loop will print one row in every iteration whereas inner for loop will print N '*' characters for Nt row.

Java Program to Check If a Year is Leap Year or Not

Here is a Java program to check whether a year is leap year or not. A leap year contains 366 days instead of the usual 365, by extending February to 29 days rather than the common 28 days. A leap year is a year containing one additional day in order to keep the calendar year in sync with the astronomical year.

It takes the Earth approximately 365.242189 days – or 365 days, 5 hours, 48 minutes, and 45 seconds – to circle once around the Sun. However, the Gregorian calendar has only 365 days in a year, so if we didn't add a leap day on February 29 nearly every four years, we would lose almost six hours off our calendar every year.

Java Program to Find Sum of all Odd Numbers between 0 to N

Here is a java program to find the sum of all odd numbers between 0 to N using loop.

Java Program to Check Whether a Number is Palindrome or Not

Here is a java program to check whether a number is palindrome or not using loop. An integer is called palindrome number, If the number remains same after reversing the sequence of it's digits. To check whether a number is palindrome number or not, we will create a copy of input number and reverse it's digits. If reversed number is same as input number then it is a palindrome number other not a palindrome number.

Java Program to Print Fibonacci Series with and without using Recursion

Here is a Java program to print Fibonacci series with recursion and without recursion. Fibonacci series is a series of integers, where Nth term is equal to the sum of N-1th and N-2th(last two terms). The first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent term is the sum of the previous two terms.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 ....

Java Program to Find Average of all Array Elements

Here is a java program to find average of all array elements. Given an array of integers of size N, we have to find the average of all array elements.

Java Program to Swap Two Numbers Without Using Third Variable

Given two numbers, we have to swap the value of two numbers. Let A and B be the two input numbers, we have to interchange their values as follows:

Java Program to Find Factorial of a Number Using Recursion

Here is a Java program to find factorial of a number using recursion. We have to write a recursive function in Java to calculate factorial of a number. he factorial of a integer N, denoted by N! is the product of all positive integers less than or equal to n.

Java Program to Find Factorial of a Number using For Loop

Here is a Java program to find factorial of a number using for loop. Given a positive integer N, we have to calculate factorial of N using for loop.

Java Program to Find Largest and Smallest Number in an Array

Here is a Java program to find the maximum and minimum element in an array. Given an integer array of size N, we have to find the maximum and minimum element of input array.

Java Program to Find Area and Perimeter of Rectangle

Here is a java program to take length and breadth of a rectangle as input from user and calculate area and perimeter of rectangle. To calculate the perimeter and area of rectangle, we need the dimensions of two adjacent sides(length and width) of a rectangle. The area of a rectangle is the amount of two-dimensional space inside the boundary on rectangle. The perimeter of a rectangle is the linear distance around the boundary of the rectangle.

Java Program to Convert Binary Number to Decimal Number

Here is a Java program to convert binary number to decimal number using Integer.parseInt method.

We have to convert a binary number( base 2) to decimal number (base 10). Binary number system is a base 2 number system using digits 0 and 1 whereas Decimal number system is base 10 and using digits from 0 to 9. Given a binary number as input from user convert it to decimal number.

Java Program to Find Duplicate Elements in an Array

Here is a java program to find duplicate elements in an integer array. Given an array of integers(which may contains duplicate elements), we have to print all duplicate elements of array once. To find duplicate elements, we will count the frequency of each elements of array and store it in a Map. If frequency of any element is id more than 1, then it is a duplicate element otherwise it is a unique element.

Java Program to Generate a Sequence of Random Numbers

Here is a Java program to implement a random number generator. This program takes "N"(number of random numbers to generates) and "maxRange" (maximum limit of random numbers) as input from user and then generates a sequence of N random numbers between 1 to maxRange. It uses java.util.Random class to generate a set of random numbers.