Thanks for visiting my GitHub account!
is a general-purpose programming language, developed in 1972, and still quite popular. C is a very powerful language. It has been used to develop operating systems, databases, applications, etc.
- Visit-> https://mega.nz/file/VOs2ESgA#k1pVAyt9jPlyDSJiKEUe97-ZAGpcvbQJRn2eEnrIh3A
- More -> https://github.com/learnwithfair/c-programming
- Code::Blocks, Download(mingw-setup.exe, FossHUB) ->https://www.codeblocks.org/downloads/binaries/
- Or, Click-here
- Select codeblocks-20.03mingw-setup.exe
- Click on FossHUB
Outline |
![]() |
- 1. Basic C Programming Topics
- 1.1 Translator Program
- 1.2 Algorithm and Flowchart
- 1.3 Introduction to C program
- 1.4 First C program and its parts
- 1.5 Comments and Escape sequences
- 1.6 Keywords, Variables, Data types
- 1.7 Input and output functions
- 1.8 Operators
- 1.9 <math.h> library
- 1.10 Control Statement
- 1.11 Functions
- 1.12 Arrays
- 2. Intermediate C
- 3. Advanced C
A program is a set of instructions to perfrom a task.
A translator program is a software tool that translates source code to object code (machine code / binary code). It ranslates code or instructions from one programming language into another. It plays a crucial role in the software development process, enabling developers to write code in high-level languages that are easier to understand and maintain, while the translator converts it into machine code that a computer can execute. There are several types of translator programs, each serving a specific purpose in this process:
-
Compiler:
- Purpose: A compiler translates the entire source code of a program written in a high-level language into machine code or another lower-level language in one go. It generates an executable file that can run independently.
- Examples: GCC (GNU Compiler Collection) for C/C++, javac for Java.
-
Interpreter:
- Purpose: An interpreter executes code line by line, translating and executing each line on the fly. It doesn't produce an independent executable; instead, it directly interprets and executes the source code.
- Examples: Python interpreter, JavaScript interpreter in web browsers.
-
Assembler:
- Purpose: An assembler translates assembly language code into machine code. Assembly language is a low-level human-readable language that corresponds closely to the architecture of a specific computer's CPU.
- Examples: NASM (Netwide Assembler) for x86 assembly.
-
Linker:
- Purpose: A linker is responsible for combining multiple object files or libraries generated by a compiler into a single executable file. It resolves references between different parts of a program.
- Examples: ld (GNU Linker), Microsoft Linker (link.exe).
-
Loader:
- Purpose: A loader loads an executable program into memory so that it can be executed by the CPU. It also performs necessary memory allocation and relocation.
- Examples: The operating system's loader component.
-
Preprocessor:
- Purpose: A preprocessor is a tool that processes the source code before compilation. It handles directives and macros, performs text substitution, and prepares the code for the compiler.
- Examples: The C/C++ preprocessor, which handles
#include
and#define
directives.
-
Transpiler (Source-to-Source Compiler):
- Purpose: A transpiler translates code from one high-level programming language into another high-level programming language. It is often used for migrating codebases or converting code to be compatible with different platforms or frameworks.
- Examples: Babel (JavaScript transpiler), TypeScript compiler (TypeScript to JavaScript).
-
Cross-Compiler:
- Purpose: A cross-compiler is designed to generate code for a different target platform or architecture than the one it runs on. This is often used in embedded systems development.
- Examples: ARM cross-compiler, used for developing software for ARM-based microcontrollers on x86-based computers.
-
Decompiler:
- Purpose: A decompiler attempts to reverse the process of compilation by translating machine code or executable files back into a higher-level programming language or assembly language. This is often used for reverse engineering and analysis of binaries.
- Examples: IDA Pro, Hex-Rays (for reverse engineering).
Each type of translator program serves a specific role in the software development process, from converting human-readable code into machine code to managing dependencies and loading the program into memory for execution. The choice of which type of translator to use depends on the programming language, target platform, and development requirements.
An algorithm is a set of well-defined, step-by-step instructions for solving a specific problem or accomplishing a particular task. It serves as a blueprint for a computer program, and it can be implemented in various programming languages. Algorithms are essential in computer science, as they help solve problems efficiently and predictably.
A flowchart is a visual representation of an algorithm that uses various shapes and symbols to represent different elements of the algorithm, such as inputs, processes, decisions, and outputs. Flowcharts make it easier to understand and communicate how an algorithm works, both for programmers and non-programmers. They are commonly used for documenting, planning, and designing algorithms before writing actual code.
Here are some key concepts related to algorithms and flowcharts:
Algorithms:
-
Problem Definition: Begin by clearly defining the problem or task you want to solve.
-
Input and Output: Identify the inputs (data or information required) and the expected outputs (results).
-
Steps: Break down the solution into a sequence of steps, each of which performs a specific operation.
-
Decisions: Include conditional statements (if-else) for making choices or decisions within the algorithm.
-
Loops: Use loops (for, while) for repeating a set of steps when necessary.
-
Pseudocode: Before creating a flowchart or writing code, often, it's helpful to describe the algorithm in a high-level, human-readable language called pseudocode.
-
Efficiency: Consider the efficiency and performance of the algorithm, aiming for the most efficient solution.
Flowcharts:
-
Start and End: Every flowchart begins with a "Start" symbol and ends with an "End" symbol.
-
Processes: Use rectangular boxes to represent the processing steps or operations in the algorithm.
-
Decision Points: Represent decision points (e.g., if-else statements) with diamond-shaped symbols.
-
Input/Output: Use parallelograms to denote input and output operations.
-
Arrows: Connect the symbols with arrows to indicate the flow of control or data from one step to another.
-
Flow Control: Use arrows with labels (e.g., "Yes" or "No") to indicate the direction of flow based on decisions.
-
Connectors: Sometimes, you may need to use connectors (small circles) to link different parts of the flowchart.
-
Annotations: Add comments and explanations to clarify the purpose of specific steps or decisions.
To create a flowchart for an algorithm, you can use specialized software or even pen and paper. Flowcharts help in visualizing the logic of an algorithm and are valuable tools for designing, documenting, and communicating the solution to others.
While flowcharts are useful for illustrating algorithms, the actual implementation of the algorithm is done through programming languages like C, Java, Python, etc. The flowchart serves as a visual guide to help translate the algorithm into code.
- C is a general-purpose mid-level programming language, a widely-used and influential programming language that was developed in the early 1970s at Bell Labs by Dennis Ritchie.
Here are some key aspects of C programming and reasons why C has been important:
-
Efficiency: C is known for its efficiency and low-level control over hardware, making it an ideal choice for system programming, embedded systems, and developing software that requires high performance.
-
Standard Library: C provides a rich standard library that includes functions for tasks like file I/O, memory management, string manipulation, and more. This standard library simplifies common programming tasks and allows developers to create efficient programs without reinventing the wheel.
-
Learning and Teaching: Mother of Programming language. C is often recommended as a first programming language for beginners because it teaches fundamental programming concepts, such as variables, loops, and functions, in a clear and concise manner. Learning C provides a solid foundation for understanding other programming languages.
-
C has been used to write everything from operating systems (including Windows and many others) to complex programs like the Python interpreter, Git, Oracle database, and more.
- code editor (VSCode/Codeblock) and compiler (gcc)
#include <stdio.h>
int main()
{
printf("hello world");
return 0;
}
-
Let's break down the code to understand each line:
-
#include <stdio.h> The function used for generating output is defined in stdio.h. In order to use the printf function, we need to first include the required file, also called a header file. The <stdio.h> library provides a range of functions for handling input and output operations in C. Some examples: printf(), scanf(), gets(), puts(), putchar(), getchar()
-
int main() The main() function is the entry point to a program. Curly brackets { } indicate the beginning and end of a function (also called a code block). The statements inside the brackets determine what the function does when executed.
-
return 0 Success Indicator: The return 0; statement is a way for a C program to signal to the operating system that it has executed successfully and is terminating without any errors. Error Indicator: If a program encounters an error or unexpected condition during execution, it can use a non-zero value (e.g., return 1;, return -1;) to indicate that something went wrong.
-
In C programming, comments and escape sequences are important for code documentation and character representation. It also help for debugging and leave explanation of codes. Here's an explanation of each:
Comments:
Comments in C are used to provide explanations or descriptions within the code. They are ignored by the compiler and serve as documentation for programmers. C provides two types of comments:
-
Single-Line Comments: Single-line comments begin with
//
and continue to the end of the line. They are often used for short explanations on a single line.// This is a single-line comment
-
Multi-Line Comments: Multi-line comments are enclosed between
/*
and*/
. They can span multiple lines and are often used for longer explanations./* This is a multi-line comment */
Example of comments in C code:
#include <stdio.h>
int main() {
// This is a single-line comment
printf("Hello, World!\n"); // This comment is at the end of the line
/* This is a
multi-line comment */
return 0;
}
Escape Sequences:
Escape sequences are special character combinations that are used to represent characters that are not directly typable or printable. They begin with a backslash \
followed by a character. Here are some common escape sequences in C:
\n
: Newline character.\t
: Tab character.\"
: Double quotation mark.\'
: Single quotation mark.\\
: Backslash.
Escape sequences are often used when you need to insert special characters into strings, such as newline characters to format text or escape quotation marks within a string.
Example of escape sequences in C code:
#include <stdio.h>
int main() {
printf("This is a newline: \n");
printf("This is a tab: \t");
printf("This is a double quote: \"\n");
printf("This is a single quote: \'\n");
printf("This is a backslash: \\\n");
return 0;
}
When you run the code, you will see that the escape sequences are interpreted and displayed as the corresponding special characters.
- Tokens of any programming language: keywords, identifiers, data types, operators, special symbols, string.
In C programming, you'll work with keywords, variables, and various data types to create programs. Here's an overview of these fundamental concepts:
Keywords are reserved words in C that have special meanings and are used to define the structure and logic of the program. You cannot use keywords as identifiers (variable or function names). Some common C keywords include:
auto double int struct break else long switch case enum register typedef char extern return union const float short unsigned continue for signed void default goto sizeof volatile do if static while
int
: Defines an integer data type.char
: Defines a character data type.float
: Defines a floating-point data type.double
: Defines a double-precision floating-point data type.if
: Used for conditional statements.else
: Used in conjunction withif
for alternative actions.while
: Used to create loops.for
: Used for loop control.switch
: Used for multi-way branching.return
: Specifies the return value of a function.break
: Exits a loop or aswitch
statement.continue
: Jumps to the next iteration of a loop.void
: Indicates that a function returns no value.
-
without variable
// without variable #include <stdio.h> int main() { printf("Math Marks: 80\n"); printf("Computer Marks: 60\n"); printf("English Marks: 70\n"); return 0; }
Variables are used to store and manipulate data within a C program. When declaring a variable, you specify its data type, a name, and an optional initial value. Variable names must be unique within a scope (a block of code). Examples of variable declarations:
-
int age;
(Declares an integer variable namedage
.) -
float salary = 5000.50;
(Declares a floating-point variable namedsalary
and assigns it an initial value.) -
char initial = 'A';
(Declares a character variable namedinitial
and assigns it the character 'A'.)// declaring variables #include <stdio.h> int main() { int math = 80; int bangla = 60; int english = 70; return 0; }
Naming conventions and rules for variables in C are essential for writing readable and maintainable code. They help developers understand the purpose of variables and ensure consistency across projects. Here are some common naming conventions and rules for variables in C:
Variable Naming Rules:
-
Valid Characters: Variable names can consist of letters (both uppercase and lowercase), digits, and underscores. They must start with a letter or an underscore. C is case-sensitive, so
myVariable
andmyvariable
are considered different names. -
Reserved Keywords: Variable names cannot be the same as C reserved keywords (e.g.,
int
,if
,while
). Avoid using these keywords as variable names. -
No Special Characters: Avoid using special characters like
@
,$
, or%
in variable names. Stick to letters, numbers, and underscores. -
Length: Variable names can be as long as necessary, but it's a good practice to keep them reasonably short and descriptive.
Variable Naming Conventions:
-
Use Descriptive Names: Choose variable names that clearly convey the purpose of the variable. For example, use
counter
instead ofc
for a counter variable. -
Camel Case: For multi-word variable names, use camel case. Start with a lowercase letter, and capitalize the first letter of each subsequent word. For example,
myVariableName
. -
Meaningful Names: Make sure variable names reflect the data they hold. For example, use
studentName
instead ofname
for a student's name. -
Avoid Single Letters: Generally, avoid using single letters (except for loop counters) as variable names. This improves code readability.
-
Constants: If a variable is a constant (a value that does not change), use uppercase letters with underscores to separate words. For example,
MAX_VALUE
. -
Prefixes and Suffixes: You can use prefixes or suffixes to indicate variable types. For example,
strName
for a string andnCount
for an integer count. -
Avoid Ambiguity: Ensure your variable names are not ambiguous. For example, if you have both
customerName
andcustomerAddress
, it's clear what they represent. -
Consistency: Maintain a consistent naming style across your codebase. If you start with camel case, continue with camel case.
Examples:
// Good variable naming examples
int numberOfStudents;
char studentName[50];
const int MAX_ATTEMPTS = 3;
// Avoid using single letters and cryptic names
int n; // Avoid using single letters like 'n'
int x; // Avoid cryptic variable names
// Meaningful names and clear intent
double temperatureCelsius;
char customerAddress[100];
// Consistent style and camel case
int totalSalesCount;
Adhering to these naming conventions and rules will improve the readability and maintainability of your C code and make it easier for you and other developers to understand and work with your programs.
// variable declarations
// variable initializations
// variable dynamic initializations
// variable naming conventions
// basic data types
// format specifiers
Date of birth - 12/03/1990
1. define 3 variables to store
2. output 1
day = 12,
month = 3,
year = 1990
day = 12, month = 3, year = 1990
C provides several built-in data types, allowing you to store different types of data in variables. Common data types include:
-
Integer Data Types:
int
: Used to store whole numbers.short
: Used for short integers.long
: Used for long integers.long long
: Used for very long integers.signed
andunsigned
: Modifiers to specify whether the integer can be negative or non-negative.
In C, the memory allocated for integer data types like
int
,short
,long
, andlong long
can vary depending on the specific implementation (compiler and system). However, there are general guidelines and common memory sizes associated with these data types on most systems.Here's an example of integer data types and their common memory sizes:
int
: - Common memory size: 4 bytes (32 bits) - Typical range: -2,147,483,648 to 2,147,483,647int myInt; // Declaration of an integer variable
short
(orshort int
): - Common memory size: 2 bytes (16 bits) - Typical range: -32,768 to 32,767short myShort; // Declaration of a short integer variable
long
: - Common memory size: 4 bytes (32 bits) or 8 bytes (64 bits, on 64-bit systems) - Typical range: -2,147,483,648 to 2,147,483,647 (32-bit), or -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (64-bit)long myLong; // Declaration of a long integer variable
long long
(orlong long int
): - Common memory size: 8 bytes (64 bits) - Typical range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807long long myLongLong; // Declaration of a long long integer variable
signed
andunsigned
: - These qualifiers can be used with integer data types to specify whether the values are signed (can be positive or negative) or unsigned (only non-negative).signed int mySignedInt; // A signed integer can store positive and negative unsigned int myUnsignedLongLong; // An unsigned can store only positive values #include <stdio.h> int main() { signed int positiveNumber = 42; signed int negativeNumber = -10; printf("Positive Number: %d\n", positiveNumber); printf("Negative Number: %d\n", negativeNumber); return 0; }
Please note that the actual memory sizes and ranges can vary depending on the specific compiler and system architecture (32-bit vs. 64-bit). You can use the
sizeof
operator in C to determine the size of data types on your system:printf("Size of int: %lu bytes\n", sizeof(int)); printf("Size of short: %lu bytes\n", sizeof(short)); printf("Size of long: %lu bytes\n", sizeof(long)); printf("Size of long long: %lu bytes\n", sizeof(long long));
This code will output the sizes of these data types on your specific system.
-
Floating-Point Data Types:
-
float
: Used for single-precision floating-point numbers. -
double
: Used for double-precision floating-point numbers. -
long double
: Used for extended precision floating-point numbers.In C, the memory allocated for floating-point data types like
float
,double
, andlong double
can also vary depending on the specific implementation (compiler and system). However, there are general guidelines and common memory sizes associated with these data types on most systems.Here's an example of floating-point data types and their common memory sizes:
float
: - Common memory size: 4 bytes (32 bits) - Typical range: Approximately 3.4e-38 to 3.4e38float myFloat; // Declaration of a floating-point variable
double
: - Common memory size: 8 bytes (64 bits) - Typical range: Approximately 1.7e-308 to 1.7e308double myDouble; // Declaration of a double-precision floating-point variable
long double
: - Common memory size: 8 bytes (64 bits) or 16 bytes (128 bits, on some systems) - Typical range: Similar todouble
but with greater precisionlong double myLongDouble; // Declaration of a long double floating-point variable
Please note that the actual memory sizes and ranges can vary depending on the specific compiler and system architecture (32-bit vs. 64-bit). You can use the
sizeof
operator in C to determine the size of data types on your system, as shown in the previous answer.Here's how you can determine the size of
float
,double
, andlong double
on your system:printf("Size of float: %lu bytes\n", sizeof(float)); printf("Size of double: %lu bytes\n", sizeof(double)); printf("Size of long double: %lu bytes\n", sizeof(long double));
In C, data type modifiers are used to alter the storage size and sign of the data type. These modifiers can help control memory allocation and the range of values that a variable can hold. Here are some commonly used data type modifiers in C and how they affect memory allocation:
-
short
andlong
Modifiers:short
: This modifier is used to reduce the storage size of an integer data type. For example,short int
is typically 2 bytes, which is smaller than a standardint
.long
: This modifier is used to increase the storage size of an integer data type. For example,long int
is typically 4 or 8 bytes, providing a larger range of values.
-
signed
andunsigned
Modifiers:signed
: This modifier is the default for integer data types. It allows variables to store both positive and negative values. For example,int
is implicitly signed.unsigned
: This modifier is used to make an integer data type capable of storing only non-negative values, effectively doubling the positive range. For example,unsigned int
can store values from 0 to 65,535 instead of -32,768 to 32,767 for a standardint
.
-
const
Modifier:- The
const
modifier is used to declare a constant, meaning the value of the variable cannot be changed once it's assigned. While this modifier doesn't directly affect memory allocation, it can help the compiler optimize code by placing constants in read-only memory segments.
- The
-
volatile
Modifier:- The
volatile
modifier is used to indicate that a variable's value can be changed by external factors not under the program's control. This modifier prevents the compiler from optimizing away accesses to the variable and can affect memory allocation in the sense that it may lead to actual memory accesses.
- The
-
register
Modifier:- The
register
modifier is used to suggest that a variable should be stored in a processor register for faster access. While it doesn't explicitly control memory allocation, it can improve performance by reducing memory accesses.
- The
These modifiers provide flexibility and control over memory allocation and variable behavior in C. When choosing which modifier to use, consider the specific requirements of your program, the range of values needed, and any optimization considerations.
-
-
-
Character Data Type:
char
: Used to store a single character.
In C, character data is represented using the
char
data type. Here's an example of using thechar
data type to declare character variables and store character values:#include <stdio.h> int main() { // Declaring and initializing character variables char grade = 'A'; // Single character char firstInitial = 'J'; char lastInitial = 'D'; // Displaying character variables printf("Grade: %c\n", grade); printf("First Initial: %c\n", firstInitial); printf("Last Initial: %c\n", lastInitial); // Character values can also be assigned as integer ASCII values char letter = 65; // ASCII value for 'A' // Displaying character values as integers printf("Character as an integer: %d\n", letter); return 0; }
In this example: We declare character variables
grade
,firstInitial
, andlastInitial
and initialize them with character values. We use the%c
format specifier to print character values. We can also assign character values using their corresponding ASCII values. The ASCII value of 'A' is 65. We display a character as an integer using the%d
format specifier. When you run this code, you'll see the character values and their corresponding ASCII values printed to the console. Character variables are useful for working with individual characters, such as letters, digits, and symbols, in C programs. -
Derived Data Types:
arrays
: Collections of variables of the same type.structures
: User-defined data types grouping variables of different data types.unions
: Like structures but share memory space for variables.pointers
: Used to store memory addresses.enum
: Defines a set of named integer constants.
-
Void Data Type:
void
: Represents the absence of type. Used when a function doesn't return a value.
Example of variable declarations with data types:
int age;
double salary = 5000.50;
char initial = 'A';
int numbers[5]; // Array of integers
struct Person {
char name[50];
int age;
};
typedef enum { RED, GREEN, BLUE } Color;
These fundamental concepts are essential for understanding and writing C programs, as they govern how data is stored, processed, and manipulated within the language.
In C are used in the printf
and scanf
functions to define the type and format of the data that you want to display or read. They specify how data should be formatted when it's input or output. Here are some commonly used format specifiers in C:
-
Integer Types:
%d
: Print or scan anint
.%u
: Print or scan anunsigned int
.%ld
: Print or scan along
.%lu
: Print or scan anunsigned long
.%lld
: Print or scan along long
.%llu
: Print or scan anunsigned long long
.%x
or%X
: Print or scan an integer in hexadecimal.%o
: Print or scan an integer in octal.
-
Floating-Point Types:
%f
: Print or scan afloat
.%lf
: Print or scan adouble
.%Lf
: Print or scan along double
.%e
or%E
: Print or scan in scientific notation.%g
or%G
: Print or scan in either%f
or%e
, depending on the value.
-
Characters:
%c
: Print or scan a character.%s
: Print or scan a string.
-
Pointers:
%p
: Print an address from a pointer.
-
Size Specifiers:
%zd
: Print or scan asize_t
.%td
: Print or scan aptrdiff_t
.
-
Special Characters:
%%
: Print a percent sign.
-
Width and Precision:
%[width]d
: Print an integer with a minimum field width of[width]
.%.[precision]f
: Print a floating-point number with[precision]
decimal places.
-
Other Format Specifiers:
%n
: Used withprintf
to count the number of characters printed.%*
: Used to specify the width or precision as a variable argument.
Here's an example demonstrating the use of format specifiers in printf
:
#include <stdio.h>
int main() {
int number = 4234;
float floatValue = 3.14159;
char letter = 'A';
char name[20];
printf("Integer: %d\n", number); // 4234
printf("Integer: %2d\n", number); // 42
printf("Float: %*f\n", floatValue); // 3.1
printf("Float: %.2f\n", floatValue); // 3.14
printf("Float: %3.2f\n", floatValue); // 3.14
printf("Character: %c\n", letter);
scanf("%3d %d %*f %5s", &number, &number, &floatValue, text); /* input: 4234 3.7 anisul */
printf("%d %d %s", number, number, text); /* output: 423 4234 anisu */
return 0;
}
This code prints an integer with %d
, a floating-point number with two decimal places using %.2f
, and a character with %c
. These format specifiers are placeholders that printf
will replace with the actual values you provide as arguments.
We can use printf(), puts(), putchar() for output and scanf(), gets(), getchar() for input.
In C, you can get user input from the standard input, typically the keyboard, using the scanf
function. Here's how you can use scanf
to read user input:
#include <stdio.h>
int main() {
int number;
char name[50];
// Prompt the user for input
printf("Enter an integer: ");
scanf("%d", &number);
printf("Enter your name: ");
scanf("%s", name); // Reads a single word (stops at whitespace)
// Display the input
printf("You entered: %d\n", number);
printf("Your name is: %s\n", name);
return 0;
}
In this example:
-
We declare two variables,
number
to store an integer andname
as a character array to store a name. -
We use
printf
to prompt the user for input. -
We use
scanf
to read the input. The format specifier%d
is used to read an integer, and%s
is used to read a string (which stops at whitespace). The&
symbol is used before the variable name to provide the address of the variable where the input should be stored. -
After reading the input, we use
printf
to display the values entered by the user.
When you run the program, the user will be prompted to enter an integer and their name. The values entered by the user are then displayed.
Keep in mind that scanf
can be sensitive to the input format, and it's a good practice to perform error checking on the return value of scanf
to ensure that the input was successfully read.
-
The
gets
function is used to read a line of text from the user. -
The
puts
function is used to display a string.#include <stdio.h> int main() { char name[50]; printf("Enter your name: "); gets(name); // Read a line of text (be cautious, gets is unsafe) printf("Hello, "); puts(name); // Display the name using puts return 0; }
Please note that gets
is considered unsafe because it doesn't limit the number of characters read, potentially causing a buffer overflow. It's recommended to use fgets
instead for safe input.
The fgets
function is commonly used for reading lines of text from the user while ensuring safety by specifying the maximum number of characters to read. Here's an example using fgets
:
#include <stdio.h>
int main() {
char name[50]; // Buffer to store the input
printf("Enter your name: ");
fgets(name, sizeof(name), stdin); // Read a line of text safely
// Remove the newline character if present
size_t len = strlen(name); // size_t is commonly used when dealing with memory allocation, dynamic arrays, and buffer sizes because it ensures that sizes are non-negative and can accommodate the largest possible size on a given system.
if (name[len - 1] == '\n') {
name[len - 1] = '\0';
}
printf("Hello, %s!\n", name); // Display the name
return 0;
}
In this example:
-
We declare a character array
name
to store the input. -
We use
printf
to prompt the user for input. -
We use
fgets
to read a line of text. Thesizeof(name)
specifies the maximum number of characters to read to avoid buffer overflow.stdin
indicates that input should come from the standard input (keyboard). -
After reading the input, we check if a newline character is present at the end of the string and remove it if necessary to ensure proper formatting.
-
Finally, we use
printf
to display the name.
The use of fgets
is recommended over gets
for reading lines of text because it is safer and allows you to specify the maximum number of characters to read, preventing buffer overflow issues.
-
The
getchar
function is used to read a single character from the user. -
The
putchar
function is used to display a character.#include <stdio.h> int main() { char character; printf("Enter a character: "); character = getchar(); // Read a single character printf("You entered: "); putchar(character); // Display the character using putchar putchar('\n'); // Add a newline character return 0; }
-
Conversion between ASCII characters and ASCII Value
ASCII (American Standard Code for Information Interchange) is a character encoding standard that uses numeric codes to represent characters. Each character is assigned a unique numeric code, known as its ASCII value. ASCII values are integers ranging from 0 to 127, and they represent standard characters like letters, digits, punctuation, and control characters.
Decimal ASCII Value Character
0 Null 1 Start of Header 2 Start of Text 3 End of Text 4 End of Transmission 5 Enquiry 6 Acknowledge 7 Bell 8 Backspace 9 Horizontal Tab 10 Line Feed 11 Vertical Tab 12 Form Feed 13 Carriage Return 14 Shift Out 15 Shift In 16 Data Link Escape 17 Device Control 1 18 Device Control 2 19 Device Control 3 20 Device Control 4 21 Negative Acknowledge 22 Synchronous Idle 23 End of Transmission Block 24 Cancel 25 End of Medium 26 Substitute 27 Escape 28 File Separator 29 Group Separator 30 Record Separator 31 Unit Separator 32 Space 33 ! 34 " 35 # 36 $ 37 % 38 & 39 ' 40 ( 41 ) 42 * 43 + 44 , 45 - 46 . 47 / 48-57 0-9 (Digits) 58 : 59 ; 60 < 61 = 62 > 63 ? 64 @ 65-90 A-Z (Uppercase Letters) 91 [ 92
93 ] 94 ^ 95 _ 96 ` 97-122 a-z (Lowercase Letters) 123 { 124 | 125 } 126 ~ 127 Delete
// Convert ASCII characters to ASCII Value
#include <stdio.h>
int main(){
char asciiCharacter;
printf("Enter any character: ");
scanf("%c",&asciiCharacter);
// asciiCharacter = getchar();
printf("The equivalent ascii value: %d\n", asciiCharacter);
}
// Convert ASCII Value to ASCII characters
#include <stdio.h>
int main(){
int asciiValue;
printf("Enter any ASCII value: ");
scanf("%d", &asciiValue);
printf("The equivalent ascii character: %c\n", asciiValue);
}
- Conversion between lowercase and uppercase letter
#include <stdio.h>
int main(){
char lowercaseLetter;
printf("Enter a lowercase letter: ");
scanf("%c", &lowercaseLetter);
printf("Equivalent uppercase letter: %c\n", lowercaseLetter-32);
getchar();
}
#include <stdio.h>
int main(){
char uppercaseLetter;
printf("Enter a uppercase letter: ");
scanf("%c", &uppercaseLetter);
printf("Equivalent lowercase letter: %c\n", uppercaseLetter+32);
getchar();
}
// using library function
#include <stdio.h>
#include <ctype.h>
int main(){
char uppercaseLetter, lowercaseLetter;
printf("Enter a uppercase letter: ");
scanf("%c", &uppercaseLetter);
lowercaseLetter = tolower(uppercaseLetter);
printf("Equivalent lowercase letter: %c\n", lowercaseLetter);
getchar();
}
#include <stdio.h>
#include <ctype.h>
int main(){
char uppercaseLetter, lowercaseLetter;
printf("Enter a lowercase letter: ");
scanf("%c", &lowercaseLetter);
uppercaseLetter = toupper(lowercaseLetter);
printf("Equivalent uppercase letter: %c\n", uppercaseLetter);
getchar();
}
- Conversion between binary, decimal, octal and hexa-decimal numbers
// %d is used to input and output integers in decimal format.
// %o is used to output integers in octal format.
// %x is used to output integers in lowercase hexadecimal format.
#include <stdio.h>
int main() {
int decimalNumber;
// Get input from the user
printf("Enter a decimal number: ");
scanf("%d", &decimalNumber);
// Display the conversions
printf(" %o in octal and %x in hexadecimal.\n", decimalNumber, decimalNumber);
return 0;
}
- There are 3 important types in C. Unary Operators, Binary Operators, ternary operator.
Unary operators in C are operators that perform operations on a single operand (a single variable or value). Here are some common unary operators with examples:
1. Unary Plus +
: This operator doesn't change the sign of a value. It's often not explicitly used because positive values are the default.
int x = 5;
int y = +x; // y is 5, the same as x
2. Unary Minus -
: This operator changes the sign of a value to its negative.
int x = 7;
int y = -x; // y is -7, the negative of x
3. Increment ++
: This operator increases the value of a variable by 1.
int x = 10;
x++; // Increment x by 1, now x is 11
4. Decrement --
: This operator decreases the value of a variable by 1.
int x = 8;
x--; // Decrement x by 1, now x is 7
5. Logical NOT !
: This operator negates a logical (boolean) value. It converts a true value to false and vice versa.
int condition = 0;
int negatedCondition = !condition; // negatedCondition is 1 (true)
6. Bitwise NOT ~
: This operator performs a bitwise NOT operation, inverting all bits of an integer value.
int x = 5; // Binary: 00000101
int y = ~x; // Binary: 11111010, y is -6 in decimal
7. Sizeof sizeof
: This operator returns the size in bytes of a data type or an expression.
int size = sizeof(int); // size is the size of an int (typically 4 bytes)
These unary operators are essential in C programming for tasks like incrementing or decrementing variables, changing signs, and performing logical or bitwise operations on data.
- operators precedence: *, / , % then +, -
1. Arithmetic Operators:
-
Addition
+
: Adds two values.int sum = 5 + 3; // sum is 8
-
Subtraction
-
: Subtracts one value from another.int difference = 10 - 3; // difference is 7
-
Multiplication
*
: Multiplies two values.int product = 4 * 5; // product is 20
-
Division
/
: Divides one value by another.float quotient = 15.0 / 4.0; // quotient is 3.75
-
Modulus
%
: Returns the remainder of a division operation.int remainder = 15 % 4; // remainder is 3
-
Challenge Exercise: Create a Simple Calculator
Write a C program to perform basic arithmetic operations. The program should: Declare variables num1 and num2 to store two input numbers. Declare a variable result to store the result of the operations. Ask the user to input two numbers. Perform the following operations: Addition Subtraction Multiplication Division Print the results of each operation. Enter the first number: 10 Enter the second number: 5 Addition: 10 + 5 = 15 Subtraction: 10 - 5 = 5 Multiplication: 10 * 5 = 50 Division: 10 / 5 = 2
// create a basic calculator
#include <stdio.h>
#include <ctype.h>
int main(){
int num1, num2, result;
float div;
printf("Enter num1 = ");
scanf("%d", &num1);
printf("Enter num2 = ");
scanf("%d", &num2);
result = num1 + num2;
printf("%d + %d = %d\n",num1,num2,result);
result = num1 - num2;
printf("%d - %d = %d\n",num1,num2,result);
result = num1 * num2;
printf("%d * %d = %d\n",num1,num2,result);
div = (float)num1 / num2; // data type casting here
printf("%d / %d = %.2f\n",num1,num2,div);
result = num1 % num2;
printf("%d %% %d = %d\n",num1,num2,result);
getchar();
}
#include <stdio.h>
#include <ctype.h>
int main(){
int num1, num2, num3, sum;
float average;
printf("Enter num1 = ");
scanf("%d", &num1);
printf("Enter num2 = ");
scanf("%d", &num2);
printf("Enter num3 = ");
scanf("%d", &num3);
sum = num1 + num2 + num3;
printf("%d + %d + %d = %d\n",num1,num2,num3,sum);
average = (float)sum/3;
printf("Average = %.2f\n",average);
getchar();
}
#include <stdio.h>
#include <ctype.h>
int main(){
float base, height, area;
printf("Enter base = ");
scanf("%f", &base);
printf("Enter height = ");
scanf("%f", &height);
area = 0.5*base*height;
printf("Area of triangle = %.2f\n",area);
getchar();
}
// Let ABC be a triangle such that the length of the 3 sides of the triangle is AB = c, BC = a and CA = b.
// The semi-perimeter of triangle ABC = s = (a + b + c)/2
// Then, the area of triangle ABC = √[s × (s – a) × (s – b) × (s – c)].
#include <stdio.h>
#include <ctype.h>
#include <math.h>
int main(){
float side1, side2, side3, semiPerimeter, areaWith3Sides;
printf("Enter side1 = ");
scanf("%f", &side1);
printf("Enter side2 = ");
scanf("%f", &side2);
printf("Enter side3 = ");
scanf("%f", &side3);
semiPerimeter = (side1 + side2 + side3) / 2;
areaWith3Sides = sqrt(semiPerimeter * (semiPerimeter-side1) * (semiPerimeter-side2) * (semiPerimeter-side3) );
printf("Area of triangle with 3 sides = %.2f\n",areaWith3Sides);
getchar();
}
// Centigrade to Farhrenheit
#include <stdio.h>
#include <ctype.h>
int main(){
float centigrade, fahrenheit;
printf("Enter centigrade = ");
scanf("%f", ¢igrade);
fahrenheit = (centigrade * 1.8) + 32;
printf("Equivalent Fahrenheit = %.2f\n",fahrenheit);
getchar();
}
// Farhrenheit to Centigrade
#include <stdio.h>
#include <ctype.h>
int main(){
float centigrade, fahrenheit;
printf("Enter fahrenheit = ");
scanf("%f", &fahrenheit);
centigrade = (fahrenheit - 32) / 1.8;
printf("Equivalent centigrade = %.2f\n",centigrade);
getchar();
}
2. Relational Operators:
-
Equal
==
: Tests if two values are equal.int isEqual = (5 == 5); // isEqual is 1 (true)
-
Not Equal
!=
: Tests if two values are not equal.int isNotEqual = (3 != 5); // isNotEqual is 1 (true)
-
Greater Than
>
: Tests if one value is greater than another.int isGreater = (8 > 3); // isGreater is 1 (true)
-
Less Than
<
: Tests if one value is less than another.int isLess = (2 < 5); // isLess is 1 (true)
3. Logical Operators:
-
Logical AND
&&
: Returns true if both conditions are true.int bothTrue = (1 && 1); // bothTrue is 1 (true)
-
Logical OR
||
: Returns true if at least one condition is true.int eitherTrue = (0 || 1); // eitherTrue is 1 (true)
-
Logical NOT
!
: Returns the opposite of a condition.int notTrue = !1; // notTrue is 0 (false)
4. Assignment Operator:
Assignment operators in C are used to assign values to variables. They also allow you to perform operations while assigning values to variables. Here are some common assignment operators with more detailed examples:
- Simple Assignment (
=
):** Assigns the value on the right side to the variable on the left side.
int x = 5; // Assigns the value 5 to variable x
- Addition Assignment (
+=
):** Adds the value on the right to the variable on the left and assigns the result to the variable on the left.
int x = 5;
x += 3; // Equivalent to x = x + 3; x is now 8
3. Subtraction Assignment (-=
): Subtracts the value on the right from the variable on the left and assigns the result to the variable on the left.
int x = 10;
x -= 4; // Equivalent to x = x - 4; x is now 6
- Multiplication Assignment (
*=
):** Multiplies the variable on the left by the value on the right and assigns the result to the variable on the left.
int x = 3;
x *= 2; // Equivalent to x = x * 2; x is now 6
- Division Assignment (
/=
):** Divides the variable on the left by the value on the right and assigns the result to the variable on the left.
int x = 12;
x /= 4; // Equivalent to x = x / 4; x is now 3
- Modulus Assignment (
%=
):** Calculates the remainder of the division of the variable on the left by the value on the right and assigns the result to the variable on the left.
int x = 15;
x %= 7; // Equivalent to x = x % 7; x is now 1
- Bitwise Assignment Operators (e.g.,
&=
,|=
,^=
):** Perform bitwise operations on the variable on the left and the value on the right, then assign the result to the variable on the left.
These assignment operators provide a concise way to update variables by performing arithmetic and bitwise operations simultaneously. They are commonly used to update variables in loops and other situations where values need to be incremented, decremented, or modified in place.
5. Bitwise Operators (e.g., &
, |
, ^
, <<
, >>
):
Bitwise operators in C are used to manipulate individual bits of integer values. They perform bit-level operations, which are especially useful for tasks like setting or clearing specific bits in flags or working with binary data. Here are some common bitwise operators with examples:
1. Bitwise AND &
: Performs a bitwise AND operation, which returns 1 for each bit position where both operands have a 1.
int a = 5; // Binary: 00000101
int b = 3; // Binary: 00000011
int result = a & b; // Binary: 00000001, result is 1
2. Bitwise OR |
: Performs a bitwise OR operation, which returns 1 for each bit position where at least one operand has a 1.
int a = 5; // Binary: 00000101
int b = 3; // Binary: 00000011
int result = a | b; // Binary: 00000111, result is 7
3. Bitwise XOR ^
: Performs a bitwise XOR (exclusive OR) operation, which returns 1 for each bit position where only one operand has a 1.
int a = 5; // Binary: 00000101
int b = 3; // Binary: 00000011
int result = a ^ b; // Binary: 00000110, result is 6
4. Bitwise NOT ~
: Performs a bitwise NOT operation, which inverts each bit (0 to 1 and 1 to 0) in a value.
int a = 5; // Binary: 00000101
int result = ~a; // Binary: 11111010, result is -6 in decimal
5. Left Shift <<
: Shifts the bits of a value to the left by a specified number of positions.
int a = 5; // Binary: 00000101
int result = a << 2; // Binary: 00010100, result is 20
6. Right Shift >>
: Shifts the bits of a value to the right by a specified number of positions. For signed numbers, it fills with the sign bit (arithmetic right shift).
int a = 16; // Binary: 00010000
int result = a >> 2; // Binary: 00000100, result is 4
Bitwise operators are commonly used for low-level operations, such as setting or clearing flags in registers, packing and unpacking data in binary formats, or implementing algorithms that require bit manipulation.
Ternary operators in C are a shorthand way of writing simple conditional statements. They allow you to evaluate an expression and return a value based on whether the expression is true or false. The ternary operator is also known as the conditional operator and has the following syntax:
condition ? value_if_true : value_if_false
The condition
is evaluated first. If it's true, the value_if_true
is returned; otherwise, the value_if_false
is returned. Here's an example:
int x = 10;
int y = (x > 5) ? 20 : 5; // If x is greater than 5, y is assigned 20; otherwise, y is assigned 5.
In this example, x > 5
is the condition. If x
is greater than 5 (which it is in this case), the value 20
is assigned to y
. If the condition were false, the value 5
would be assigned to y
.
Ternary operators are useful when you want to assign a value to a variable based on a simple condition. They can make your code more concise, especially for short conditional assignments, and are often used within larger expressions or when initializing variables.
- Write a program that add 2 integers/floating point number.
- Write a program that add, subtract, multiply, divide 2 integers/floating point number.
- Write algorithm, flowchart and c program that calculate the area of a triangle.
- Write algorithm, flowchart and c program that calculate the area of a triangle, 3 sides length are given.
- Write A,F,C program that calculate the area of a rectangle.
- Write A,F,C program that calculate the area of a circle.
- Write A,F,C program that convert the Celsius temperature to Fahrenheit.
- Write A,F,C program that convert the Fahrenheit temperature to Celsius.
- Write A,F,C program that swaps 2 numbers.
- Write A,F,C program that calculate (a+b)^2 formula; take the values for a and b from user.
In C, you can use the math library, which provides a wide range of mathematical functions for various calculations. To use functions from the math library, you need to include the <math.h> or <stdlib.h>
header. Here's an example that demonstrates how to use some common math library functions:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main() {
// Calculating square root
double number = 25.0;
double squareRoot = sqrt(number);
printf("Square root of %lf is %lf\n", number, squareRoot);
// Calculating power
double base = 2.0;
double exponent = 3.0;
double result = pow(base, exponent);
printf("%lf raised to the power of %lf is %lf\n", base, exponent, result);
// Calculating absolute value
int value = -10;
int absoluteValue = abs(value);
printf("The absolute value of %d is %d\n", value, absoluteValue);
// Rounding functions
double floatingNumber = 3.456;
double roundedDown = floor(floatingNumber);
double roundedUp = ceil(floatingNumber);
printf("Original: %lf, Rounded Down: %lf, Rounded Up: %lf\n", floatingNumber, roundedDown, roundedUp);
return 0;
}
In this example, we include <math.h>
and use functions like sqrt()
, pow()
, abs()
, floor()
, and ceil()
to perform various mathematical calculations. These functions are just a subset of what the math library provides. You can explore more functions for advanced mathematical operations, such as trigonometry, logarithms, and exponential functions.
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int main(){
int number, absoluteNumber;
printf("Enter any negative number = ");
scanf("%d", &number);
absoluteNumber = abs(number);
printf("abs(%d) = %d\n",number, absoluteNumber);
getchar();
}
Conditional control statements in C are used to control the flow of a program based on conditions. They allow you to execute different code blocks based on whether a condition is true or false. There are primarily two types of conditional control statements in C: if
and switch
. Here are examples for both:
The if
statement is used to execute a block of code if a specified condition is true. If the condition is false, the code block is skipped.
#include <stdio.h>
int main() {
int x = 10;
if (x > 5) {
printf("x is greater than 5.\n");
} else {
printf("x is not greater than 5.\n");
}
return 0;
}
In this example, the if
statement checks if x
is greater than 5. If it is, the first block of code is executed. Otherwise, the else
block is executed.
#include <stdio.h>
int main() {
int num = 10;
if (num < 0) {
printf("Number is negative.\n");
} else if (num > 0) {
printf("Number is positive.\n");
} else {
printf("Number is zero.\n");
}
return 0;
}
- Flowchart of if, else if and else statement
- Write a program that read mark and display pass or fail.
- Write a program that read mark and display result in grade.
- Write a program to check a number even or odd.
- Write a program that read mark and display pass or fail.
- Write a program that read mark and display result in grade.
- Write a program to check a number even or odd.
- Write a program to check a number positive or negative.
- Write a program that read two numbers and display maximum.
- Write a program that read two numbers and display minimum.
- Write a program that read three numbers and display maximum.
- Write a program that read three numbers and display minimum.
- Write a program that read three numbers and display medium.
- Write a program that read three numbers (a, b, c) and determine the roots of the quadratic equation.
- Write a program that read any year and display leap or not.
- Write a program that read any letter and display vowel or consonant.
- Write a program that read any letter and display its uppercase or lowercase.
// check if the number is even or odd
#include <stdio.h>
int main()
{
int number;
if (number % 2 == 0)
{
printf("%d is even", number);
}
else
{
printf("%d is odd", number);
}
return 0;
}
// check if the number is positive or negative or zero
#include <stdio.h>
int main()
{
int number;
if (number > 0)
{
printf("positive");
}
else if (number < 0)
{
printf("negative");
}
else
{
printf("zero");
}
return 0;
}
// find largest numer of 2 numbers
#include <stdio.h>
int main()
{
int number1, number2;
printf("Enter two numbers: ");
scanf("%d %d", &number1, &number2);
if (number1 > number2)
{
printf("%d is the largest number\n", number1);
}
else if (number2 > number1)
{
printf("%d is the largest number\n", number2);
}
else
{
printf("Both numbers are equal\n");
}
return 0;
}
// find largest numer of 3 numbers
#include <stdio.h>
int main()
{
int number1, number2, number3;
printf("Enter three numbers: ");
scanf("%d %d %d", &number1, &number2, &number3);
if (number1 > number2 && number1 > number3)
{
printf("%d is the largest number\n", number1);
}
else if (number2 > number1 && number2 > number3)
{
printf("%d is the largest number\n", number2);
}
else if (number3 > number1 && number3 > number2)
{
printf("%d is the largest number\n", number3);
}
else
{
printf("Both numbers are equal\n");
}
return 0;
}
// check a year is a leap year or not
#include <stdio.h>
int main()
{
int year;
printf("Enter a year: ");
scanf("%d", &year);
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
{
printf("%d is a leap year\n", year);
}
else
{
printf("%d is not a leap year\n", year);
}
return 0;
}
// Check a letter is capital letter or small letter or not a letter
#include <stdio.h>
int main()
{
char letter;
printf("Enter a letter: ");
scanf("%c", &letter);
if (letter >= 'A' && letter <= 'Z')
{
printf("%c is a capital letter\n", letter);
}
else if (letter >= 'a' && letter <= 'z')
{
printf("%c is a small letter\n", letter);
}
else
{
printf("%c is not a letter\n", letter);
}
return 0;
}
// Check a letter is vowel or consonant or not a letter
#include <stdio.h>
#include <ctype.h>
int main()
{
char letter;
printf("Enter a letter: ");
scanf("%c", &letter);
letter = tolower(letter);
if (!(letter >= 'a' && letter <= 'z'))
{
printf("%c is not a letter\n", letter);
}
else if (letter == 'a' || letter == 'e' || letter == 'i' || letter == 'o' || letter == 'u')
{
printf("%c is a vowel\n", letter);
}
else
{
printf("%c is a consonant\n", letter);
}
return 0;
}
// Find Letter Grade from a student's mark
#include <stdio.h>
#include <ctype.h>
int main()
{
int mark;
printf("Enter your mark: ");
scanf("%d", &mark);
if (mark > 100 && mark < 0)
{
printf("Invalid mark");
}
else if (mark >= 90 && mark < 100)
{
printf("A+");
}
else if (mark >= 80 && mark < 90)
{
printf("A");
}
else if (mark >= 70 && mark < 80)
{
printf("A-");
}
else if (mark >= 60 && mark < 70)
{
printf("B");
}
else if (mark >= 50 && mark < 60)
{
printf("C");
}
else if (mark >= 40 && mark < 50)
{
printf("D");
}
else
{
printf("F");
}
return 0;
}
The switch
statement allows you to select one of many code blocks to be executed. It's typically used when you have multiple conditions to test.
#include <stdio.h>
int main() {
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
default:
printf("Other day\n");
}
return 0;
}
In this example, the switch
statement checks the value of the day
variable and executes the code block associated with the matching case
. If there's no match, the default
block is executed.
// switch : vowel / consonant program
#include <stdio.h>
#include <ctype.h>
int main()
{
char letter;
printf("Enter a letter: ");
scanf("%c", &letter);
switch (letter)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
printf("Vowel\n");
break;
default:
printf("Consonant\n");
break;
}
return 0;
}
// switch: temperature converter
#include <stdio.h>
#include <ctype.h>
int main()
{
int choice;
printf("Temperature Converter Started");
printf("Choose 1. Fahrenheit to Celsius\n");
printf("Choose 2. Celsius to Fahrenheit\n");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("Enter temperature in Fahrenheit: ");
float fahr;
scanf("%f", &fahr);
float celsius = (fahr - 32) / 1.8;
printf("Temperature in Celsius: %.2f\n", celsius);
break;
case 2:
printf("Enter temperature in Celsius: ");
float celsius;
scanf("%f", &celsius);
float fahr = celsius * 1.8 + 32;
printf("Temperature in Fahrenheit: %.2f\n", fahr);
break;
default:
printf("Invalid choice\n");
break;
}
return 0;
}
// switch: basic calculator
#include <stdio.h>
#include <ctype.h>
int main()
{
int number1, number2;
char operation;
printf("Enter an operation: ");
scanf("%c", &operation);
printf("Enter two numbers: ");
scanf("%d %d", &number1, &number2);
switch (operation){
case '+':
printf("%d + %d = %d\n", number1, number2, number1 + number2);
break;
case '-':
printf("%d - %d = %d\n", number1, number2, number1 - number2);
break;
case '*':
printf("%d * %d = %d\n", number1, number2, number1 * number2);
break;
case '/':
printf("%d / %d = %d\n", number1, number2, number1 / number2);
break;
default:
printf("Invalid operation\n");
break;
}
return 0;
}
- Four import keywords in switch.
- Write a program that read a digit and display by its spelling.
- Write a program that read a year and display leap year or not.
- Write a program that read any letter and display vowel or consonant.
- Write a program that read any number and display its Roman number.
- Write a program that read mark and display pass or fail.
- Write a program to check a number even or odd.
- Write a program that read two numbers and display maximum.
- Write a program that read two numbers and display minimum.
- Write a program that read three numbers and display maximum.
- Write a program that read three numbers and display minimum.
- Write a program that read three numbers and display medium.
In C, there are several types of loops, each designed for different use cases. The common types of loops are:
-
for Loop: The
for
loop is used when you know in advance how many times you want to execute a block of code. It has a loop control variable, initialization, condition, and an increment (or decrement) statement.for (int i = 0; i < 5; i++) { // Code to be executed }
-
while Loop: The
while
loop is used when you want to execute a block of code as long as a condition is true. The condition is checked before each iteration.int i = 0; while (i < 5) { // Code to be executed i++; }
-
do...while Loop: The
do...while
loop is used when you want to execute a block of code at least once and then continue as long as a condition is true. The condition is checked after each iteration.int i = 0; do { // Code to be executed i++; } while (i < 5);
-
Nested Loops: You can have loops inside other loops, creating nested loops. This is often used for tasks that involve two or more levels of iteration.
for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { // Code to be executed } }
-
Infinite Loop: You can create a loop that runs indefinitely using constructs like
while (1)
orfor (;;)
for tasks that need continuous execution.#include <stdio.h> int main() { // indefinite for loop for(;;) { printf("Hello javatpoint"); } // indefinite while loop while (1) { // Code to be executed indefinitely } // indefinite do while loop do{ // body of the loop.. } while(1); return 0; }
Jump control Statement include break
, continue
, and goto
. Here are examples for each:
1. break
Statement:
The break
statement is used to exit a loop prematurely, either a for
, while
, or do...while
loop. It is typically used to terminate a loop based on a certain condition.
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i is 5
}
printf("%d ", i);
}
return 0;
}
In this example, the loop is terminated when i
equals 5, and the program exits the loop early.
2. continue
Statement:
The continue
statement is used to skip the current iteration of a loop and continue with the next iteration. It is often used to avoid certain iterations based on a condition.
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
printf("%d ", i);
}
return 0;
}
In this example, even numbers are skipped, and only odd numbers are printed.
3. goto
Statement:
The goto
statement is used to transfer control to a labeled statement within the same function. It's generally considered bad practice and should be used sparingly, if at all.
#include <stdio.h>
int main() {
int i = 1;
start: // Label
if (i <= 10) {
printf("%d ", i);
i++;
goto start; // Jump to the "start" label
}
return 0;
}
In this example, the program jumps back to the "start" label using goto
to repeat the loop until i
becomes greater than 10.
The break
and continue
statements are commonly used in loops to control the flow of iterations, while the goto
statement is used much less frequently and should be used with caution.
- Write a program to print 1 to 10 by using for, while & do-while loop.
- Find the total sum from 1 to n numbers.
- Write a program to add m to n numbers and display average.
- Check sum outputs from the hand note.
- Write a program to print the numbers from 1 to 100, skip those numbers which are divisible by 3 or 5 but not both.
- Write a while loop to print all the multiples of 5 from 13 to 121 in descending order,
- Write a program to print all odd numbers from 1 to 1000 which are divisible by 3.
- Write a program using while loop that will print all even numbers between 2 to 20.
- Write a program that read any integer and display prime or not.
- Write a program that prints all the prime numbers from m to n.
- Write a program that prints all the prime numbers from m to n and count total prime numbers.
- Write a program that read any positive integer and display sum of its digit.
- Write a program that reads any positive integer and displays its reverse.
- Write a program to check a number is palindrome or not.
- How to check a number is palindrome using for loop.
- Write a program to check given number is Armstrong number.
- Write a program that read two numbers and display LCM and GCD.
- Write a program to print time table of any number.
- Write a program to print the entire time table from m to n.
- Write a program that generates Fibonacci series.
- Write a program that prints all Fibonacci numbers from 1 to n.
- Write a program that can check a number is Fibonacci or not.
- Write a program that read a positive integer and display its factorial.
- Write a program that read any decimal number and display equivalent binary number.
- Write a program that read any decimal number and display equivalent octal number.
- Write a program that read any decimal number and display equivalent hexadecimal number.
- Write a program that read two numbers (x, y) and display xy .
- Write a program that read two numbers (n, r) and display nPr (Permutation).
- Write a program that read two numbers (n, r) and display nCr (Combination).
// check a number is prime or not: first version
#include <stdio.h>
#include <ctype.h>
int main(){
int number, count=0;
printf("Enter a number: ");
scanf("%d", &number);
for(int i=2; i<number; i++){
if(number%i==0){
count=1;
break;
}
}
if(count==0){
printf("%d is a prime number", number);
}else{
printf("%d is not a prime number", number);
}
getchar();
}
// check a number is prime or not: second version
#include <stdio.h>
#include <ctype.h>
int main(){
int number, count=0;
printf("Enter a number: ");
scanf("%d", &number);
if(number<=1){
printf("%d is not a prime number", number);
}else{
for(int i=2; i<number/2; i++){
if(number%i==0){
count=1;
break;
}
}
}
if(count==0){
printf("%d is a prime number", number);
}else{
printf("%d is not a prime number", number);
}
getchar();
}
// check a number is prime or not: third version
#include <stdio.h>
#include <math.h>
#include <ctype.h>
int main(){
int number, count=0;
printf("Enter a number: ");
scanf("%d", &number);
if(number<=1){
printf("%d is not a prime number", number);
}else{
for(int i=2; i<sqrt(number); i++){
if(number%i==0){
count=1;
break;
}
}
}
if(count==0){
printf("%d is a prime number", number);
}else{
printf("%d is not a prime number", number);
}
getchar();
}
// print prime, find total prime numbers, find sum of prime numbers from m to n
#include <stdio.h>
#include <math.h>
#include <ctype.h>
int main(){
int number,count=0, totalPrimeNumbers=0, sumOfPrimeNumbers=0, startingNumber, endingNumber;
printf("Enter starting number: ");
scanf("%d", &startingNumber);
printf("Enter ending number: ");
scanf("%d", &endingNumber);
for(number=startingNumber; number<=endingNumber; number++){
count=0;
if(number <=1){
count=1;
}else{
for(int i=2; i<= sqrt(number); i++){
if(number%i==0){
count=1;
break;
}
}
}
if(count==0){
printf("%d ", number);
totalPrimeNumbers++;
sumOfPrimeNumbers = sumOfPrimeNumbers + number;
}
}
printf("\nTotal prime numbers: %d\n", totalPrimeNumbers);
printf("Sum of prime numbers: %d\n", sumOfPrimeNumbers);
getchar();
}
// using function to separate prime number logic
#include <stdio.h>
#include <ctype.h>
int main(){
int number, sum=0, temp, remainder;
printf("Enter any number: ");
scanf("%d", &number);
temp = number;
while(temp!=0){
remainder = temp%10;
sum = sum + remainder*remainder*remainder;
temp = temp / 10;
}
if(number == sum){
printf("Armstrong number");
}else{
printf("Not Armstrong number");
}
getchar();
}
- an array is a collection of variables of the same type
int numbers1[5]; // Array of 5 integers, uninitialized
int numbers2[] = {85, 90, 78, 92, 88}; // Array initialized with values
int numbers[5] = {10, 20, 30, 40, 50};
printf("%d\n", numbers[0]); // prints 10
// version 1
#include <stdio.h>
int main() {
int numbers[] = {1, 2, 3, 4, 5};
printf("%d\n", numbers[0]);
printf("%d\n", numbers[1]);
printf("%d\n", numbers[2]);
printf("%d\n", numbers[3]);
printf("%d\n", numbers[4]);
return 0;
}
// version 2: print array with loop
#include <stdio.h>
int main() {
int numbers[] = {1, 2, 3, 4, 5};
for(int index=0; index<5; index++){
printf("%d\n", numbers[index]);
}
return 0;
}
// version 3: take user input for an array
#include <stdio.h>
int main() {
int numbers[5];
for(int index=0; index<5; index++){
scanf("%d", &numbers[index]);
}
for(int index=0; index<5; index++){
printf("%d\n", numbers[index]);
}
return 0;
}
// version 4: give instrcution for inputs
The simplest form of an array. Elements are stored in a linear sequence. Accessing elements is done using a single index.
-
linear searching algorithm: Sequentially checks each element of a list until a match is found.
#include <stdio.h> int linearSearch(int arr[], int n, int target) { for (int i = 0; i < n; i++) { if (arr[i] == target) { return i; // Return the index if the target is found } } return -1; // Return -1 if the target is not found } int main() { int numbers[] = {2, 4, 6, 8, 10, 12, 14, 16}; // Calculate the number of elements in the array; sizeof() here returns the size of entire array in bytes int n = sizeof(numbers) / sizeof(numbers[0]); int target = 10; int result = linearSearch(numbers, n, target); if (result != -1) { printf("Element %d found at index %d\n", target, result); } else { printf("Element %d not found in the array\n", target); } return 0; }
#include <stdio.h> int main(){ int numbers[] = {20,40,1,100,98,-4}; int searchNumber = 40; int found = -1; for(int index=0; index<sizeof(numbers)/sizeof(numbers[0]); index++){ if(numbers[index]== searchNumber){ found = index; break; } } if(found == -1){ printf("%d is not found in the array", searchNumber); } else{ printf("%d is found in position %d", searchNumber, found); } return 0; }
-
find the largest and second largest from an unsorted array
#include <stdio.h> void findLargestAndSecondLargest(int arr[], int n) { if (n < 2) { printf("Array should have at least two elements.\n"); return; } int first, second; if (arr[0] > arr[1]) { first = arr[0]; second = arr[1]; } else { first = arr[1]; second = arr[0]; } for (int i = 2; i < n; i++) { if (arr[i] > first) { second = first; first = arr[i]; } else if (arr[i] > second && arr[i] != first) { second = arr[i]; } } printf("Largest Element: %d\n", first); printf("Second Largest Element: %d\n", second); } int main() { int arr[] = {12, 35, 1, 10, 34, 1}; int n = sizeof(arr) / sizeof(arr[0]); findLargestAndSecondLargest(arr, n); return 0; }
This program initializes first and second based on the first two elements of the array. Then, it iterates through the array starting from the third element, updating first and second accordingly. The final values of first and second are the largest and second-largest elements in the array.
-
find the larget and second largest for an sorted array
If the array is sorted in ascending order, finding the largest and second-largest elements becomes simpler. In this case, the largest element will be the last element of the array, and the second-largest element will be the second-to-last element. Here's the modified code:
#include <stdio.h> void findLargestAndSecondLargest(int arr[], int n) { if (n < 2) { printf("Array should have at least two elements.\n"); return; } int first = arr[n - 1]; int second = arr[n - 2]; printf("Largest Element: %d\n", first); printf("Second Largest Element: %d\n", second); } int main() { int arr[] = {1, 10, 12, 34, 35}; int n = sizeof(arr) / sizeof(arr[0]); findLargestAndSecondLargest(arr, n); return 0; }
In this version,
first
is assignedarr[n - 1]
(the last element), andsecond
is assignedarr[n - 2]
(the second-to-last element). There is no need for an additional loop since the array is already sorted.
-
-
bubble searching algorithm: Requires a sorted array. Divides the array in half at each step.
int binarySearch(int arr[], int low, int high, int target) { while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] == target) { return mid; } else if (arr[mid] < target) { low = mid + 1; } else { high = mid - 1; } } return -1; }
-
Bubble sort: Repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order.
void bubbleSort(int arr[], int n) { for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { // Swap arr[j] and arr[j+1] int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } }
-
Merge sort: Divides the array into two halves, recursively sorts them, and then merges the two sorted halves.
void merge(int arr[], int l, int m, int r) { // Merge two subarrays of arr[] // ... } void mergeSort(int arr[], int l, int r) { if (l < r) { int m = l + (r - l) / 2; mergeSort(arr, l, m); mergeSort(arr, m + 1, r); merge(arr, l, m, r); } }
-
Quick sort: Picks a 'pivot' element and partitions the array into two subarrays according to whether elements are less than or greater than the pivot.
Represents a table of elements arranged in rows and columns. Accessing elements requires two indices.
// program: a simple matrix
#include <stdio.h>
int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Accessing and printing elements
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
// program: add two matrices and store the result in a third matrix
#include <stdio.h>
// Function to add two matrices and store the result in a third matrix
void addMatrices(int first[10][10], int second[10][10], int result[10][10], int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = first[i][j] + second[i][j];
}
}
}
// Function to display a matrix
void displayMatrix(int matrix[10][10], int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
int main() {
int firstMatrix[10][10], secondMatrix[10][10], resultMatrix[10][10];
int rows, cols;
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);
// Input for the first matrix
printf("Enter elements of the first matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &firstMatrix[i][j]);
}
}
// Input for the second matrix
printf("Enter elements of the second matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &secondMatrix[i][j]);
}
}
// Call the function to add matrices
addMatrices(firstMatrix, secondMatrix, resultMatrix, rows, cols);
// Display the matrices and their sum
printf("\nFirst Matrix:\n");
displayMatrix(firstMatrix, rows, cols);
printf("\nSecond Matrix:\n");
displayMatrix(secondMatrix, rows, cols);
printf("\nSum of Matrices:\n");
displayMatrix(resultMatrix, rows, cols);
return 0;
}
#include <stdio.h>
#define MAX 10
int isIdentityMatrix(int matrix[MAX][MAX], int n) {
// Check for square matrix
if (n != n)
return 0;
// Check for identity matrix
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if ((i == j && matrix[i][j] != 1) || (i != j && matrix[i][j] != 0))
return 0;
return 1;
}
int main() {
int matrix[MAX][MAX];
int n;
printf("Enter the size of the square matrix: ");
scanf("%d", &n);
printf("Enter the elements of the matrix:\n");
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
scanf("%d", &matrix[i][j]);
if (isIdentityMatrix(matrix, n))
printf("The matrix is an identity matrix.\n");
else
printf("The matrix is not an identity matrix.\n");
return 0;
}
-
Multi dimensional array (>2D) Arrays with more than two dimensions. Used for complex data structures.
int partition(int arr[], int low, int high) { // ... } void quickSort(int arr[], int low, int high) { if (low < high) { int pi = partition(arr, low, high); quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } }
-
C does not have a built-in string data type like some other programming languages; rather, strings are represented as arrays of characters. The array is terminated by a null character ('\0'), which indicates the end of the string.
-
How to decalre, initialize and print a string?
// method 1
#include <stdio.h>
#include <ctype.h>
int main()
{
char name[5];
name[0] = 'a';
name[1] = 'n';
name[2] = 'i';
name[3] = 's';
name[4] = '\0'; // null character
printf("Name = %s\n", name);
return 0;
}
// method 2
#include <stdio.h>
#include <ctype.h>
int main()
{
char name[5] = {'A', 'n', 'i', 's', '\0'};
printf("Name = %s\n", name);
return 0;
}
// method 3
#include <stdio.h>
#include <ctype.h>
int main()
{
char name[5] = "Anis";
printf("Name = %s\n", name);
return 0;
}
// method 4 - multiple line
#include <stdio.h>
#include <ctype.h>
int main()
{
char name[5] = "Anis \
Islam"; // line break
printf("Name = %s\n", name);
return 0;
}
- how to take string as user input
// method 1
#include <stdio.h>
#include <ctype.h>
int main()
{
char name[20];
printf("Enter your Full name: ");
gets(name);
printf("Full Name: %s\n", name);
return 0;
}
// method 2
#include <stdio.h>
#include <ctype.h>
int main()
{
char name[20];
printf("Enter your Full name: ");
fgets(name, sizeof(name), stdin);
printf("Full Name: %s\n", name);
return 0;
}
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int vowelsCount = 0;
int consonantsCount = 0;
int digitsCount = 0;
int wordsCount = 0;
int specialCharsCount = 0;
int spacesCount = 0;
int uppercaseCount = 0;
int lowercaseCount = 0;
// Input a string from the user
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
// Iterate through each character in the string
for (int i = 0; str[i] != '\0'; ++i) {
char currentChar = str[i];
// Check for vowels (case-insensitive)
char lowerChar = tolower(currentChar);
if (lowerChar == 'a' || lowerChar == 'e' || lowerChar == 'i' ||
lowerChar == 'o' || lowerChar == 'u') {
++vowelsCount;
}
// Check for consonants (alphabets excluding vowels)
if (isalpha(currentChar) && !isvowel(lowerChar)) {
++consonantsCount;
}
// Check for digits
if (isdigit(currentChar)) {
++digitsCount;
}
// Check for spaces
if (isspace(currentChar)) {
++spacesCount;
}
// Check for words
if (isalpha(currentChar) && (i == 0 || !isalpha(str[i - 1]))) {
++wordsCount;
}
// Check for special characters -> isalnum means isalphanumeric or not
// An alphanumeric character is either a letter (uppercase or lowercase) or a digit (0-9).
if (!isalnum(currentChar) && !isspace(currentChar)) {
++specialCharsCount;
}
// Check for uppercase and lowercase letters
if (isalpha(currentChar)) {
if (isupper(currentChar)) {
++uppercaseCount;
} else {
++lowercaseCount;
}
}
}
// Output the results
printf("Number of vowels: %d\n", vowelsCount);
printf("Number of consonants: %d\n", consonantsCount);
printf("Number of digits: %d\n", digitsCount);
printf("Number of words: %d\n", wordsCount);
printf("Number of special characters: %d\n", specialCharsCount);
printf("Number of spaces: %d\n", spacesCount);
printf("Number of uppercase letters: %d\n", uppercaseCount);
printf("Number of lowercase letters: %d\n", lowercaseCount);
return 0;
}
int isvowel(char c) {
return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
}
#include <stdio.h>
#include <string.h>
int main() {
// Example 1: strlen
char str1[] = "Hello, World!";
printf("Length of '%s': %zu\n", str1, strlen(str1));
// Example 2: strcpy
char str2[20];
strcpy(str2, "Copy me!");
printf("Copied string: %s\n", str2);
// Example 3: strcat
char str3[30] = "Hello";
strcat(str3, ", World!");
printf("Concatenated string: %s\n", str3);
// Example 4: strcmp
char str4[] = "apple";
char str5[] = "orange";
int result = strcmp(str4, str5);
printf("Comparison result: %d\n", result);
// Example 5: strchr
char str6[] = "Hello, World!";
char *found = strchr(str6, 'W');
if (found != NULL) {
printf("Found 'W' at position: %ld\n", found - str6);
} else {
printf("Character not found.\n");
}
// Example 6: strstr
char str7[] = "This is a sample string.";
char *substring = strstr(str7, "sample");
if (substring != NULL) {
printf("Substring found: %s\n", substring);
} else {
printf("Substring not found.\n");
}
// Example 7: strtok
char str8[] = "apple,orange,banana";
char *token = strtok(str8, ",");
while (token != NULL) {
printf("Token: %s\n", token);
token = strtok(NULL, ",");
}
return 0;
}
- my program that I have created during the live session
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int isVowel(char letter)
{
return (letter == 'a' || letter == 'e' || letter == 'i' || letter == 'o' || letter == 'u');
}
int isLetter(char ch)
{
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}
int isDigit(char ch)
{
return ch >= '0' && ch <= '9';
}
int isSpace(char ch)
{
return ch == ' ';
}
int main()
{
char text[] = "I love";
printf("Length of text : %d\n", strlen(text));
char text2[30];
printf("text2 = %s\n", strcpy(text2, text));
char password[] = "A123456";
char confirmedPassword[] = "A123456";
int result = strcmp(password, confirmedPassword);
printf("comparision result = %d\n", result);
int numberOfLetters = 0;
int numberOfDigits = 0;
int numberOfSpaces = 0;
int numberOfWords = 0;
int numberOfVowels = 0;
int numberOfConsonants = 0;
int numberOfSpecialCharacters = 0;
for (int index = 0; text[index] != '\0'; index++)
{
char currentCharacter = text[index];
// is letter or not
if (isLetter(currentCharacter))
{
numberOfLetters++;
}
if (isdigit(currentCharacter))
{
numberOfDigits++;
}
if (isspace(currentCharacter))
{
numberOfSpaces++;
}
// convert lowercase
currentCharacter = tolower(currentCharacter);
if (isVowel(currentCharacter))
{
numberOfVowels++;
}
if (isLetter(currentCharacter) && !isVowel(currentCharacter))
{
numberOfConsonants++;
}
// not alphanumeric -> letter and digit and not space
if (!(isalnum(currentCharacter) || isspace(currentCharacter)))
{
numberOfSpecialCharacters++;
}
}
printf("Number of letters : %d\n", numberOfLetters);
printf("Number of Digits : %d\n", numberOfDigits);
printf("Number of Spaces : %d\n", numberOfSpaces);
printf("Number of Words : %d\n", numberOfSpaces + 1);
printf("Number of Vowels : %d\n", numberOfVowels);
printf("Number of Consonants : %d\n", numberOfConsonants);
printf("Number of special characters : %d\n", numberOfSpecialCharacters);
return 0;
}
// number of letters
A function is a block of code that performs a specific task or set of tasks. Functions provide a way to modularize code, making it more organized, reusable, and easier to understand. Here are the key components and concepts related to functions in C:
// Function Declaration
int add(int a, int b);
// Function Definition
int add(int a, int b) {
return a + b;
}
In the above example, add
is a function that takes two integer parameters (a
and b
) and returns an integer result.
int result = add(5, 3);
This line calls the add
function with arguments 5
and 3
and assigns the result (8
) to the variable result
.
// Function with no parameters and no return value
void greet() {
printf("Hello, World!\n");
}
// Function with parameters and a return value
int multiply(int x, int y) {
return x * y;
}
// Function Prototype
int divide(int x, int y);
// Function Definition
int divide(int x, int y) {
return x / y;
}
Function prototypes declare the existence of a function before its actual definition. This is useful when functions are defined later in the code.
#include <stdio.h>
// Function to check if a character is a vowel or consonant
void checkVowelOrConsonant(char ch) {
// Convert the character to lowercase for case-insensitive comparison
ch = tolower(ch);
// Check if the character is a vowel or consonant
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
printf("%c is a vowel.\n", ch);
} else {
printf("%c is a consonant.\n", ch);
}
} else {
printf("Invalid input. Please enter an alphabetic character.\n");
}
}
int main() {
char userInput;
// Get a character from the user
printf("Enter a character: ");
scanf(" %c", &userInput);
// Call the function and pass the character
checkVowelOrConsonant(userInput);
return 0;
}
#include <stdio.h>
// Function to print the elements of an integer array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
// Declare and initialize an array
int numbers[] = {1, 2, 3, 4, 5};
// Calculate the size of the array
int size = sizeof(numbers) / sizeof(numbers[0]);
// Call the function and pass the array
printArray(numbers, size);
return 0;
}
#include <stdio.h>
// Function to print the elements of a 2D array
void print2DArray(int arr[][3], int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
int main() {
// Declare and initialize a 2D array
int matrix[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
// Call the function and pass the 2D array along with its dimensions
print2DArray(matrix, 3, 3);
return 0;
}
// Recursive Function to calculate factorial
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
A recursive function is a function that calls itself. The factorial
function calculates the factorial of a number using recursion.
int globalVariable = 10; // Global variable
void exampleFunction() {
int localVariable = 5; // Local variable
printf("%d\n", globalVariable + localVariable);
}
int main() {
exampleFunction();
return 0;
}
Variables can have local scope (inside a function) or global scope (accessible throughout the program).
These are some fundamental aspects of functions in C programming. Let me know if you'd like more specific examples or details on any particular aspect!
- structure is a collection of variables of different types under a single name.
- structure is a user defined data (your own data type) type in C/C++.
// global structure basic syntax
#include <stdio.h>
#include <ctype.h>
struct Person
{
int age;
float salary;
};
int main()
{
struct Person anis, nusrat;
anis.age = 33;
anis.salary = 3300;
nusrat.age = 33;
nusrat.salary = 3300;
printf("Age: %d\n", anis.age);
printf("Salary: %.2f\n", anis.salary);
return 0;
}
// number of letters
- how to get input for structure
#include <stdio.h>
#include <ctype.h>
struct Person
{
char name[50];
int age;
float salary;
};
int main()
{
struct Person anis, nusrat;
strcpy(anis.name, "anis");
printf("Enter age for anis: ");
scanf("%d", &anis.age);
printf("Enter salary for anis: ");
scanf("%f", &anis.salary);
printf("Age: %d\n", anis.age);
printf("Salary: %.2f\n", anis.salary);
return 0;
}
// number of letters
- how to initialize structure directly
#include <stdio.h>
#include <ctype.h>
struct Person
{
char name[50];
int age;
float salary;
};
int main()
{
struct Person p1 = {"anis", 33, 3100};
struct Person p2 = p1;
printf("Age: %d\n", p1.age);
printf("Salary: %.2f\n", p1.salary);
return 0;
}
- struct comparison
#include <stdio.h>
#include <ctype.h>
struct Person
{
char name[50];
int age;
float salary;
};
int main()
{
struct Person p1 = {"anis", 33, 3100};
struct Person p2 = p1;
if (p1.age == p2.age && p1.name == p2.name)
{
printf("Equal");
}
else
{
printf("Not Equal");
}
return 0;
}
// number of letters
- Array of structure & structure passing to a function
#include <stdio.h>
#include <ctype.h>
struct Person
{
char name[50];
int age;
float salary;
};
void display(struct Person person)
{
printf("Name = %s\n", person.name);
printf("Age = %d\n", person.age);
printf("Salary = %.2f\n", person.salary);
}
int main()
{
struct Person person[4];
int i;
for (i = 1; i <= 4; i++)
{
printf("Enter information for person %d\n", i + 1);
printf("Enter name: ");
fflush(stdin);
gets(person[i].name);
printf("Enter age: ");
scanf("%d", &person[i].age);
printf("Enter salary: ");
scanf("%f", &person[i].salary);
}
for (i = 1; i <= 4; i++)
{
printf("information for person %d\n", i + 1);
display(person[i])
}
return 0;
}
// number of letters
- Example of a structure
#include <stdio.h>
#include <ctype.h>
struct Student
{
char name[50];
int age;
float cgpa;
};
void printStudentInfo(struct Student student)
{
// printing student info
printf("Name = %s\n", student.name);
printf("Age = %d\n", student.age);
printf("CGPA = %.2f\n", student.cgpa);
}
int main()
{
struct Student students[4];
for (int index = 0; index < 4; index++)
{
printf("Enter Name: ");
fflush(stdin);
gets(students[index].name);
printf("Enter age: ");
scanf("%d", &students[index].age);
printf("Enter cgpa: ");
scanf("%f", &students[index].cgpa);
}
for (int index = 0; index < 4; index++)
{
printf("information for student %d\n", index + 1);
printStudentInfo(students[index]);
}
getchar();
}
// why do we need structure?
// how to create a structre?
// how to access a structure?
// how to take user input for a structure?
// how to pass structure as a paramter into a function
// array of structure
- A pointer is a variable that stores the memory address (unsigned or postive integer) of another variable. Pointers are powerful features of the C/C++ language, this feature differentiates C/C++ from other languages such as Java/Python.
- allowing you to directly manipulate memory and work with data structures efficiently.
- but excessive usage may make the program less undesratable.
int *ptr; // Declares a pointer to an integer
int x = 10;
int *ptr = &x; // Intitializing a pointer. Pointer ptr now holds the address of variable x
int x = 10;
int *ptr = &x; // Accessing values through a pointer
printf("Value of x: %d\n", *ptr); // Prints the value of x, which is 10
- swapping 2 numbers using pointer
#include <stdio.h>
#include <stdlib.h>
int main()
{
int number1 = 10, number2 = 20, temp;
int *ptr1, *ptr2;
ptr1 = &number1;
ptr2 = &number2;
temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
printf("number1 = %d\n", number1);
printf("number2 = %d\n", number2);
}
- swapping two numbers using pointers + function
#include <stdio.h>
#include <stdlib.h>
void swap(int *ptr1, int *ptr2)
{
int temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
}
int main()
{
int number1 = 10, number2 = 20, temp;
printf("before swapping: \n");
printf("number1 = %d\n", number1);
printf("number2 = %d\n", number2);
int *ptr1, *ptr2;
swap(&number1, &number2);
printf("After swapping: \n");
printf("number1 = %d\n", number1);
printf("number2 = %d\n", number2);
}
- sum of 2 numbers using pointers
#include <stdio.h>
int main()
{
int number1 = 10;
int number2 = 20;
int *ptr1 = &number1;
int *ptr2 = &number2;
int sum = *ptr1 + *ptr2;
printf("Sum of numbers = %d\n", sum);
}
// Another version
#include <stdio.h>
// Function to calculate the sum of two numbers using pointers
int sum(int *ptr1, int *ptr2) {
return (*ptr1) + (*ptr2);
}
int main() {
int number1 = 10;
int number2 = 20;
int *ptr1 = &number1; // Pointer to number1
int *ptr2 = &number2; // Pointer to number2
// Call the sum function with pointers as arguments
int result = sum(ptr1, ptr2);
printf("Sum of numbers = %d\n", result);
return 0;
}
- accessing arrays using pointer and arithmetic operation
#include <stdio.h>
#include <stdlib.h>
int main()
{
int numbers[5] = {10, 20, 30, 40, 50};
int *ptr = &numbers[0];
printf("%d\n", *ptr);
printf("%d\n", *ptr + 1);
printf("%d\n", *(ptr + 1));
printf("%d\n", *(ptr + 2));
printf("%d\n", *(ptr + 3));
printf("%d\n", *(ptr + 4));
}
- dynamic memory allocation: Pointers are commonly used with functions like malloc() and free() for dynamic memory allocation:
int *ptr = (int *)malloc(sizeof(int)); // Allocates memory for an integer
*ptr = 10; // Assigns a value to the allocated memory
free(ptr); // Deallocates the memory
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr1 = (int *)malloc(sizeof(int)); // Allocates memory for an integer
int *ptr2 = (int *)malloc(sizeof(int));
*ptr1 = 10; // Assigns a value to the allocated memory
*ptr2 = 20;
int sum = *ptr1 + *ptr2;
printf("Sum of numbers = %d\n", sum);
free(ptr1); // Deallocates the memory
free(ptr2); // Deallocates the memory
// Another complex example of dynamic memory allocation for an array increasing size during run time
#include <stdio.h>
#include <stdlib.h>
int main() {
int *dynamicArray = NULL; // Pointer to dynamically allocated memory
int size = 0; // Current size of the dynamic array
int capacity = 2; // Initial capacity of the dynamic array
// Allocate memory for the dynamic array
dynamicArray = (int *)malloc(capacity * sizeof(int));
// Check if memory allocation was successful
if (dynamicArray == NULL) {
printf("Memory allocation failed\n");
return 1;
}
// Prompt the user to enter numbers until they input -1
int num;
printf("Enter numbers (-1 to stop):\n");
while (1) {
scanf("%d", &num);
if (num == -1) {
break;
}
// Resize the dynamic array if necessary
if (size == capacity) {
capacity *= 2;
dynamicArray = (int *)realloc(dynamicArray, capacity * sizeof(int));
if (dynamicArray == NULL) {
printf("Memory reallocation failed\n");
return 1;
}
}
// Add the new number to the dynamic array
dynamicArray[size++] = num;
}
// Print the elements of the dynamic array
printf("Dynamic array elements:\n");
for (int i = 0; i < size; i++) {
printf("%d ", dynamicArray[i]);
}
printf("\n");
// Free dynamically allocated memory
free(dynamicArray);
return 0;
}
}
- static vs dynamic memory allocation - Key Differences: - Static memory allocation occurs at compile time, while dynamic memory allocation occurs at runtime. - Static memory allocation is done on the stack, while dynamic memory allocation is done on the heap. - The size of statically allocated memory must be known at compile time, whereas the size of dynamically allocated memory can be determined at runtime. - Static memory allocation is more straightforward but less flexible, while dynamic memory allocation allows for more flexibility but requires manual memory management.
Dynamic Memory Allocation (malloc/free):
- Advantages:
- Allows you to allocate memory at runtime, which can be useful when the size of data is not known at compile time.
- Helps manage memory efficiently by allocating only what is needed, reducing memory wastage.
- Disadvantages:
- Requires explicit memory management (using
malloc
andfree
), which can lead to memory leaks or segmentation faults if not done properly. - Can be slower than static memory allocation due to the overhead of managing memory at runtime.
- Requires explicit memory management (using
Static Memory Allocation (stack allocation):
- Advantages:
- Memory is allocated and deallocated automatically by the compiler, simplifying memory management.
- Generally faster than dynamic memory allocation as allocation and deallocation are done at compile time.
- Disadvantages:
- Limited flexibility since the size of data must be known at compile time.
- Stack memory is typically smaller than the heap, so it might not be suitable for large data structures.
Which One Is Better:
- For simple programs or when the size of data is known at compile time, static memory allocation can be preferred due to its simplicity and efficiency.
- For more complex programs where the size of data is not known in advance or when memory needs to be dynamically allocated and deallocated during program execution, dynamic memory allocation is necessary.
In summary, there's no definitive answer to which approach is better. It depends on the specific requirements, constraints, and performance considerations of your program. Both dynamic and static memory allocation have their place in software development, and the choice between them should be made based on the particular needs of your application.
-
not storing data
# include <stdio.h> int main() { char name[50]; char phone[50]; char email[50]; printf("Enter Name: "); fgets(name, sizeof name, stdin); printf("Enter Phone: "); fgets(phone, sizeof phone, stdin); printf("Enter Email: "); fgets(email, sizeof email, stdin); printf("Contacts.\n "); printf("Name: %s\nPhone: %s\nEmail: %s\n", name, phone, email); return 0; } ```
-
File is a place for storing data. In C programming, file system operations are facilitated through the Standard I/O Library (stdio.h). This library provides functions to perform various operations on files, such as creating, opening, reading, writing, and closing files.
-
functions which help us to do write operations: fputc, fputw, fprintf, fputs, fwrite
-
functions which help us to do read operations: fgetc, fgetw, fscanf, fgetss, fread
-
how to declare a file:
FILE *nameOfTheFile
file pointer variable -
how to create and close a file in c
#include <stdio.h> int main() { FILE *file; // `FILE *nameOfTheFile` file pointer variable file = fopen("contact.txt", "a"); // fopen(name of the file, mode of file- r, w, a, r+, w+, a+); if (file == NULL) { printf("The contact file is created.\n"); return; } else { printf("The contact file is not created.\n"); fclose(file); } // char name[50]; // char phone[50]; // char email[50]; // printf("Enter Name: "); // fgets(name, sizeof name, stdin); // printf("Enter Phone: "); // fgets(phone, sizeof phone, stdin); // printf("Enter Email: "); // fgets(email, sizeof email, stdin); // printf("Contacts.\n "); // printf("Name: %s\nPhone: %s\nEmail: %s\n", name, phone, email); // return 0; }
-
how to write strings in a file using fprintf()
#include <stdio.h> int main() { char name[50]; char phone[50]; char email[50]; FILE *file; file = fopen("contact.txt", "a"); if (file == NULL) { printf("Unable to open the contact file.\n"); return 0; } else { // writing to a file printf("The contact file is open.\n"); fflush(stdin); printf("Enter Name: "); fgets(name, sizeof name, stdin); printf("Enter Phone: "); fgets(phone, sizeof phone, stdin); printf("Enter Email: "); fgets(email, sizeof email, stdin); // Write contact details to file fprintf(file, "%s%s%s\n", name, phone, email); fclose(file); printf("Contact added successfully.\n"); } }
-
how to read a file using fscanf
#include <stdio.h> int main() { char name[50]; char phone[50]; char email[50]; FILE *file; file = fopen("contact.txt", "r"); if (file == NULL) { printf("Unable to open the contact file.\n"); return 0; } else { // read from a file printf("Contacts:\n"); // It tells fscanf to read strings until it encounters a newline character \n, but it skips leading whitespace characters. This allows it to read strings containing spaces. while (fscanf(file, " %[^\n] %[^\n] %[^\n]", name, phone, email) != EOF) { printf("Name: %s\nPhone: %s\nEmail: %s\n\n", name, phone, email); } fclose(file); // write a contact to a file // printf("The contact file is open.\n"); // fflush(stdin); // printf("Enter Name: "); // fgets(name, sizeof name, stdin); // printf("Enter Phone: "); // fgets(phone, sizeof phone, stdin); // printf("Enter Email: "); // fgets(email, sizeof email, stdin); // // Write contact details to file // fprintf(file, "%s %s %s\n", name, phone, email); // fclose(file); // printf("Contact added successfully.\n"); } }
-
create functions to separate read and write
#include <stdio.h> void addContact() { char name[50]; char phone[50]; char email[50]; FILE *file; file = fopen("contact.txt", "a"); if (file == NULL) { printf("Unable to open the contact file.\n"); return; } else { // write a contact to a file fflush(stdin); printf("Enter Name: "); fgets(name, sizeof name, stdin); printf("Enter Phone: "); fgets(phone, sizeof phone, stdin); printf("Enter Email: "); fgets(email, sizeof email, stdin); // Write contact details to file fprintf(file, "%s%s%s\n", name, phone, email); fclose(file); printf("Contact added successfully.\n"); } } void displayContacts() { char name[50]; char phone[50]; char email[50]; FILE *file; file = fopen("contact.txt", "r"); if (file == NULL) { printf("Unable to open the contact file.\n"); return; } else { printf("Contacts:\n"); while (fscanf(file, " %[^\n] %[^\n] %[^\n]", name, phone, email) != EOF) { printf("Name: %s\nPhone: %s\nEmail: %s\n\n", name, phone, email); } fclose(file); } } int main() { addContact(); displayContacts(); }
-
create a structure to make this more easier
#include <stdio.h>
// Structure to represent a contact
typedef struct
{
char name[50];
char phone[20];
char email[50];
} Contact;
void addContact()
{
Contact newContact;
FILE *file;
file = fopen("contact.txt", "a");
if (file == NULL)
{
printf("Unable to open the contact file.\n");
return;
}
else
{
// write a contact to a file
fflush(stdin);
printf("Enter Name: ");
fgets(newContact.name, sizeof newContact.name, stdin);
printf("Enter Phone: ");
fgets(newContact.phone, sizeof newContact.phone, stdin);
printf("Enter Email: ");
fgets(newContact.email, sizeof newContact.email, stdin);
// Write contact details to file
fprintf(file, "%s%s%s\n", newContact.name, newContact.phone, newContact.email);
fclose(file);
printf("Contact added successfully.\n");
}
}
void displayContacts()
{
Contact contact;
FILE *file;
file = fopen("contact.txt", "r");
if (file == NULL)
{
printf("Unable to open the contact file.\n");
return;
}
else
{
printf("Contacts:\n");
while (fscanf(file, " %[^\n] %[^\n] %[^\n]", contact.name, contact.phone, contact.email) != EOF)
{
printf("Name: %s\nPhone: %s\nEmail: %s\n\n", contact.name, contact.phone, contact.email);
}
fclose(file);
}
}
int main()
{
addContact();
displayContacts();
}
- Finally lets add some choices here
int main()
{
int choice;
do
{
printf("\nContact Management System\n");
printf("1. Add Contact\n");
printf("2. Display Contacts\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
addContact();
break;
case 2:
displayContacts();
break;
case 3:
printf("Exiting...\n");
break;
default:
printf("Invalid choice. Please try again.\n");
}
} while (choice != 3);
return 0;
}
- Final version of Contact Management System
#include <stdio.h>
struct Contact
{
char name[50];
char phone[50];
char email[50];
};
void addContact()
{
FILE *file;
file = fopen("contact.txt", "a");
if (file == NULL)
{
printf("File does not exist or could not be created");
}
else
{
struct Contact contact;
fflush(stdin);
printf("Enter Name: ");
fgets(contact.name, sizeof contact.name, stdin);
printf("Enter Phone: ");
fgets(contact.phone, sizeof contact.phone, stdin);
printf("Enter Email: ");
fgets(contact.email, sizeof contact.email, stdin);
// write to the file
fprintf(file, "%s%s%s\n", contact.name, contact.phone, contact.email);
fclose(file);
printf("Added to Contact Management System\n");
}
}
void displayContacts()
{
struct Contact contact;
FILE *file;
file = fopen("contact.txt", "r");
if (file == NULL)
{
printf("File does not exist or could not be created");
}
else
{
printf("Contacts.\n");
while (fscanf(file, " %[^\n] %[^\n] %[^\n]", contact.name, contact.phone, contact.email) != EOF)
{
printf("Name: %s\nPhone: %s\nEmial: %s\n\n", contact.name, contact.phone, contact.email);
}
fclose(file);
}
}
int main()
{
int choice;
do
{
printf("\nContact Management System\n");
printf("1. Add Contact\n");
printf("2. Display Contacts\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
addContact();
break;
case 2:
displayContacts();
break;
case 3:
printf("Exiting...\n");
break;
default:
printf("Invalid Choice. Please try again.\n");
}
} while (choice != 3);
}