C Language
Programming is the process of giving instructions to a computer to perform specific tasks. It involves writing code in a programming language that the computer can understand and execute. The basic concepts include variables (for storing data), data types (like numbers and strings), control structures (such as loops and conditional statements), functions (reusable blocks of code), and algorithms (step-by-step instructions for solving problems). Different programming languages offer various syntax and features, but these fundamental concepts are common across most languages.
A compiler is a software tool that translates high-level programming code written by humans into machine code or executable code that a computer can directly understand and execute. It goes through multiple stages, including lexical analysis, syntax analysis, semantic analysis, optimization, and code generation. The end result is a compiled program that can be run on a specific computer architecture without requiring the original human-readable source code.
An interpreter is a software program that reads and executes high-level programming code line by line, translating it into machine code and immediately executing each line. Unlike a compiler, which generates a complete executable file before running it, an interpreter processes code in a more interactive and iterative manner. This allows for quicker feedback and debugging, as errors are often identified as soon as the interpreter encounters them. However, interpreted code generally tends to be slower in execution compared to compiled code due to the on-the-fly translation process.
A linker is a software tool that combines multiple object files generated by a compiler into a single executable program or library. It resolves references between different parts of the code, such as function calls and variable references, ensuring that everything is connected correctly. The linker also handles tasks like allocating memory addresses for variables and functions, and it may perform optimizations to improve the final executable's efficiency. In essence, the linker is responsible for creating a coherent and executable program by merging various code modules and resolving dependencies.
A loader is a program that loads an executable program from storage (such as a hard drive) into a computer's memory, allowing it to be executed. It's an essential component of the process that turns compiled code into a running application. The loader takes care of tasks like allocating memory space for the program, resolving references to external libraries or resources, and setting up the environment for the program to run. Once the loading process is complete, control is transferred to the starting point of the program, and it begins executing.
An algorithm is a step-by-step set of instructions designed to solve a specific problem or accomplish a particular task. Here's a breakdown of understanding algorithms from a beginner to an expert level:
**Beginner:**
1. **Problem Statement:** Clearly define the problem you want to solve.
2. **Input and Output:** Identify what data the algorithm will take as input and what it should produce as output.
3. **Pseudocode:** Write a high-level description of the steps you plan to take in plain language. Focus on the logic rather than the syntax of a programming language.
4. **Flowchart:** Create a visual representation of your algorithm using symbols and arrows to show the flow of steps.
**Intermediate:**
1. **Data Structures:** Learn about various data structures (arrays, linked lists, stacks, queues, trees, graphs) to organize and store data efficiently.
2. **Control Structures:** Understand control flow mechanisms like loops (for, while) and conditional statements (if, else) to control the execution path of your algorithm.
3. **Time and Space Complexity:** Analyze the efficiency of your algorithm in terms of how much time and memory it requires as the input size grows. Learn Big O notation to express complexity.
4. **Divide and Conquer:** Explore strategies like breaking down a problem into smaller sub-problems and solving them recursively.
**Advanced:**
1. **Sorting and Searching:** Study various sorting (merge sort, quicksort) and searching (binary search) algorithms and their trade-offs.
2. **Dynamic Programming:** Master the technique of solving complex problems by breaking them down into overlapping sub-problems.
3. **Greedy Algorithms:** Learn how to make locally optimal choices to achieve a globally optimal solution.
4. **Graph Algorithms:** Dive into algorithms like Dijkstra's, Bellman-Ford, and Floyd-Warshall for solving problems involving graphs.
5. **Complex Data Structures:** Explore advanced data structures like heaps, hash tables, and self-balancing trees.
6. **Algorithm Design Patterns:** Study common algorithmic patterns, like backtracking, breadth-first search, depth-first search, and divide-and-conquer.
**Expert:**
1. **Advanced Topics:** Delve into more complex subjects such as network flow algorithms, computational geometry, and quantum algorithms.
2. **Parallel and Concurrent Algorithms:** Understand how algorithms can be designed to take advantage of parallel processing and multi-core systems.
3. **Approximation Algorithms:** Learn about algorithms that provide near-optimal solutions for NP-hard problems.
4. **Machine Learning Algorithms:** Explore algorithms used in machine learning, such as clustering, regression, and neural networks.
5. **Algorithm Analysis and Optimization:** Develop skills to deeply analyze algorithms, optimize code for performance, and explore cache-friendly techniques.
Remember, becoming an expert in algorithms requires continuous learning, practice, and exposure to a wide range of problem-solving scenarios. It's a journey that involves both theoretical understanding and practical application.
A flowchart is a visual representation of a process or algorithm using various symbols to illustrate the sequence of steps and decision points. Here's a step-by-step guide to creating and understanding flowcharts:
**Step 1: Define the Problem or Process:**
Clearly understand the problem you want to represent or the process you want to visualize using the flowchart.
**Step 2: Identify Symbols:**
Flowcharts use different symbols to represent different types of actions and decisions. Common symbols include:
- **Start/End Symbol:** Represents the start or end of the process.
- **Process Symbol:** Represents a specific action or step.
- **Decision Symbol:** Represents a branching point where a decision is made based on a condition.
- **Input/Output Symbol:** Represents input or output actions.
**Step 3: Arrange Symbols:**
Arrange the symbols in a logical sequence to represent the flow of the process. Start with the "Start" symbol and end with the "End" symbol.
**Step 4: Connect Symbols with Arrows:**
Use arrows to connect the symbols and show the direction of flow. Arrows indicate the sequence of steps, decision outcomes, and loops.
**Step 5: Define Processes:**
Add process symbols to represent the actual actions or steps involved in the process. Label each process with a brief description of the action.
**Step 6: Add Decision Points:**
Use decision symbols to represent points where a choice or condition is evaluated. Label the decision with a question that describes the condition being checked.
**Step 7: Define Paths:**
For each decision point, draw arrows representing the different paths the process could take based on the outcome of the decision.
**Step 8: Include Input/Output:**
Add input and output symbols to indicate where data enters the process or results are produced. Label these symbols with a description of the data being input or output.
**Step 9: Test and Validate:**
Review the flowchart to ensure that it accurately represents the process or algorithm. Walk through each step to verify that it makes sense and accurately captures the logic.
**Step 10: Simplify and Optimize:**
Simplify the flowchart by eliminating unnecessary steps or symbols. Look for ways to optimize the sequence of actions and decision points.
**Step 11: Revise as Needed:**
Flowcharts are iterative; you might need to revise and refine your flowchart as you gain a deeper understanding of the problem or process.
**Step 12: Document the Flowchart:**
If necessary, provide explanations or annotations for symbols or steps that might be unclear. This documentation can help others understand your flowchart.
**Step 13: Use Proper Notation:**
Follow conventions and standards for flowchart notation to ensure that your flowchart is easily understandable by others who may view it.
Remember, the purpose of a flowchart is to provide a clear and visual representation of a process or algorithm, making it easier to communicate and understand complex sequences of actions and decisions.
Testing and execution are crucial aspects of programming that help ensure the quality and reliability of software applications. These processes involve various techniques and practices to identify and fix errors, validate functionality, and improve overall software performance. Let's delve into both testing and execution in programming: 1. Testing: Software testing is the process of evaluating a software application to identify discrepancies between expected and actual outcomes. It aims to identify defects, bugs, or issues in the software to ensure its correctness, reliability, and performance. There are several levels and types of testing: - Unit Testing: This is the process of testing individual components or units of code in isolation. It verifies that each unit works as expected and can be a building block for more complex functionalities. - Integration Testing: Integration testing focuses on testing the interactions between different units or modules. It ensures that the combined components work together as intended. - Functional Testing: Functional testing involves testing the application's functionality against its specifications. It ensures that the software meets the requirements and performs the intended tasks accurately. - Regression Testing: Regression testing is performed to ensure that new code changes or updates do not negatively impact existing functionalities. It involves re-testing the application after modifications. - Performance Testing: Performance testing evaluates the software's responsiveness, scalability, and stability under different loads and conditions. It includes tests like load testing, stress testing, and scalability testing. - Security Testing: Security testing focuses on identifying vulnerabilities and potential security breaches in the software. It ensures that sensitive data is protected and the application is resistant to attacks. - User Acceptance Testing (UAT): UAT involves testing the software from the perspective of the end users. It ensures that the software meets user expectations and is ready for deployment. 2. Execution: Execution refers to the process of running the software application to perform its intended tasks. It involves translating the high-level source code into machine-executable code that the computer's hardware can understand and execute. The execution process involves several steps: - Compilation: In languages like C, C++, and Java, the source code is compiled into intermediate code or machine code using a compiler. This intermediate code is then executed by the computer. - Interpretation: In languages like Python, the source code is interpreted line by line by the interpreter. Each line is executed as it's encountered, which allows for more dynamic and flexible programming. - Execution Environment: The execution environment includes the operating system, hardware, libraries, and other resources required to run the software. Ensuring compatibility with the execution environment is important for the software to function correctly. In summary, testing ensures the software's quality and functionality by identifying and fixing issues, while execution involves running the software to perform its tasks. Both processes are integral to the software development lifecycle and contribute to delivering reliable and effective software applications.
Examples of flowcharts and algorithms. Please note that creating flowcharts in text format might not be very accurate due to the visual nature of flowcharts. However, I'll do my best to describe them in a way that you can understand. Let's start with some simple examples: Example 1: Finding the Sum of Two Numbers Algorithm: 1. Start 2. Input num1 3. Input num2 4. sum = num1 + num2 5. Display sum 6. Stop Flowchart: +-----------+ | Start | +-----+-----+ | v +-----+-----+ | Input num1 | +-----+-----+ | v +-----+-----+ | Input num2 | +-----+-----+ | v +-----+-----+ | sum = num1 + num2 | +-----+-----+ | v +-----+-----+ | Display sum | +-----+-----+ | v +-----------+ | Stop | +-----------+ Example 2: Finding the Factorial of a Number Algorithm: 1. Start 2. Input num 3. fact = 1 4. for i from 1 to num: - fact = fact * i 5. Display fact 6. Stop Flowchart: +-----------+ | Start | +-----+-----+ | v +-----+-----+ | Input num | +-----+-----+ | v +-----+-----+ | fact = 1 | +-----+-----+ | v +-----+-----+ | for i from 1 to num | +-----+-----+ | v +-----+-----+ | fact = fact * i | +-----+-----+ | v +-----+-----+ | Display fact | +-----+-----+ | v +-----------+ | Stop | +-----------+ Example 3: Linear Search in an Array Algorithm: 1. Start 2. Input arr, key 3. Initialize index = -1 4. for i from 0 to length of arr: - if arr[i] equals key: - index = i - break 5. Display index 6. Stop Flowchart: +-----------+ | Start | +-----+-----+ | v +-----+-----+ | Input arr, key | +-----+-----+ | v +-----+-----+ | index = -1 | +-----+-----+ | v +-----+-----+ | for i from 0 to length of arr | +-----+-----+ | v +-----+-----+ | if arr[i] equals key | +-----+-----+ | v +-----+-----+ | index = i | +-----+-----+ | v +-----+-----+ | break | +-----+-----+ | v +-----+-----+ | Display index | +-----+-----+ | v +-----------+ | Stop | +-----------+ Please remember that these are simplified textual representations of flowcharts and algorithms. In practice, you would use appropriate tools or programming languages to create and execute these algorithms. The examples provided here should give you a basic understanding of how flowcharts and algorithms work.
Programming tokens, also known as lexical tokens or simply tokens, are the smallest units of a programming language. They are fundamental building blocks that make up the source code of a program. In essence, a programming token represents a meaningful element of the language, such as keywords, identifiers, operators, constants, and punctuation. Tokens play a crucial role in the process of translating human-readable source code into machine-executable instructions. Here are some common types of programming tokens: 1. Keywords: Keywords are reserved words that have predefined meanings in the programming language. They often represent control structures, data types, or other language-specific functionalities. Examples include `if`, `else`, `while`, `int`, `float`, and `return`. 2. Identifiers: Identifiers are user-defined names given to variables, functions, classes, or other program entities. They consist of letters, digits, and underscores, and typically start with a letter or underscore. Examples of identifiers are `count`, `totalAmount`, and `calculateAverage`. 3. Literals: Literals are constant values that are used directly in the code without any computation. They can be of various types, such as integer literals (`42`, `-10`), floating-point literals (`3.14`, `-0.5`), string literals (`"Hello, world!"`), and boolean literals (`true`, `false`). 4. Operators: Operators are symbols that represent operations to be performed on operands. They can be arithmetic operators (`+`, `-`, `*`, `/`), comparison operators (`==`, `<`, `>`), logical operators (`&&`, `||`, `!`), and assignment operators (`=`). 5. Punctuation: Punctuation symbols are used to structure and separate code. Examples include semicolons (`;`), commas (`,`), parentheses (`(` and `)`), braces (`{` and `}`), and brackets (`[` and `]`). 6. Comments: Comments are text that are ignored by the compiler or interpreter and are used to provide explanations or notes within the code. They help programmers and others understand the code's purpose and functionality. 7. Whitespace: Whitespace characters (spaces, tabs, line breaks) are used to separate tokens and improve code readability. They are generally ignored by the compiler or interpreter. Here's an example of a simple code snippet broken down into tokens: Tokens: - Identifier: `x` - Operator: `=` - Literal (integer): `5` - Operator: `+` - Literal (integer): `3` - Keyword: `if` - Identifier: `x` - Operator: `>` - Literal (integer): `7` - Punctuation: `:` - Identifier: `print` - Punctuation: `(` - Literal (string): `"x is greater than 7"` - Punctuation: `)` Each of these tokens contributes to the code's structure and functionality. Understanding programming tokens is essential for reading and writing code in any programming language.
Certainly! Here is a list of keywords in the C programming language, along with explanations of their meanings and uses: 1. auto: - Explanation: The `auto` keyword is used for automatic storage class. It's the default storage class for local variables inside a function block. - Example: `auto int num = 10;` 2. break: - Explanation: The `break` keyword is used to terminate the execution of the nearest enclosing loop or switch statement. - Example: ```c while (condition) { if (some_condition) { break; } } ``` 3. case: - Explanation: The `case` keyword is used in a `switch` statement to label a particular value or condition. - Example: ```c switch (value) { case 1: // Code for case 1 break; case 2: // Code for case 2 break; } ``` 4. char: - Explanation: The `char` keyword is used to define a character data type. It can store a single character. - Example: `char ch = 'A';` 5. const: - Explanation: The `const` keyword is used to declare a constant variable whose value cannot be changed after initialization. - Example: `const int PI = 3.14159;` 6. continue: - Explanation: The `continue` keyword is used to skip the current iteration of a loop and continue with the next iteration. - Example: ```c for (int i = 0; i < 10; i++) { if (i == 5) { continue; } } ``` 7. default: - Explanation: The `default` keyword is used in a `switch` statement to provide a default case when none of the other cases match. - Example: ```c switch (value) { case 1: // Code for case 1 break; default: // Code for default case } ``` 8. do: - Explanation: The `do` keyword is used to start a `do-while` loop, which executes the loop body at least once before checking the loop condition. - Example: ```c do { // Loop body } while (condition); ``` 9. double: - Explanation: The `double` keyword is used to define a floating-point data type that can store double-precision floating-point numbers. - Example: `double value = 3.14;` 10. else: - Explanation: The `else` keyword is used to specify an alternative block of code to execute when the condition of an `if` statement is false. - Example: ```c if (condition) { // Code for true condition } else { // Code for false condition } ``` 11. enum: - Explanation: The `enum` keyword is used to define an enumeration data type, which is a set of named integer constants. - Example: ```c enum Days { Sunday, Monday, Tuesday, // ... }; ``` 12. extern: - Explanation: The `extern` keyword is used to declare a global variable that is defined in another source file. - Example: `extern int globalVar;` 13. float: - Explanation: The `float` keyword is used to define a floating-point data type that can store single-precision floating-point numbers. - Example: `float value = 3.14;` 14. for: - Explanation: The `for` keyword is used to start a `for` loop, which repeatedly executes a block of code based on a specified condition. - Example: ```c for (int i = 0; i < 10; i++) { // Loop body } ``` 15. goto: - Explanation: The `goto` keyword is used to transfer control to a labeled statement within the same function. - Example: ```c if (condition) { goto error_handling; } // ... error_handling: // Handle the error ``` 16. if: - Explanation: The `if` keyword is used to start an `if` statement, which conditionally executes a block of code based on a specified condition. - Example: ```c if (condition) { // Code to execute if the condition is true } ``` 17. int: - Explanation: The `int` keyword is used to define an integer data type that can store whole numbers. - Example: `int num = 42;` 18. long: - Explanation: The `long` keyword is used to define a data type that can store larger integer values than the `int` data type. - Example: `long bigNum = 1234567890L;` 19. register: - Explanation: The `register` keyword is used to suggest that a variable should be stored in a processor register for faster access. - Example: `register int counter;` 20. return: - Explanation: The `return` keyword is used to exit a function and return a value to the calling code. - Example: ```c int add(int a, int b) { return a + b; } ``` 21. short: - Explanation: The `short` keyword is used to define a data type that can store smaller integer values than the `int` data type. - Example: `short smallNum = 10;` 22. signed: - Explanation: The `signed` keyword is used to indicate that a data type can store both positive and negative values. - Example: `signed int temperature;` 23. sizeof: - Explanation: The `sizeof` keyword is used to determine the size (in bytes) of a data type or variable. - Example: ```c int size = sizeof(int); ``` 24. static: - Explanation: The `static` keyword is used to declare a static variable, which retains its value between function calls. - Example: `static int counter = 0;` 25. struct: - Explanation: The `struct` keyword is used to define a user-defined composite data type that groups together variables of different data types. - Example: ```c struct Point { int x; int y; }; ``` 26. switch: - Explanation: The `switch` keyword is used to start a `switch` statement, which allows you to select among multiple code paths based on a value. - Example: ```c switch (value) { case 1: // Code for case 1 break; case 2: // Code for case 2 break; default
In C programming, an identifier is a name given to a program element such as a variable, function, array, or other user-defined entity. Identifiers are used to provide a unique name to these elements, making it easier for programmers to read and understand the code. Here are the rules and conventions for defining identifiers in C: 1. Naming Rules: - An identifier can consist of letters (both uppercase and lowercase), digits, and underscores (`_`). - The first character of an identifier must be a letter or an underscore. - C is case-sensitive, meaning `myVar` and `myvar` are treated as two different identifiers. - Identifiers should not be C keywords. 2. Good Practices: - Choose descriptive and meaningful names for identifiers to improve code readability. - Use lowercase letters for variable and function names, and uppercase letters for constants (conventionally). - Separate words within an identifier using underscores (snake_case) or capitalization (camelCase). Here are some examples of valid identifiers: c int age; double temperature; char firstName; float average_score; const int MAX_COUNT = 10; void process_data(); And here are some examples of invalid identifiers: c int 2var; // Starts with a digit double my-var; // Contains a hyphen (not allowed) char first name; // Contains a space (not allowed) float while; // Uses a C keyword (while is a keyword) It's important to follow these rules to ensure that your code is both readable and free of errors. Choosing meaningful and well-formatted identifiers contributes to the overall quality of your code and makes it easier for you and others to understand and maintain.
In C programming, constants are values that do not change during the execution of a program. They are used to represent fixed values that remain constant throughout the code. Constants provide a way to improve code readability and maintainability by avoiding hardcoding values directly into the code. There are different types of constants in C: 1. Integer Constants: Integer constants are whole numbers without decimal points. They can be represented in decimal, octal (base 8), or hexadecimal (base 16) formats. c int decimal = 42; // Decimal representation int octal = 052; // Octal representation (42 in decimal) int hex = 0x2A; // Hexadecimal representation (42 in decimal) 2. Floating-Point Constants: Floating-point constants are used to represent real numbers with decimal points. They include the fractional part and can be written in standard or exponential notation. c float standard = 3.14; float exponential = 1.23e-5; // 0.0000123 3. Character Constants: Character constants represent single characters enclosed within single quotes. They are usually of type `char`. c char ch = 'A'; char newline = '\n'; // Represents a newline character 4. String Constants: String constants are sequences of characters enclosed within double quotes. They are used to represent text or strings. c char message[] = "Hello, World!"; 5. Symbolic Constants (Macros): Symbolic constants are defined using the `#define` preprocessor directive. They are replaced with their respective values before the code is compiled. c #define PI 3.14159 #define MAX_LENGTH 100 6. Enumeration Constants: Enumeration constants are used in enums to define named values. Enumerations provide a way to create user-defined data types with a set of symbolic constant values. c enum Days { Sunday, Monday, Tuesday, // ... }; 7. Literal Constants: Literal constants are constants with specific values, not represented by variables or expressions. They can be integer, floating-point, character, or string literals. c 42 // Integer literal 3.14f // Floating-point literal 'A' // Character literal "Hello" // String literal Using constants instead of hardcoding values directly in your code makes it more maintainable and allows for easier modifications when values need to be changed. It also enhances code readability by providing meaningful names for fixed values.
Variables in C: In C programming, a variable is a named storage location that holds a value. Variables are used to store data that can be manipulated and used within a program. They play a crucial role in storing information for calculations, comparisons, and other operations. Here's a detailed overview of variables in C: 1. Declaration and Initialization: - Declaration: To create a variable, you need to declare it by specifying its data type and name. For example: c int age; float temperature; char firstInitial; - Initialization: You can also assign an initial value to a variable at the time of declaration. This is called initialization: c int num = 42; float pi = 3.14159; char grade = 'A'; 2. Variable Naming Rules and Conventions: - Variable names can consist of letters (both uppercase and lowercase), digits, and underscores (`_`). - The first character of a variable name must be a letter or an underscore. - C is case-sensitive, so `myVar` and `myvar` are considered different variables. - Variable names cannot be C keywords. - Descriptive and meaningful names are recommended for better code readability. - Variable names should not start with an underscore followed by an uppercase letter, as these are often used for system-level identifiers. 3. Data Types: - Variables have a specific data type, which determines the kind of data they can hold (e.g., integers, floating-point numbers, characters). - Examples of data types include `int`, `float`, `char`, `double`, etc. 4. Scope and Lifetime: - Scope: The scope of a variable refers to the part of the code where the variable is accessible. Variables declared inside a function have local scope and are accessible only within that function. Variables declared outside functions have global scope and can be accessed throughout the program. - Lifetime: The lifetime of a variable is the duration it exists in memory. Local variables are created when a function is called and destroyed when the function exits. Global variables exist throughout the program's execution. 5. Constants and Mutable Variables: - C provides two types of variables: mutable variables and constants. Mutable variables can have their values changed during the program's execution, while constants have fixed values that cannot be changed. 6. Example: c #includeint main() { int age; // Declaration age = 25; // Initialization float temperature = 98.6; // Declaration and Initialization char grade = 'B'; // Declaration and Initialization printf("Age: %d\n", age); printf("Temperature: %f\n", temperature); printf("Grade: %c\n", grade); return 0; } In this example, we declare and initialize variables of different data types. Then, we use `printf` to display their values. Using variables in your C programs allows you to work with data and perform operations dynamically. Proper naming, scoping, and type selection contribute to writing effective and maintainable code.
Data types in C: In C programming, data types define the kind of data that a variable can hold. They specify the size and format of the data that the variable can store. Understanding data types is essential for writing efficient and correct programs. Here's a detailed overview of various data types in C, along with examples: 1. Basic Data Types: C provides a set of basic data types that represent integer and floating-point numbers, characters, and boolean values (true or false). - int: Represents integers, which are whole numbers without decimal points. c int num = 42; - float: Represents single-precision floating-point numbers with decimal points. c float pi = 3.14159; - double: Represents double-precision floating-point numbers with higher precision than `float`. c double big_pi = 3.14159265358979323846; - char: Represents a single character from the ASCII character set. c char letter = 'A'; - _Bool: Represents boolean values (true or false). c _Bool is_true = 1; // true _Bool is_false = 0; // false 2. Modifier Keywords: C also provides modifier keywords that can be used with basic data types to modify their properties. - short: Represents integers with smaller range compared to `int`. c short small_num = 10; - long: Represents integers with a larger range than `int`. c long big_num = 1234567890L; // Note: 'L' indicates a long constant - unsigned: Represents only positive integers or zero. c unsigned int positive_num = 100; - signed: Represents both positive and negative integers (default for `int`). c signed int temperature = -5; 3. Derived Data Types: Derived data types are created by combining basic data types in various ways. - Arrays: A collection of elements of the same data type. c int scores[5] = {90, 85, 78, 92, 88}; - Pointers: Stores memory addresses of variables. c int num = 42; int *ptr = # // Pointer to an integer - Structures: A composite data type that groups together variables of different types. c struct Person { char name[50]; int age; }; - Unions: Similar to structures but share the same memory location for all members. c union Value { int intValue; float floatValue; char charValue; }; - Enums: Defines a set of named integer constants. c enum Days { Sunday, Monday, Tuesday, // ... }; 4. Typedef: `typedef` is used to create an alias for existing data types, making code more readable and maintainable. c typedef unsigned int uint; // Creating an alias for unsigned int uint count = 5; These are the fundamental data types in C, each with its own specific use cases and properties. Choosing the appropriate data type is crucial for efficient memory usage and accurate representation of data in your programs.
In C programming, symbolic constants, often referred to as macros, are used to define constant values with meaningful names. These constants are replaced with their respective values during the preprocessing phase of compilation. This approach enhances code readability and maintainability by avoiding the use of hard-coded values directly in the code. Here are examples of defining and using symbolic constants in C: 1. Using the `#define` Preprocessor Directive: The `#define` directive is used to define symbolic constants in C. It doesn't allocate memory; instead, it's a text replacement mechanism. c #include#define PI 3.14159 #define MAX_LENGTH 100 int main() { float radius = 5.0; float circumference = 2 * PI * radius; char name[MAX_LENGTH]; printf("Enter your name (up to %d characters): ", MAX_LENGTH); scanf("%s", name); printf("Hello, %s! The circumference of a circle with radius %.2f is %.2f\n", name, radius, circumference); return 0; } In this example, `PI` and `MAX_LENGTH` are defined as symbolic constants using the `#define` directive. They are then used in the `main` function to calculate the circumference of a circle and specify the maximum length of a name. 2. Using `const` Keyword for Constants: In addition to symbolic constants defined with `#define`, C also allows you to define constants using the `const` keyword. c #include const float PI = 3.14159; const int MAX_LENGTH = 100; int main() { float radius = 5.0; float circumference = 2 * PI * radius; char name[MAX_LENGTH]; printf("Enter your name (up to %d characters): ", MAX_LENGTH); scanf("%s", name); printf("Hello, %s! The circumference of a circle with radius %.2f is %.2f\n", name, radius, circumference); return 0; } In this example, the `const` keyword is used to define `PI` and `MAX_LENGTH` as constants. The usage is similar to symbolic constants. Benefits of Symbolic Constants: 1. Readability: Using symbolic constants makes the code more readable by providing meaningful names for values. 2. Maintainability: Changing a constant value requires modifying it only in one place, reducing the chances of errors. 3. Consistency: Symbolic constants help maintain consistency in the code by using the same value throughout the program. 4. Debugging: If an error occurs, the constant name can provide better context compared to a raw value. In general, using symbolic constants or `const` variables for constant values is considered good practice in C programming.
Certainly, here are some simple C programs that demonstrate basic concepts while aiming for better performance and efficiency: 1. Sum of Natural Numbers: Calculate the sum of the first n natural numbers using the arithmetic series formula. c #includeint main() { int n; printf("Enter a positive integer: "); scanf("%d", &n); int sum = (n * (n + 1)) / 2; printf("Sum of the first %d natural numbers: %d\n", n, sum); return 0; } 2. Factorial Calculation: Calculate the factorial of a given number using iterative approach. c #include int main() { int n; printf("Enter a non-negative integer: "); scanf("%d", &n); int factorial = 1; for (int i = 1; i <= n; ++i) { factorial *= i; } printf("Factorial of %d: %d\n", n, factorial); return 0; } 3. Fibonacci Series: Print the Fibonacci series up to a specified number of terms using an optimized approach. c #include int main() { int n; printf("Enter the number of terms: "); scanf("%d", &n); int first = 0, second = 1; printf("Fibonacci Series: %d %d ", first, second); for (int i = 3; i <= n; ++i) { int next = first + second; printf("%d ", next); first = second; second = next; } printf("\n"); return 0; } 4. Prime Number Check: Check if a given number is prime or not using trial division. c #include #include bool is_prime(int num) { if (num <= 1) { return false; } for (int i = 2; i * i <= num; ++i) { if (num % i == 0) { return false; } } return true; } int main() { int num; printf("Enter an integer: "); scanf("%d", &num); if (is_prime(num)) { printf("%d is a prime number.\n", num); } else { printf("%d is not a prime number.\n", num); } return 0; } 5. Reversing an Array: Reverse the elements of an integer array in-place. c #include void reverse_array(int arr[], int size) { for (int i = 0; i < size / 2; ++i) { int temp = arr[i]; arr[i] = arr[size - i - 1]; arr[size - i - 1] = temp; } } int main() { int size; printf("Enter the size of the array: "); scanf("%d", &size); int arr[size]; printf("Enter the elements of the array:\n"); for (int i = 0; i < size; ++i) { scanf("%d", &arr[i]); } reverse_array(arr, size); printf("Reversed array:\n"); for (int i = 0; i < size; ++i) { printf("%d ", arr[i]); } printf("\n"); return 0; } These simple programs cover various fundamental concepts in C programming while focusing on better performance and efficiency. Understanding these examples will provide you with a solid foundation for more complex programming tasks.
C Language 1. Program to print "Hello World!!". #include#include void main() { clrscr(); printf("Hello World!!"); getch(); } #basics 2. Program to assign values of two numbers and print their addition. #include #include void main() { int a=10,b=20; clrscr(); int ans = a + b; printf("Addition is : %d",ans); getch(); } #basics 3. Program to accept values of two numbers and print their addition. #include #include void main() { int a,b,ans; clrscr(); printf("Enter 1st number:"); scanf("%d",&a); printf("Enter 2nd number:"); scanf("%d",&b); ans = a + b; printf("Addition is : %d",ans); getch(); } #basics 4. Program to print simple interest. #include #include void main() { float interest, p, r, n; clrscr(); printf("Enter value of P: "); scanf("%f",&p); printf("Enter value of R: "); scanf("%f",&r); printf("Enter value of N: "); scanf("%f",&n); interest=p*r*n/100f; printf("Simple Interest : %f", interest); getch(); } #basics 5. Program to accept value of radius and print area of a circle. #include #include void main() { float area,radius; clrscr(); printf("Enter Radius:"); scanf("%f",&radius); area=3.14*radius*radius; printf("Area : %6.2f",area); getch(); } #basics 6. Program to accept a number from user and print it’s square & cube. #include #include void main() { int n,sqre,cube; clrscr(); printf("Enter Number: "); scanf("%d",&n); sqre=n*n; cube=n*n*n; printf("\nSquare: %d\nCube: %d",sqre,cube); getch(); } #basics 7. Program to accept two values of a & b and swap their values. #include #include void main() { int a,b,temp; clrscr(); printf("Enter 1st number : "); scanf("%d",&a); printf("Enter 2nd number : "); scanf("%d",&b); printf("\nBefore Swapping..."); printf("A=%d, B=%d",a,b); temp=a; a=b; b=temp; printf("\nAfter Swapping..."); printf("\n A=%d, B=%d",a,b); getch(); } #basics 8. Program to accept two number and print largest among them. #include #include void main() { int a,b; clrscr(); printf("Enter 1st number : "); scanf("%d",&a); printf("Enter 2nd number : "); scanf("%d",&b); if(a>b) printf("Largest value is : %d",a); else printf("Largest value is : %d",b); getch(); } #if_else 9. Program to accept a number and check whether the number is Positive, Negative or Zero. #include #include void main() { int n; clrscr(); printf("Enter number: "); scanf("%d",&n); if(n>0) printf("Number is positive"); else if(n<0) printf("Number is negative"); else printf("Number is Zero"); getch(); } #if_else 10. Program to check whether the number is even or odd. #include #include void main() { int n; clrscr(); printf("Enter number: ); scanf("%d",&n); if(n%2==0) printf("Number is even"); else printf("Number is odd"); getch(); } #if_else 11. Program to accept three numbers from user and print them in ascending and decending order. #include #include void main() { int a,b,c; clrscr(); printf("Enter numbers:"); scanf("%d %d %d",&a,&b,&c); if ((a>=b)&&(a>=c)) { if (b>=c) { printf("\nDesc : %d %d %d",a,b,c); printf("\nAsc : %d %d %d",c,b,a); } else { printf("\nDesc : %d %d %d",a,c,b); printf("\nAsc : %d %d %d",b,c,a); } } else if ((b>=a)&&(b>=c)) { if (a>=c) { printf("\nDesc : %d %d %d",b,a,c); } } else { if (b>=a) { printf("\nDesc : %d %d %d",c,b,a); printf("\nAsc : %d %d %d",a,b,c); } else { printf("\nDesc : %d %d %d",c,a,b); printf("\nAsc : %d %d %d",b,a,c); } } getch(); } #if_else 12. Program to find the roots of a quadratic equation. #include #include #include void main() { float a, b, c, discriminant, real; double r1, r2, imag; printf("Enter coefficients a, b and c: "); scanf("%f%f%f", &a, &b, &c); discriminant = b * b - 4 * a * c; if (discriminant > 0) { r1 = (-b + sqrt(discriminant)) / (2 * a); r2 = (-b - sqrt(discriminant)) / (2 * a); printf("Roots are: %.2f and %.2f", r1, r2); } else if (discriminant == 0) { r1 = r2 = -b / (2 * a); printf("Roots are: %.2f and %.2f", r1, r2) } else { real = -b / (2 * a); imag = sqrt(-discriminant) / (2 * a); printf("Roots : %.2f+%.2fi and %.2f-%.2fi", real, imag, real, imag); } getch(); } #if_else 13. Program to accept rollnumber and marks of three subjects from user and print total marks, average and grade. #include #include void main() { int RollNum, m1, m2, m3, total; float avg; clrscr(); printf("Enter Roll Number : "); scanf("%d",&RollNum); printf("Enter marks for three subjects : "); scanf("%d %d %d", &m1, &m2, &m3); total = m1 + m2 + m3; avg = total / 3.0; printf("\nTotal is : %d", total); printf("\nAverage is : %5.2f", avg); if(avg>80) printf("\nGrade : A"); else if((avg>60)&&(avg<=80)) printf("\nGrade : B"); else if((avg>40)&&(avg<=60)) printf("\nGrade : C"); else if((avg>=33)&&(avg<=40) printf("\nGrade : D"); else printf("\nGrade : Fail"); getch(); } #if_else 14. Program to print numbers from 1 to n using while loop. #include #include void main() { int i=1, n; clrscr(); printf("Enter n : "); scanf("%d", &n); while(i<=n) { printf("%d\t",i); i++; } getch(); } #while_loop 15. Program to print numbers from n to 1 using Do While loop. #include #include void main() { int i=1, n; clrscr(); printf("Enter n : "); scanf("%d", &n); i=n; do { printf("%d\t",i); i--; } while (i >= 1); getch(); } #do_while_loop 16. Program to print first n even numbers. #include #include void main() { int i = 2, n; //to print odd numbers set variable i = 1 clrscr(); printf("Enter n : "); scanf("%d", &n); while(i<=n) { printf("%d\t", i); i = i + 2; } getch(); } #while_loop 17. Program to accept a number and print that number in reverse order. Ex:- 1024 Output:- 4201 #include #include void main() { int reminder, n; clrscr(); printf("Enter n : "); scanf("%d", &n); while(n>0) { reminder=n%10; printf("%d", reminder); n=n/10; } getch(); } #while_loop 18. Program to accept a number and print sum of it’s digits. #include #include void main() { int reminder, sum=0, n; clrscr(); printf("Enter n : "); scanf("%d", &n); while(n>0) { reminder = n % 10; sum = sum + reminder; n = n / 10; } printf("Sum of digits : %d",sum); getch(); } #while_loop 19. Program to take a number from user and check whether it is Armstrong number or not. #include #include void main() { int i=2, temp, rem, sum=0, n; clrscr(); printf("Enter n : "); scanf("%d", &n); temp = n; while(n>0) { rem = n%10; sum = sum+(rem*rem*rem); n = n/10; } if(temp == sum) printf("Entered number is an Armstrong Number"); else printf("Entered number is not an Armstrong Number"); getch(); } #while_loop 20. Program to take number from user and print table of that number. #include #include void main() { int i, n; clrscr(); printf("Enter number : "); scanf("%d", &n); for(i = 1; i <= 10; i++) printf("%d × %d = %d\n", n, i, n*i); getch(); } #for_loop 21. Pattern 1 • • • • • • • • • • • • • • • #include #include void main() { int i, j, n; clrscr(); printf("Enter number :"); scanf("%d", &n); for(i=1; i<=n; i++) { for(j=1; j<=i; j++) { printf("• "); } printf("\n"); } getch(); } #pattern 22. Pattern 2 • • • • • • • • • • • • • • • #include #include void main() { int i, j, n; clrscr(); printf("Enter number : "); scanf("%d", &n); for(i=n; i>=1; i--) { for(j=1;j<=i;j++) { printf("• "); } printf("\n"); } getch(); } #pattern 23. Pattern 3 • • • • • • • • • • • • • • • #include #include void main() { char ch = '*'; int n,i, j, no_of_spaces = 0, spaceCount; printf("Enter number : "); scanf("%d", &n); printf("\n"); no_of_spaces = n - 1; for (i = 1; i <= n; i++) { for (spaceCount = no_of_spaces; spaceCount >= 1; spaceCount--) { printf(" "); } for (j = 1; j <= i; j++) { printf("%2c", ch); } printf("\n"); no_of_spaces--; } getch(); } #pattern 24. Pattern 4 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 #include #include void main() { int n, i, j; printf("Enter number : "); scanf("%d", &n); for (i = 1; i <= n; i++) { for (j = 1; j <= i; j++) { printf("%d ", j); } printf("\n"); } getch(); } #pattern 25. Pattern 5 1 2 1 3 2 1 4 3 2 1 5 4 3 2 1 #include #include void main() { int i, j, n; printf("Enter number : "); scanf("%d", &n); printf("\n"); for (i = 1; i <= n; i++) { for (j = i; j >= 1; j--) { printf("%d ", j); } printf("\n"); } getch(); } #pattern 26. Pattern 6 A B C D E F G H I J K L M N O #include #include void main() { int i, j, n; clrscr(); printf("Enter number : "); scanf("%d", &n); int c = 'A'; for (i = 0; i < n; i++) { for (j = 0; j <= i; j++) { printf("%c", c); c = c + 1; } printf("\n"); } getch(); } #pattern 27. Pattern 7 1 1 2 1 1 2 3 2 1 1 2 3 4 3 2 1 1 2 3 4 5 4 3 2 1 #include #include void main() { int i, j, n; clrscr(); printf("Enter number : "); scanf("%d", &n); for (i = 1; i <= n; i++) { for (j = 1; j <= i; j++) { printf("%d", j); } for (j = i - 1; j >= 1; j--) { printf("%d", j); } printf("\n"); } getch(); } #pattern 28. Pattern 8 (Binary Pattern) 1 0 1 1 0 1 0 1 0 1 1 0 1 0 1 #include #include void main() { int i, j; int count = 1; clrscr(); for (i = 1; i <= 5; i++) { for (j = 1; j <= i; j++) { printf("%d", count++ % 2); if (j == i && i != 5) printf("\n"); } if (i % 2 == 0) count = 1; else count = 0; } getch(); } #pattern 29. Pattern 9 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1 #include #include void main() { int i, j, k, l, n; clrscr(); printf("Enter number : "); scanf("%d", &n); printf("\n"); for (i = n; i >= 1; i--) { for (j = 1; j <= i; j++) printf("%d", j); printf("\n"); } getch(); } #pattern 30. Pattern 10 1 2 1 3 2 1 4 3 2 1 5 4 3 2 1 #include #include void main() { int i, j, k; clrscr(); for (i = 1; i <= 5; i++) { for (j = 5; j >= 1; j--) { if (j <= i) { printf("%d", j); } else { printf(" "); } } printf("\n"); } getch(); } #pattern 31. Pattern 11 1 1 1 2 2 1 1 2 3 3 2 1 1 2 3 4 4 3 2 1 #include #include void main() { int i, j, k; clrscr(); for (i = 1; i <= 5; i++) { for (j = 1; j <= 5; j++) { if (j <= i) { printf("%d ", j); } else { printf(" "); } } for (j = 5; j >= 1; j--) { if (j <= i) { printf("%d ", j); } else { printf(" "); } } printf("\n"); } getch(); } #pattern 32. Floyd's triangle 1 2 3 4 5 6 7 8 9 10 11 12 13 14 #include #include void main() { int n, i, c, a = 1; clrscr(); printf("Enter the number of rows : "); scanf("%d", &n); for (i = 1; i <= n; i++) { for (c = 1; c <= i; c++) { printf("%d ", a); a++; } printf("\n"); } getch(); } #pattern 33. Pyramid * * * * * * * * * * * * * * * #include #include void main() { int row, c, n, temp; clrscr(); printf("Enter the number of rows : "); scanf("%d", &n); temp = n; for (row = 1; row <= n; row++) { for (c = 1; c < temp; c++) printf(" "); temp--; for (c = 1; c <= 2 * row - 1; c++) printf("*"); printf("\n"); } getch(); } #pattern 34. Pyramid 2 * A A*A A*A*A A*A*A*A #include #include void main() { int n, c, k, space, count = 1; clrscr(); printf("Enter the number of rows : "); scanf("%d", &n); space = n; for (c = 1; c <= n; c++) { for (k = 1; k < space; k++) printf(" "); for (k = 1; k <= c; k++) { printf("*"); if (c > 1 && count < c) { printf("A"); count++; } } printf("\n"); space--; count = 1; } getch(); } #pattern 35. Number Pyramid 1 232 34543 4567654 567898765 #include #include void main() { int n, c, d, num = 1, space; clrscr(); printf("Enter the number of rows : "); scanf("%d", &n); space = n - 1; for (d = 1; d <= n; d++) { num = d; for (c = 1; c <= space; c++) printf(" "); space--; for (c = 1; c <= d; c++) { printf("%d", num); num++; } num--; num--; for (c = 1; c < d; c++) { printf("%d", num); num--; } printf("\n"); } getch(); } #pattern 36. Pascal triangle 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 #include #include long fact(int); void main() { int line, i, j; clrscr(); printf("Enter the number : "); scanf("%d", &line); for (i = 0; i < line; i++) { for (j = 0; j < line - i - 1; j++) { printf(" "); } for (j = 0; j <= i; j++) { printf("%ld ", fact(i) / (fact(j) * fact(i - j))); } printf("\n"); } getch(); } long fact(int num) { long f = 1; int i = 1; while (i <= num) { f = f * i; i++; } return f; } #pattern 37. Pascal triangle without using function 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 #include #include void main() { int x, y, n, a, z, s; clrscr(); printf("Enter the number : "); scanf("%d", &n); s = n; for (x = 0; x <= n; x++) { a = 1; for (z = s; z >= 0; z--) printf(" "); s--; for (y = 0; y <= x; y++) { printf("%d ", a); a = (a * (x - y) / (y + 1)); } printf("\n"); } getch(); } #pattern 38. Pascal triangle 2 1 121 12321 1234321 123454321 #include #include void main() { int n, c, k, number = 1, space = n; clrscr(); printf("Enter number of rows : "); scanf("%d", &n); printf("\n"); space = n; for (c = 1; c <= n; c++) { for (k = space; k > 1; k--) printf(" "); space--; for (k = 1; k <= 2 * c - 1; k++) { if (k <= c) { printf("%d", number); if (k < c) number++; } else { number--; printf("%d", number); } } number = 1; printf("\n"); } getch(); } #pattern 39. Number Alphabet Pattern 1 A B 2 3 4 C D E F 5 6 7 8 9 G H I J K L #include #include void main() { int num, r, c; int i = 1; char ch = 'A'; clrscr(); printf("Enter the number of rows : "); scanf("%d", &num); printf("\n"); for (r = 1; r <= num; r++) { for (c = 1; c <= r; c++) { if (r % 2 == 0) { printf(" %c", ch++); } else { printf(" %d", i++); } } printf("\n"); } getch(); } #pattern 40. Number Diamond Pattern 1 1 2 3 1 2 3 4 5 1 2 3 4 5 6 7 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 1 2 3 4 5 1 2 3 1 #include #include void main() { int i, j, k; clrscr(); for(i=1;i<=5;i++) { for(j=i;j<5;j++) { printf(" "); } for(k=1;k<(i*2);k++) { printf("%d",k); } printf("\n"); } for(i=4;i>=1;i--) { for(j=5;j>i;j--) { printf(" "); } for(k=1;k<(i*2);k++) { printf("%d",k); } printf("\n"); } getch(); } #pattern 41. Diamond of Numbers 1 2 2 2 3 3 3 3 3 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 4 4 4 4 4 4 4 3 3 3 3 3 2 2 2 1 #include #include void main() { int i, j, k; clrscr(); for (i = 1; i <= 5; i++) { for (j = i; j < 5; j++) { printf(" "); } for (k = 1; k < (i * 2); k++) { printf("%d", i); } printf("\n"); } for (i = 4; i >= 1; i--) { for (j = 5; j > i; j--) { printf(" "); } for (k = 1; k < (i * 2); k++) { printf("%d", i); } printf("\n"); } getch(); } #pattern 42. Diamond Pattern • ••• ••••• ••• • #include #include void main() { int n, c, k, space = 1; clrscr(); printf("Enter number of rows : "); scanf("%d", &n); space = n - 1; for (k = 1; k <= n; k++) { for (c = 1; c <= space; c++) printf(" "); space--; for (c = 1; c <= 2 * k - 1; c++) printf("•"); printf("\n"); } space = 1; for (k = 1; k <= n - 1; k++) { for (c = 1; c <= space; c++) printf(" "); space++; for (c = 1; c <= 2 * (n - k) - 1; c++) printf("•"); printf("\n"); } getch(); } #pattern 43. Diamond star outline * * * * * * * * * * * * #include #include void main() { int i, j; clrscr(); for (i = 1; i <= 5; i++) { for (j = 5; j > i; j--) { printf(" "); } printf("*"); for (j = 1; j < (i - 1) * 2; j++) { printf(" "); } if (i == 1) { printf("\n"); } else { printf("*\n"); } } for (i = 4; i >= 1; i--) { for (j = 5; j > i; j--) { printf(" "); } printf("*"); for (j = 1; j < (i - 1) * 2; j++) { printf(" "); } if (i == 1) { printf("\n"); } else { printf("*\n"); } } getch(); } #pattern 44. Hollow Diamond * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * #include #include void main() { int i, j, k; clrscr(); for (i = 1; i <= 5; i++) { for (j = 1; j <= 6 - i; j++) { printf("*"); } for (k = 1; k < i; k++) { printf(" "); } for (j = 1; j <= 6 - i; j++) { printf("*"); } printf("\n"); } for (i = 2; i <= 5; i++) { for (j = 1; j <= i; j++) { printf("*"); } for (k = 1; k <= 5 - i; k++) { printf(" "); } for (j = 1; j <= i; j++) { printf("*"); } printf("\n"); } getch(); } #pattern 45. Hollow Square * * * * * * * * * * * * * * * * #include #include void main() { int i, j, n; clrscr(); printf("Enter value of n : "); scanf("%d", &n); printf("\n"); for (i = 1; i <= n; i++) { for (j = 1; j <= n; j++) { if (i != 1 && i != n && j != 1 && j != n) { printf(" "); } else { printf("*"); } } printf("\n"); } getch(); } #pattern 46. Hourglass Pattern * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * #include #include void main() { int num, n, r, c, sp; clrscr(); printf("Enter number of rows: "); scanf("%d", &num); printf("\n"); n = num; for (r = 1; r <= num; r++) { for (sp = 1; sp <= r; sp++) printf(" "); for (c = 1; c <= n; c++) printf("*"); for (c = num - r; c >= 1; c--) printf("*"); n--; printf("\n"); } for (r = 2; r <= num; r++) { for (sp = num - r + 1; sp >= 1; sp--) printf(" "); for (c = 1; c <= r; c++) printf("*"); for (c = r - 1; c >= 1; c--) printf("*"); printf("\n"); } getch(); } #pattern 47. Nested Star-Hash Pyramid #####*##### ######### ######### ######### ######### ######### #include #include void main() { int n = 5, r, c; clrscr(); for (r = 1; r <= 6; r++, n--) { // first pyramid for (c = 1; c <= n; c++) { printf(" #"); } // second pyramid for (c = 1; c <= r; c++) { if (c == 1) { printf(" *"); } else { printf(" #"); } } // third pyramid for (c = r; c > 1; c--) { if (c == 2) { printf(" *"); } else { printf(" #"); } } // fourth pyramid for (c = n; c >= 1; c--) { printf(" #"); } printf("\n"); } getch(); } #pattern 48. Reverse star pyramid * * * * * * * * * * * * * * * * * * * * * * * * * #include #include void main() { int i, j, k; clrscr(); for (i = 5; i >= 1; i--) { for (j = 5; j > i; j--) { printf(" "); } for (k = 1; k < (i * 2); k++) { printf("* "); } printf("\n"); } getch(); } #pattern 49. Rhombus Pattern 1 1 2 2 3 3 4 4 5 5 4 4 3 3 2 2 1 1 #include #include void main() { int num, r, c, sp, n; clrscr(); printf("Enter the number : "); scanf("%d", &num); for (r = 1; r <= num; r++) { for (sp = num - r; sp >= 1; sp--) printf(" "); printf("%d", r); for (sp = r * 2; sp > 1; sp--) printf(" "); printf("%d", r); printf("\n"); } for (r = 1, n = num - 1; r < num; r++, n--) { for (sp = r; sp >= 1; sp--) printf(" "); printf("%d", n); for (sp = n * 2; sp > 1; sp--) printf(" "); printf("%d", n); printf("\n"); } getch(); } #pattern 50. Square kite pattern 1 2 2 3 3 4 4 3 3 2 2 1 #include #include void main() { int i, j, k; clrscr(); for (i = 1; i <= 4; i++) { for (j = 4; j >= (i - 1) * 2 - 1; j--) printf(" "); printf("%d", i); for (j = 2; j <= (i - 1) * 4; j++) printf(" "); if (i > 1) printf("%d", i); printf("\n"); } for (i = 3; i >= 1; i--) { for (j = 4; j >= (i - 1) * 2 - 1; j--) printf(" "); printf("%d", i); for (j = 2; j <= (i - 1) * 4; j++) printf(" "); if (i > 1) printf("%d", i); printf("\n"); } getch(); } 51. Triangle with only border #include #include * * * * * * * * * * * * * * * * * void drawTriangle(char border, char filler, int length) { int start = 2; int base = 4; int i, sp, j, b; for (i = start; i <= length; i++) { for (sp = 0; sp <= length - i; sp++) { printf(" "); } if (i > start) { printf("%c ", border); } if (i > start) { for (b = base; b <= i; b++) { printf("%c ", filler); } } printf("%c \n", border); } for (j = base; j < length + base; j++) { printf("%c ", border); } printf("\n"); } void main() { int length = 6; clrscr(); drawTriangle('*', ' ', length); getch(); } 52. Program to accept number and print it's factorial. #include #include void main() { int i, fact=1, n; clrscr(); printf("Enter number : "); scanf("%d", &n); for(i=1; i<=n; i++) { fact = fact*i; } printf("Factorial is: %d", fact); getch(); } 53. Program to accept number and print if it is prime number or not. #include #include void main() { int i, n; clrscr(); printf("Enter number : "); scanf("%d", &n); for(i=2; i<=n/2; i++) { if(n%i==0) { printf("Number is not Prime"); getch(); break; } } printf("Number is Prime"); getch(); } 54. Program to print 'n' prime numbers. #include #include #include void main() { int i, j, flag=1, n; clrscr(); printf("Enter number : "); scanf("%d", &n); for(i=2; i<=n; i++) { flag=1; for(j=2; j<=i/2; j++) { if(i%j==0) { flag=0; break; } } if(flag==1) printf("%d\n", i); } getch(); } 55. Program to accept a number and print Fibonacci sequence. #include #include void main() { int pre=1, cur=1, temp, i, n; //pre means previous number //cur means current number clrscr(); printf("Enter number : "); scanf("%d", &n); printf("%d\t%d", pre, cur); for(i=3; i<=n; i++) { temp = cur; cur = pre + cur; pre = temp; printf("\t%d", cur); } getch(); } 56. Add 'n' numbers. #include #include void main() { int n, sum=0, i, value; clrscr(); printf("Enter total numbers you want to add : "); scanf("%d", &n); for (i=1; i<=n; i++) { printf("Enter number %d : ", i); scanf("%d", &value); sum = sum + value; } printf("Sum of entered numbers : %d", sum); getch(); } 57. Add 'n' numbers using array. #include #include void main() { int n, sum = 0, i, array[100]; clrscr(); printf("Enter total numbers you want to add : "); scanf("%d", &n); for (i = 1; i <= n; i++) { printf("Enter number %d : ", i); scanf("%d", &array[i]); sum = sum + array[i]; } printf("Sum : %d\n", sum); getch(); } 58. Program to accept a number and add the digits of that number. #include #include void main() { int n, sum = 0, remainder; clrscr(); printf("Enter the number : "); scanf("%d", &n); while (n != 0) { remainder = n % 10; sum = sum + remainder; n = n / 10; } printf("Sum of digits of entered number : %d", sum); getch(); } 59. Program to accept a number and add the digits of that number using recursion. #include #include int add_digits(int); void main() { int n, result; clrscr(); printf("Enter a number : "); scanf("%d", &n); result = add_digits(n); printf("Sum : %d", result); getch(); } int add_digits(int n) { static int sum = 0; if (n == 0) { return 0; } sum = n % 10 + add_digits(n / 10); return sum; } 60. Average of numbers. #include #include void main() { int n, i; float sum=0, x, avg; clrscr(); printf("Enter total Numbers : "); scanf("%d", &n); for (i = 1; i <= n; i++) { printf("\nNumber %d : ", i ); scanf("%f", &x); sum += x; } avg = sum / n; printf("\nThe Average is : %0.2f", avg); getch(); } 61. Program to calculate Square of 'n' numbers. #include #include void main() { int n, r, i, sqr=0; clrscr(); printf("\nEnter the range : "); scanf("%d", &r); for (i = 1; i <= r; i++) { n = i; sqr = n * n; printf("\nSquare of %d is : %d .", n, sqr); } getch(); } 62. Program to take an alphabet from user and check whether it is a vowel or not. #include #include void main() { char ch; clrscr(); printf("Enter an alphabet : "); scanf("%c", &ch); if (ch=='a' || ch=='A' || ch=='e' || ch=='E' || ch=='i' || ch=='I' || ch=='o' || ch=='O' || ch=='u' || ch=='U') printf("%c is a vowel.", ch); else printf("%c is not a vowel.", ch); getch(); } 63. Program to take two numbers and check whether they are amicable numbers or not. #include #include //check function int check(int a, int b) { int s = 0, i; for (i = 1; i < a; i++) { if (a % i == 0) { s = s + i; } } if (s == b) { s = 0; for (i = 1; i < b; i++) { if (b % i == 0) { s = s + i; } } if (s == a) return 1; else return 0; } return 0; } void main() { int a, b; clrscr(); printf("Enter 1st number : "); scanf("%d", &a); printf("Enter 2nd number : "); scanf("%d", &b); if (check(a, b)) { printf("\n%d and %d are Amicable Numbers.", a, b); } else { printf("\n%d and %d are not Amicable Numbers.", a, b); } } 64. Program to accept a number and print the factors of that number. #include #include void main() { int n, i; clrscr(); printf("Enter a number : "); scanf("%d", &n); printf("Factors of %d are : ", n); for (i = 1; i <= n; ++i) { if (n % i == 0) printf("\n%d ", i); } getch(); } 65. Program to accept two integer numbers and print the GCD(Greatest Common Divisor). #include #include void main() { int x, y, m, i; clrscr(); printf("Enter 1st number : "); scanf("%d", &x); printf("Enter 2nd number : "); scanf("%d", &y); if (x > y) m = y; else m = x; for (i = m; i >= 1; i--) { if (x % i == 0 && y % i == 0) { printf("GCD of two number is : %d", i); break; } } getch(); } 66. Program to find power of number. #include #include void main() { int base, expo; int value = 1; clrscr(); printf("Enter base number : "); scanf("%d", &base); printf("Enter exponent number : "); scanf("%d", &expo); while (expo != 0) { // value = value * base; value *= base; --expo; } printf("Answer : %d", value); getch(); } 67. Program to calculate HCF & LCM. #include #include void main() { int a, b, x, y, t, hcf, lcm; clrscr(); printf("Enter two numbers : "); scanf("%d%d", &x, &y); a = x; b = y; while (b != 0) { t = b; b = a % b; a = t; } hcf = a; lcm = (x * y) / hcf; printf("\nHighest Common Factor of %d and %d : %d", x, y, hcf); printf("\nLeast Common Multiple of %d and %d : %d", x, y, lcm); getch(); } 68. Program to find largest among 3 numbers using ternary operator. #include #include void main() { int a, b, c, big; clrscr(); printf("Enter 3 numbers : "); scanf("%d %d %d", &a, &b, &c); big = (a > b && a > c ? a : b > c ? b : c); printf("\nThe biggest number is : %d", big); getch(); } 69. Program to find largest number of 'n' numbers. #include #include void main() { int n, num, i; int big; clrscr(); printf("Enter total numbers : "); scanf("%d", &n); printf("Number %d : ", 1); scanf("%d", &big); for (i = 2; i <= n; i++) { printf("Number %d : ", i); scanf("%d", &num); if (big < num) big = num; } printf("Largest number is : %d", big); getch(); } 70. Program to check whether the number is neon number or not. #include #include void main() { int n, sq, i, sum = 0; clrscr(); printf("Enter the number : "); scanf("%d", &n); sq = n * n; for (i = sq; i > 0; i = i / 10) sum = sum + i % 10; if (sum == n) printf("%d is a neon number.", n); else printf("%d is not a neon number.", n); getch(); } 71. Program to check Niven number (Harshad number). #include #include void main() { int n, d, a, sum = 0; clrscr(); printf("Enter the number : "); scanf("%d", &n); a = n; while (a > 0) { d = a % 10; sum = sum + d; a = a / 10; } if (n % sum == 0) printf("\nThe number is Niven Number."); else printf("\nThe number is not a Niven Number."); getch(); } 72. Program to check whether the number is palindrome or not. #include #include void main() { int n, rev = 0, temp; clrscr(); printf("Enter a number : "); scanf("%d", &n); temp = n; while (temp != 0) { rev = rev * 10; rev = rev + temp % 10; temp = temp / 10; } if (n == rev) printf("\n%d is palindrome number.", n); else printf("\n%d is not palindrome number.", n); getch(); } 73. Program to check perfect number. #include #include void main() { int n, i = 1, sum = 0; clrscr(); printf("Enter a number : "); scanf("%d", &n); /The first perfect number is 6, because 1, 2, and 3 are its proper positive divisors, and 1 + 2 + 3 = 6./ while (i < n) { if (n % i == 0) { sum = sum + i; } i++; } if (sum == n) { printf("\n%d is a perfect number.", i); } else { printf("\n%d is not a perfect number.", i); } getch(); } 74. Program to find the square root of a number. #include #include #include void main() { double num, result; clrscr(); printf("Enter number : "); scanf("%lf", &num); result = sqrt(num); printf("Square root of %lf is %lf.", num, result); getch(); } 75. Program to print sum of 'n' prime numbers. #include #include void main() { int n, i = 3, count, c, sum = 2; clrscr(); printf("Enter total number of prime numbers for addition : "); scanf("%d", &n); if (n >= 1) { printf("\nFirst %d prime numbers are :", n); printf("\n2 "); } for (count = 2; count <= n;) { for (c = 2; c <= i - 1; c++) { if (i % c == 0) break; } if (c == i) { sum = sum + i; printf("%d ", i); count++; } i++; } printf("\nSum : %d", sum); getch(); } 76. Program to print sum of factorial series 1/1! + 2/2! +...1/N! #include #include double sumseries(double); void main() { double number, sum; clrscr(); printf("Enter the number : "); scanf("%lf", &number); sum = sumseries(number); printf("\nSum of the above series = %lf ", sum); getch(); } double sumseries(double m) { double sum2 = 0, f = 1, i; for (i = 1; i <= m; i++) { f = f * i; sum2 = sum2 + (i / f); if (i == m) { printf("%.2lf / %.2lf = %lf", i, f, sum2); } else { printf("%.2lf / %.2lf + \n", i, f); } } return(sum2); } 77. Program to calculate the sum of 'n' terms in Taylor series. #include #include #include void main() { int x, i; int fact = 1, n; float sum = 0; clrscr(); printf("Enter the value of x : "); scanf("%d", &x); printf("Enter the number of terms : "); scanf("%d", &n); for (i = 1; i < n; i++) { fact = fact * i; sum = sum + (pow(x, i) / fact); } sum = sum + 1; printf("The sum of taylor series is : "); printf("%f", sum); getch(); } 78. Program to swap two numbers without using third variable. #include #include void main() { int x = 10, y = 5; clrscr(); printf("Enter x : "); scanf("%d", &x); printf("Enter y : "); scanf("%d", &y); printf("\nBefore Swapping : \n x = %d \n y = %d", x, y); // Code to swap x and y x = x + y; y = x - y; x = x - y; printf("\nAfter Swapping : \n x = %d \n y = %d", x, y); getch(); } 79. Program to swap two numbers using bitwise XOR. #include #include void main() { long i, k; clrscr(); printf("Enter two integers : \n"); scanf("%ld %ld", &i, &k); printf("\n Before swapping i : %ld and k : %ld", i, k); i = i ^ k; k = i ^ k; i = i ^ k; printf("\nAfter swapping i : %ld and k : %ld", i, k); getch(); } 80. Program to swap two numbers using pointer. #include #include void main() { int a, b; int *ptra, *ptrb, *temp; clrscr(); printf("Enter a : "); scanf("%d", &a); printf("Enter b : "); scanf("%d", &b); printf("\nBefore swapping : a : %d, b : %d", a, b); ptra = &a; ptrb = &b; temp = ptra; *ptra = *ptrb; *ptrb = *temp; printf("\nAfter swapping : a : %d, b : %d", a, b); getch(); } 81. Program to add two numbers using pointer. #include #include void main() { int first, second, *p, *q, sum; clrscr(); printf("Enter two integers : \n"); scanf("%d %d", &first, &second); p = &first; q = &second; sum = *p + *q; printf("\nSum of entered numbers : %d", sum); getch(); } 82. Program to add first and last digit of a number. #include #include void main() { int input, firstNum, lastNum; clrscr(); printf("Enter number : "); scanf("%d", &input); lastNum = input % 10; firstNum = input; while (firstNum >= 10) firstNum /= 10; printf("\nAddition of first and last number : %d + %d = %d", firstNum, lastNum, firstNum + lastNum); getch(); } 83. Program to find area of triangle using Heron's formula. #include #include #include void main() { double a, b, c, s, area; clrscr(); printf("\nEnter the sides of triangle : \n"); scanf("%lf%lf%lf", &a, &b, &c); s = (a + b + c) / 2; area = sqrt(s * (s - a) * (s - b) * (s - c)); printf("\nArea of triangle using Heron's Formula : %.2lf", area); getch(); } 84. Program to convert Binary to Decimal. #include #include #include int binary_decimal(int n); void main() { int n; char c; clrscr(); printf("Enter Binary number : "); scanf("%d", &n); printf("%d in binary = %d in decimal", n, binary_decimal(n)); getch(); } //Function to convert binary to decimal. int binary_decimal(int n) { int decimal = 0, i = 0, rem; while (n != 0) { rem = n % 10; n /= 10; decimal += rem * pow(2, i); ++i; } return decimal; } 85. Program to convert Decimal numbers to Binary. #include #include void main() { int n, c, k; clrscr(); printf("Enter a decimal number : "); scanf("%d", &n); printf("\n%d in binary number system is : ", n); for (c = 31; c >= 0; c--) { k = n >> c; if (k & 1) { printf("1"); } else { printf("0"); } } printf("\n"); getch(); } 86. Program to find f(x) by Lagrange's interpolation method. #include #include void main() { float x[10], y[10], temp = 1, f[10], sum, p; int i, n, j, k = 0, c; clrscr(); printf("How many record you will enter : "); scanf("%d", &n); for (i = 0; i < n; i++) { printf("\n\nenter the value of x%d: ", i); scanf("%f", &x[i]); printf("\n\nEnter the value of f(x%d): ", i); scanf("%f", &y[i]); } printf("\n\nEnter X for finding f(x): "); scanf("%f", &p); for (i = 0; i < n; i++) { temp = 1; k = i; for (j = 0; j < n; j++) { if (k == j) { continue; } else { temp = temp * ((p - x[j]) / (x[k] - x[j])); } } f[i] = y[i] * temp; } for (i = 0; i < n; i++) { sum = sum + f[i]; } printf("\n\nf(%.1f) = %f ", p, sum); getch(); } 87. Program to check the leap year. #include #include void main() { int year; clrscr(); printf("Enter a year : "); scanf("%d", &year); if (year % 400 == 0) printf("\n%d is a leap year.", year); else if (year % 100 == 0) printf("\n%d is not a leap year.", year); else if (year % 4 == 0) printf("\n%d is a leap year.", year); else printf("%d is not a leap year.", year); getch(); } 88. Program to find nCr & nPr. #include #include long factorial(int); long find_ncr(int, int); long find_npr(int, int); void main() { int n, r; long ncr, npr; clrscr(); printf("Enter the value of n and r : \n"); scanf("%d %d", &n, &r); ncr = find_ncr(n, r); npr = find_npr(n, r); printf("%dC%d = %ld\n", n, r, ncr); printf("%dP%d = %ld\n", n, r, npr); getch(); } long find_ncr(int n, int r) { long result; result = factorial(n) / (factorial(r) * factorial(n - r)); return result; } long find_npr(int n, int r) { long result; result = factorial(n) / factorial(n - r); return result; } long factorial(int n) { int c; long result = 1; for (c = 1; c <= n; c++) result = result * c; return (result); } 89. Program for Newton Raphson General. #include #include int user_power, i = 0, cnt = 0, flag = 0; int coef[10] = {0}; float x1 = 0, x2 = 0, t = 0; float fx1 = 0, fdx1 = 0; int main() { printf("PROGRAM FOR NEWTON RAPHSON GENERAL"); printf("\nEnter the total no. of power : "); scanf("%d", &user_power); for (i = 0; i <= user_power; i++) { printf("\nx^%d : ", i); scanf("%d", &coef[i]); } printf("\n"); printf("\n\nThe Polynomial is "); //printing coeff. for (i = user_power; i >= 0; i--) { printf("%dx^%d", coef[i], i); } printf("\n\nIntial x1 -> "); scanf("%f", &x1); printf("Iteration\tX1\tFX1\tF'X1"); do { cnt++; fx1 = fdx1 = 0; for (i = user_power; i >= 1; i--) { fx1 += coef[i] * (pow(x1, i)); } fx1 += coef[0]; for (i = user_power; i >= 0; i--) { fdx1 += coef[i] * (i * pow(x1, (i - 1))); } t = x2; x2 = (x1 - (fx1 / fdx1)); x1 = x2; printf("\n\t%d\t%.3f\t%.3f\t%.3f ", cnt, x2, fx1, fdx1); } while ((fabs(t - x1)) >= 0.0001); printf("\n\nThe root of equation is %f", x2); return 0; } 90. Program to calculate the sum of even numbers from 1 to n. #include #include void main() { int sum = 0, n; clrscr(); printf("Enter the number : "); scanf("%d", &n); // Using Math formula // (n/2)((n / 2) + 1) sum = ((n / 2) * ((n / 2) + 1)); printf("Sum of even numbers from 1 to %d : %d", n, sum); getch(); } 91. Simpson 1/3 rule. #include float f(float x) { return (1 / (1 + x)); } void main() { int i, n; float x0, xn, h, y[20], so, se, ans, x[20]; clrscr(); printf("\nEnter values of x0,xn,h: "); scanf("%f%f%f", &x0, &xn, &h); n = (xn - x0) / h; if (n % 2 == 1) { n = n + 1; } h = (xn - x0) / n; printf("\nRefined value of n and h are:%d and %f\n", n, h); printf("\n Y values: \n"); for (i = 0; i <= n; i++) { x[i] = x0 + i * h; y[i] = f(x[i]); printf("\n %f\n", y[i]); } so = 0; se = 0; for (i = 1; i < n; i++) { if (i % 2 == 1) { so = so + y[i]; } else { se = se + y[i]; } } ans = h / 3 * (y[0] + y[n] + 4 * so + 2 * se); printf("\nFinal integration is %f", ans); getch(); } 92. Program to add two strings without using concat() function. #include #include void concat(char[], char[]); void main() { char s1[50], s2[30]; clrscr(); printf("\nEnter String 1 : "); gets(s1); printf("\nEnter String 2 : "); gets(s2); concat(s1, s2); printf("\nConcated string is : %s", s1); getch(); } void concat(char s1[], char s2[]) { int i, j; i = strlen(s1); for (j = 0; s2[j] != '\0'; i++, j++) { s1[i] = s2[j]; } s1[i] = '\0'; } 93. Program to check vowels in string. #include int count_vowels(char []); int check_vowel(char); void main() { char array[100]; int c; clrscr(); printf("Enter a string : "); gets(array); c = count_vowels(array); printf("\nNumber of vowels in %s : %d", array, c); getch(); } int count_vowels(char a[]) { int count = 0, c = 0, flag; char d; do { d = a[c]; flag = check_vowel(d); if (flag == 1) count++; c++; } while (d != '\0'); return count; } int check_vowel(char a) { if (a >= 'A' && a <= 'Z') { // Converting to lower case a = a + 'a' - 'A'; } if (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u') return 1; return 0; } 94. Program to compare two strings. #include #include void main() { char a[100], b[100]; clrscr(); printf("\nEnter the first string : "); gets(a); printf("\nEnter the second string : "); gets(b); if (strcmp(a, b) == 0) printf("\nEntered strings are equal."); else printf("\nEntered strings are not equal."); getch(); } 95. Program to compare strings without using strcmp() function. #include int stringCompare(char[], char[]); void main() { char str1[100], str2[100]; int compare; clrscr(); printf("Enter first string : "); scanf("%s", str1); printf("Enter second string : "); scanf("%s", str2); compare = stringCompare(str1, str2); if (compare == 1) printf("\nBoth strings are equal."); else printf("\nBoth strings are not equal."); getch(); } int stringCompare(char str1[], char str2[]) { int i = 0, flag = 0; while (str1[i] != '\0' && str2[i] != '\0') { if (str1[i] != str2[i]) { flag = 1; break; } i++; } if (flag == 0 && str1[i] == '\0' && str2[i] == '\0') return 1; else return 0; } 96. Program to convert string from uppercase to lowercase. #include #include #include void main() { char str[20]; int i; clrscr(); printf("Enter string : "); gets(str); for (i = 0; i <= strlen(str); i++) { if (str[i] >= 65 && str[i] <= 90) { str[i] = (char) (str[i] + 32); } } printf("String in lowercase : %s", str); getch(); } 97. Program to copy char array / copy string. #include #include #include void main() { char source[] = "C program"; char destination[50]; clrscr(); strcpy(destination, source); printf("Source string: %s\n", source); printf("Destination string: %s\n", destination); getch(); } 98. Program to copy string without using strcpy() function. #include #include void strCopy(char[], char[]); void main() { char str1[100], str2[100]; printf("Enter any string: "); scanf("%s", str1); strCopy(str1, str2); printf("After copying: %s", str2); getch(); } void strCopy(char str1[], char str2[]) { int i = 0; while (str1[i] != '\0') { str2[i] = str1[i]; i++; } str2[i] = '\0'; } 99. Program to count frequency of characters in a string. #include #include #include void main() { char str[1500]; int c = 0, count[26] = {0}; clrscr(); printf("Enter a string : "); gets(str); while (str[c] != '\0') { if (str[c] >= 'a' && str[c] <= 'z') count[str[c] - 'a']++; c++; } for (c = 0; c < 26; c++) { if (count[c] != 0) printf("%c occurs %d times in the string.\n", c + 'a', count[c]); } getch(); } 100. Program to count total number of uppercase and lowercase in a string. #include #include #include void main() { int upper = 0, lower = 0; char ch[80]; int i; clrscr(); printf("Enter string : "); gets(ch); i = 0; while (ch[i] != '\0') { //uppercase counter if (ch[i] >= 'A' && ch[i] <= 'Z') { upper++; } //lowercase counter if (ch[i] >= 'a' && ch[i] <= 'z') { lower++; } i++; } printf("\nUppercase Letters : %d", upper); printf("\nLowercase Letters : %d", lower); getch(); } C Language 👨💻: 101. Program to calculate the length of string. #include #include #include void main() { char a[100]; int length; clrscr(); printf("\nEnter a string to calculate it's length : "); gets(a); length = strlen(a); printf("\nLength of entered string is : %d", length); getch(); } 102. Program to calculate the length of string without using strlen() function. #include #include void main() { char s[1000], i; clrscr(); printf("Enter a string : "); scanf("%s", s); for (i = 0; s[i] != '\0'; ++i); printf("Length of string : %d", i); getch(); } 103. Program to check the palindrome of string. #include #include #include void main() { char text[100]; int begin, middle, end, length = 0; clrscr(); printf("Enter the string to check if it is a palindrome : \n"); gets(text); while (text[length] != '\0') { length++; } end = length - 1; middle = length / 2; for (begin = 0; begin < middle; begin++) { if (text[begin] != text[end]) { printf("\nString is not a palindrome."); break; } end--; } if (begin == middle) printf("\nString is Palindrome."); getch(); } 104. Program to check the palindrome of word using array. #include #include #include void main() { char word[100]; int length, counter; clrscr(); printf("Enter a word : "); scanf("%s", word); length = strlen(word); int flag = 1; for (counter = 0; counter < length / 2 && flag; counter++) { if (word[counter] != word[length - counter - 1]) { flag = 0; break; } } if (flag) { printf("\n%s is a palindrome.", word); } else { printf("\n%s is NOT a palindrome.", word); } getch(); } 105. Program to remove white space in string. #include #include #include void main() { int i = 0, j = 0, len; char buff[50]; clrscr(); printf("Enter String with white space : "); gets(buff); len = (int) strlen(buff); while (i != len) { if (buff[i] != ' ') buff[j++] = buff[i]; i++; } buff[j] = 0; printf("\nYour String is : %s.", buff); getch(); } 106. Program to reverse the string. #include #include #include char *strrev(char *str) { char *p1, *p2; if (!str || !*str) return str; for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2) { *p1 ^= *p2; *p2 ^= *p1; *p1 ^= *p2; } return str; } void main() { char arr[100]; clrscr(); printf("\nEnter a string to reverse : "); gets(arr); strrev(arr); printf("\nReverse of entered string is : %s", arr); getch(); } 107. Program to reverse the string using pointer. #include #include void main() { char str_array[10000], *ptr; int i, len; clrscr(); printf("Enter a string : "); gets(str_array); ptr = str_array; for (i = 0; i < 10000; i++) { if (*ptr == '\0') break; ptr++; } len = i; ptr--; printf("\nReversed String is : "); for (i = len; i > 0; i--) { printf("%c", *ptr--); } getch(); } 108. Program to sort the strings. #include #include #include void main() { int i, j, n; char str[20][20], temp[20]; clrscr(); printf("Enter the number of string to be sorted : "); scanf("%d", &n); for (i = 0; i <= n; i++) gets(str[i]); for (i = 0; i <= n; i++) for (j = i + 1; j <= n; j++) { if (strcmp(str[i], str[j]) > 0) { strcpy(temp, str[i]); strcpy(str[i], str[j]); strcpy(str[j], temp); } } printf("\nSorted string :"); for (i = 0; i <= n; i++) { puts(str[i]); } getch(); } 109. Program to swap two strings. #include #include #include #include void main() { char str1[100], str2[100], *temp; clrscr(); printf("Enter first string : "); gets(str1); printf("Enter second string : "); gets(str2); printf("\nBefore Swapping : \n"); printf("First string : %s\n", str1); printf("Second string : %s\n", str2); temp = (char *) malloc(100); strcpy(temp, str1); strcpy(str1, str2); strcpy(str2, temp); printf("\nAfter Swapping : \n"); printf("First string : %s\n", str1); printf("Second string : %s\n", str2); getch(); } 110. Program to add two matrix. #include #include void main() { int m, n, c, d, first[10][10], second[10][10], sum[10][10]; clrscr(); printf("Enter the number of rows and columns of matrix :"); scanf("%d%d", &m, &n); printf("\nEnter the elements of first matrix : \n"); for (c = 0; c < m; c++) { for (d = 0; d < n; d++) { scanf("%d", &first[c][d]); } } printf("\nEnter the elements of second matrix : \n"); for (c = 0; c < m; c++) { for (d = 0; d < n; d++) { scanf("%d", &second[c][d]); } } printf("\nSum of entered matrices : \n"); for (c = 0; c < m; c++) { for (d = 0; d < n; d++) { sum[c][d] = first[c][d] + second[c][d]; printf("%d\t", sum[c][d]); } printf("\n"); } getch(); } 111. Program to arrange array numbers in ascending order. #include #include void main() { int i, j, a, n, number[30]; clrscr(); printf("Enter total numbers : "); scanf("%d", &n); printf("\n Enter the numbers :\n"); for (i = 0; i < n; ++i) { scanf("%d", &number[i]); } for (i = 0; i < n; ++i) { for (j = i + 1; j < n; ++j) { if (number[i] > number[j]) { a = number[i]; number[i] = number[j]; number[j] = a; } } } printf("The numbers arranged in ascending order are :\n"); for (i = 0; i < n; ++i) { printf("%d\n", number[i]); } getch(); } 112. Program to check whether the matrix is sparse matrix or not. #include #include void main() { static int array[10][10]; int i, j, m, n; int counter = 0; clrscr(); printf("Enter the order of the matix : "); scanf("%d %d", &m, &n); printf("\nEnter the co-efficients of the matix :\n"); for (i = 0; i < m; ++i) { for (j = 0; j < n; ++j) { scanf("%d", &array[i][j]); if (array[i][j] == 0) { ++counter; } } } if (counter > ((m * n) / 2)) { printf("The given matrix is sparse matrix \n"); } else { printf("The given matrix is not a sparse matrix \n"); } printf("There are %d number of zeros", counter); getch(); } 113. Program to delete an element from array. #include