- Notifications
You must be signed in to change notification settings - Fork0
learnwithfair/c-programming-documentation
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
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 developoperating 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 |
![]() |
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>intmain(){printf("hello world");return0;}
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>intmain() {// This is a single-line commentprintf("Hello, World!\n");// This comment is at the end of the line/* This is a multi-line comment */return0;}
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>intmain() {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");return0;}
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 structbreak else long switchcase enum register typedefchar extern return unionconst float short unsignedcontinue for signed voiddefault goto sizeof volatiledo 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>intmain(){printf("Math Marks: 80\n");printf("Computer Marks: 60\n");printf("English Marks: 70\n");return0;}
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>intmain(){intmath=80;intbangla=60;intenglish=70;return0;}
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 examplesintnumberOfStudents;charstudentName[50];constintMAX_ATTEMPTS=3;// Avoid using single letters and cryptic namesintn;// Avoid using single letters like 'n'intx;// Avoid cryptic variable names// Meaningful names and clear intentdoubletemperatureCelsius;charcustomerAddress[100];// Consistent style and camel caseinttotalSalesCount;
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 specifiersDateofbirth-12/03/19901.define3variablestostore2.output1day=12,month=3,year=1990day=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,647intmyInt;// Declaration of an integer variable
short
(orshort int
): - Common memory size: 2 bytes (16 bits) - Typical range: -32,768 to 32,767shortmyShort;// 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)longmyLong;// 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 longmyLongLong;// 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).signedintmySignedInt;// A signed integer can store positive and negativeunsignedintmyUnsignedLongLong;// An unsigned can store only positive values#include<stdio.h>intmain() {signedintpositiveNumber=42;signedintnegativeNumber=-10;printf("Positive Number: %d\n",positiveNumber);printf("Negative Number: %d\n",negativeNumber);return0;}
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.4e38floatmyFloat;// Declaration of a floating-point variable
double
: - Common memory size: 8 bytes (64 bits) - Typical range: Approximately 1.7e-308 to 1.7e308doublemyDouble;// 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 precisionlongdoublemyLongDouble;// 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(longdouble));
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>intmain() {// Declaring and initializing character variableschargrade='A';// Single charactercharfirstInitial='J';charlastInitial='D';// Displaying character variablesprintf("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 valuescharletter=65;// ASCII value for 'A'// Displaying character values as integersprintf("Character as an integer: %d\n",letter);return0;}
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:
intage;doublesalary=5000.50;charinitial='A';intnumbers[5];// Array of integersstructPerson {charname[50];intage;};typedefenum {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 theprintf
andscanf
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 inprintf
:
#include<stdio.h>intmain() {intnumber=4234;floatfloatValue=3.14159;charletter='A';charname[20];printf("Integer: %d\n",number);// 4234printf("Integer: %2d\n",number);// 42printf("Float: %*f\n",floatValue);// 3.1printf("Float: %.2f\n",floatValue);// 3.14printf("Float: %3.2f\n",floatValue);// 3.14printf("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 */return0;}
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 thatprintf
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 thescanf
function. Here's how you can usescanf
to read user input:
#include<stdio.h>intmain() {intnumber;charname[50];// Prompt the user for inputprintf("Enter an integer: ");scanf("%d",&number);printf("Enter your name: ");scanf("%s",name);// Reads a single word (stops at whitespace)// Display the inputprintf("You entered: %d\n",number);printf("Your name is: %s\n",name);return0;}
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 thatscanf
can be sensitive to the input format, and it's a good practice to perform error checking on the return value ofscanf
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>intmain() {charname[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 putsreturn0;}
Please note thatgets
is considered unsafe because it doesn't limit the number of characters read, potentially causing a buffer overflow. It's recommended to usefgets
instead for safe input.
Thefgets
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 usingfgets
:
#include<stdio.h>intmain() {charname[50];// Buffer to store the inputprintf("Enter your name: ");fgets(name,sizeof(name),stdin);// Read a line of text safely// Remove the newline character if presentsize_tlen=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 namereturn0;}
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 offgets
is recommended overgets
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>intmain() {charcharacter;printf("Enter a character: ");character=getchar();// Read a single characterprintf("You entered: ");putchar(character);// Display the character using putcharputchar('\n');// Add a newline characterreturn0;}
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 Null1 Start of Header2 Start of Text3 End of Text4 End of Transmission5 Enquiry6 Acknowledge7 Bell8 Backspace9 Horizontal Tab10 Line Feed11 Vertical Tab12 Form Feed13 Carriage Return14 Shift Out15 Shift In16 Data Link Escape17 Device Control 118 Device Control 219 Device Control 320 Device Control 421 Negative Acknowledge22 Synchronous Idle23 End of Transmission Block24 Cancel25 End of Medium26 Substitute27 Escape28 File Separator29 Group Separator30 Record Separator31 Unit Separator32 Space33 !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>intmain(){charasciiCharacter;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>intmain(){intasciiValue;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>intmain(){charlowercaseLetter;printf("Enter a lowercase letter: ");scanf("%c",&lowercaseLetter);printf("Equivalent uppercase letter: %c\n",lowercaseLetter-32);getchar();}#include<stdio.h>intmain(){charuppercaseLetter;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>intmain(){charuppercaseLetter,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>intmain(){charuppercaseLetter,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>intmain() {intdecimalNumber;// Get input from the userprintf("Enter a decimal number: ");scanf("%d",&decimalNumber);// Display the conversionsprintf(" %o in octal and %x in hexadecimal.\n",decimalNumber,decimalNumber);return0;}
- 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.
intx=5;inty=+x;// y is 5, the same as x
2. Unary Minus-
: This operator changes the sign of a value to its negative.
intx=7;inty=-x;// y is -7, the negative of x
3. Increment++
: This operator increases the value of a variable by 1.
intx=10;x++;// Increment x by 1, now x is 11
4. Decrement--
: This operator decreases the value of a variable by 1.
intx=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.
intcondition=0;intnegatedCondition= !condition;// negatedCondition is 1 (true)
6. Bitwise NOT~
: This operator performs a bitwise NOT operation, inverting all bits of an integer value.
intx=5;// Binary: 00000101inty= ~x;// Binary: 11111010, y is -6 in decimal
7. Sizeofsizeof
: This operator returns the size in bytes of a data type or an expression.
intsize=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.intsum=5+3;// sum is 8
Subtraction
-
: Subtracts one value from another.intdifference=10-3;// difference is 7
Multiplication
*
: Multiplies two values.intproduct=4*5;// product is 20
Division
/
: Divides one value by another.floatquotient=15.0 /4.0;// quotient is 3.75
Modulus
%
: Returns the remainder of a division operation.intremainder=15 %4;// remainder is 3
Challenge Exercise: Create a Simple Calculator
WriteaCprogramtoperformbasicarithmeticoperations.Theprogramshould:Declarevariablesnum1andnum2tostoretwoinputnumbers.Declareavariableresulttostoretheresultoftheoperations.Asktheusertoinputtwonumbers.Performthefollowingoperations:AdditionSubtractionMultiplicationDivisionPrinttheresultsofeachoperation.Enterthefirstnumber:10Enterthesecondnumber:5Addition:10+5=15Subtraction:10-5=5Multiplication:10*5=50Division:10 /5=2
// create a basic calculator#include<stdio.h>#include<ctype.h>intmain(){intnum1,num2,result;floatdiv;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 hereprintf("%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>intmain(){intnum1,num2,num3,sum;floataverage;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>intmain(){floatbase,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>intmain(){floatside1,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>intmain(){floatcentigrade,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>intmain(){floatcentigrade,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.intisEqual= (5==5);// isEqual is 1 (true)
Not Equal
!=
: Tests if two values are not equal.intisNotEqual= (3!=5);// isNotEqual is 1 (true)
Greater Than
>
: Tests if one value is greater than another.intisGreater= (8>3);// isGreater is 1 (true)
Less Than
<
: Tests if one value is less than another.intisLess= (2<5);// isLess is 1 (true)
3. Logical Operators:
Logical AND
&&
: Returns true if both conditions are true.intbothTrue= (1&&1);// bothTrue is 1 (true)
Logical OR
||
: Returns true if at least one condition is true.inteitherTrue= (0||1);// eitherTrue is 1 (true)
Logical NOT
!
: Returns the opposite of a condition.intnotTrue= !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.
intx=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.
intx=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.
intx=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.
intx=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.
intx=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.
intx=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.
inta=5;// Binary: 00000101intb=3;// Binary: 00000011intresult=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.
inta=5;// Binary: 00000101intb=3;// Binary: 00000011intresult=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.
inta=5;// Binary: 00000101intb=3;// Binary: 00000011intresult=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.
inta=5;// Binary: 00000101intresult= ~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.
inta=5;// Binary: 00000101intresult=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).
inta=16;// Binary: 00010000intresult=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
Thecondition
is evaluated first. If it's true, thevalue_if_true
is returned; otherwise, thevalue_if_false
is returned. Here's an example:
intx=10;inty= (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. Ifx
is greater than 5 (which it is in this case), the value20
is assigned toy
. If the condition were false, the value5
would be assigned toy
.
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>intmain() {// Calculating square rootdoublenumber=25.0;doublesquareRoot=sqrt(number);printf("Square root of %lf is %lf\n",number,squareRoot);// Calculating powerdoublebase=2.0;doubleexponent=3.0;doubleresult=pow(base,exponent);printf("%lf raised to the power of %lf is %lf\n",base,exponent,result);// Calculating absolute valueintvalue=-10;intabsoluteValue=abs(value);printf("The absolute value of %d is %d\n",value,absoluteValue);// Rounding functionsdoublefloatingNumber=3.456;doubleroundedDown=floor(floatingNumber);doubleroundedUp=ceil(floatingNumber);printf("Original: %lf, Rounded Down: %lf, Rounded Up: %lf\n",floatingNumber,roundedDown,roundedUp);return0;}
In this example, we include<math.h>
and use functions likesqrt()
,pow()
,abs()
,floor()
, andceil()
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>intmain(){intnumber,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
andswitch
. Here are examples for both:
Theif
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>intmain() {intx=10;if (x>5) {printf("x is greater than 5.\n"); }else {printf("x is not greater than 5.\n"); }return0;}
In this example, theif
statement checks ifx
is greater than 5. If it is, the first block of code is executed. Otherwise, theelse
block is executed.
#include<stdio.h>intmain() {intnum=10;if (num<0) {printf("Number is negative.\n"); }elseif (num>0) {printf("Number is positive.\n"); }else {printf("Number is zero.\n"); }return0; }
- 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>intmain(){intnumber;if (number %2==0) {printf("%d is even",number); }else {printf("%d is odd",number); }return0;}
// check if the number is positive or negative or zero#include<stdio.h>intmain(){intnumber;if (number>0) {printf("positive"); }elseif (number<0) {printf("negative"); }else {printf("zero"); }return0;}
// find largest numer of 2 numbers#include<stdio.h>intmain(){intnumber1,number2;printf("Enter two numbers: ");scanf("%d %d",&number1,&number2);if (number1>number2) {printf("%d is the largest number\n",number1); }elseif (number2>number1) {printf("%d is the largest number\n",number2); }else {printf("Both numbers are equal\n"); }return0;}
// find largest numer of 3 numbers#include<stdio.h>intmain(){intnumber1,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); }elseif (number2>number1&&number2>number3) {printf("%d is the largest number\n",number2); }elseif (number3>number1&&number3>number2) {printf("%d is the largest number\n",number3); }else {printf("Both numbers are equal\n"); }return0;}
// check a year is a leap year or not#include<stdio.h>intmain(){intyear;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); }return0;}
// Check a letter is capital letter or small letter or not a letter#include<stdio.h>intmain(){charletter;printf("Enter a letter: ");scanf("%c",&letter);if (letter >='A'&&letter <='Z') {printf("%c is a capital letter\n",letter); }elseif (letter >='a'&&letter <='z') {printf("%c is a small letter\n",letter); }else {printf("%c is not a letter\n",letter); }return0;}
// Check a letter is vowel or consonant or not a letter#include<stdio.h>#include<ctype.h>intmain(){charletter;printf("Enter a letter: ");scanf("%c",&letter);letter=tolower(letter);if (!(letter >='a'&&letter <='z')) {printf("%c is not a letter\n",letter); }elseif (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); }return0;}
// Find Letter Grade from a student's mark#include<stdio.h>#include<ctype.h>intmain(){intmark;printf("Enter your mark: ");scanf("%d",&mark);if (mark>100&&mark<0) {printf("Invalid mark"); }elseif (mark >=90&&mark<100) {printf("A+"); }elseif (mark >=80&&mark<90) {printf("A"); }elseif (mark >=70&&mark<80) {printf("A-"); }elseif (mark >=60&&mark<70) {printf("B"); }elseif (mark >=50&&mark<60) {printf("C"); }elseif (mark >=40&&mark<50) {printf("D"); }else {printf("F"); }return0;}
Theswitch
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>intmain() {intday=3;switch (day) {case1:printf("Monday\n");break;case2:printf("Tuesday\n");break;case3:printf("Wednesday\n");break;default:printf("Other day\n"); }return0;}
In this example, theswitch
statement checks the value of theday
variable and executes the code block associated with the matchingcase
. If there's no match, thedefault
block is executed.
// switch : vowel / consonant program#include<stdio.h>#include<ctype.h>intmain(){charletter;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; }return0;}
// switch: temperature converter#include<stdio.h>#include<ctype.h>intmain(){intchoice;printf("Temperature Converter Started");printf("Choose 1. Fahrenheit to Celsius\n");printf("Choose 2. Celsius to Fahrenheit\n");scanf("%d",&choice);switch (choice) {case1:printf("Enter temperature in Fahrenheit: ");floatfahr;scanf("%f",&fahr);floatcelsius= (fahr-32) /1.8;printf("Temperature in Celsius: %.2f\n",celsius);break;case2:printf("Enter temperature in Celsius: ");floatcelsius;scanf("%f",&celsius);floatfahr=celsius*1.8+32;printf("Temperature in Fahrenheit: %.2f\n",fahr);break;default:printf("Invalid choice\n");break; }return0;}
// switch: basic calculator#include<stdio.h>#include<ctype.h>intmain(){intnumber1,number2;charoperation;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; }return0;}
- 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 (inti=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.inti=0;while (i<5) {// Code to be executedi++;}
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.inti=0;do {// Code to be executedi++;}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 (inti=0;i<3;i++) {for (intj=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>intmain(){// indefinite for loopfor(;;) {printf("Hello javatpoint"); }// indefinite while loopwhile (1) {// Code to be executed indefinitely }// indefinite do while loopdo{// body of the loop.. }while(1);return0;}
Jump control Statement includebreak
,continue
, andgoto
. Here are examples for each:
1.break
Statement:
Thebreak
statement is used to exit a loop prematurely, either afor
,while
, ordo...while
loop. It is typically used to terminate a loop based on a certain condition.
#include<stdio.h>intmain() {for (inti=1;i <=10;i++) {if (i==5) {break;// Exit the loop when i is 5 }printf("%d ",i); }return0;}
In this example, the loop is terminated wheni
equals 5, and the program exits the loop early.
2.continue
Statement:
Thecontinue
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>intmain() {for (inti=1;i <=10;i++) {if (i %2==0) {continue;// Skip even numbers }printf("%d ",i); }return0;}
In this example, even numbers are skipped, and only odd numbers are printed.
3.goto
Statement:
Thegoto
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>intmain() {inti=1;start:// Labelif (i <=10) {printf("%d ",i);i++; gotostart;// Jump to the "start" label }return0;}
In this example, the program jumps back to the "start" label usinggoto
to repeat the loop untili
becomes greater than 10.
Thebreak
andcontinue
statements are commonly used in loops to control the flow of iterations, while thegoto
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>intmain(){intnumber,count=0;printf("Enter a number: ");scanf("%d",&number);for(inti=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>intmain(){intnumber,count=0;printf("Enter a number: ");scanf("%d",&number);if(number<=1){printf("%d is not a prime number",number); }else{for(inti=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>intmain(){intnumber,count=0;printf("Enter a number: ");scanf("%d",&number);if(number<=1){printf("%d is not a prime number",number); }else{for(inti=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>intmain(){intnumber,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(inti=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>intmain(){intnumber,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
intnumbers1[5];// Array of 5 integers, uninitializedintnumbers2[]= {85,90,78,92,88};// Array initialized with values
intnumbers[5]= {10,20,30,40,50};printf("%d\n",numbers[0]);// prints 10// version 1#include<stdio.h>intmain() {intnumbers[]= {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]);return0;}// version 2: print array with loop#include<stdio.h>intmain() {intnumbers[]= {1,2,3,4,5};for(intindex=0;index<5;index++){printf("%d\n",numbers[index]); }return0;}// version 3: take user input for an array#include<stdio.h>intmain() {intnumbers[5];for(intindex=0;index<5;index++){scanf("%d",&numbers[index]); }for(intindex=0;index<5;index++){printf("%d\n",numbers[index]); }return0;}// 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>intlinearSearch(intarr[],intn,inttarget) {for (inti=0;i<n;i++) {if (arr[i]==target) {returni;// Return the index if the target is found } }return-1;// Return -1 if the target is not found }intmain() {intnumbers[]= {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 bytesintn=sizeof(numbers) /sizeof(numbers[0]);inttarget=10;intresult=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); }return0; }
#include<stdio.h>intmain(){intnumbers[]= {20,40,1,100,98,-4};intsearchNumber=40;intfound=-1;for(intindex=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); }return0; }
find the largest and second largest from an unsorted array
#include<stdio.h>voidfindLargestAndSecondLargest(intarr[],intn) {if (n<2) {printf("Array should have at least two elements.\n");return; }intfirst,second;if (arr[0]>arr[1]) {first=arr[0];second=arr[1]; }else {first=arr[1];second=arr[0]; }for (inti=2;i<n;i++) {if (arr[i]>first) {second=first;first=arr[i]; }elseif (arr[i]>second&&arr[i]!=first) {second=arr[i]; } }printf("Largest Element: %d\n",first);printf("Second Largest Element: %d\n",second);}intmain() {intarr[]= {12,35,1,10,34,1};intn=sizeof(arr) /sizeof(arr[0]);findLargestAndSecondLargest(arr,n);return0;}
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>voidfindLargestAndSecondLargest(intarr[],intn) {if (n<2) {printf("Array should have at least two elements.\n");return; }intfirst=arr[n-1];intsecond=arr[n-2];printf("Largest Element: %d\n",first);printf("Second Largest Element: %d\n",second);}intmain() {intarr[]= {1,10,12,34,35};intn=sizeof(arr) /sizeof(arr[0]);findLargestAndSecondLargest(arr,n);return0;}
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.
intbinarySearch(intarr[],intlow,inthigh,inttarget) {while (low <=high) {intmid=low+ (high-low) /2;if (arr[mid]==target) {returnmid; }elseif (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.
voidbubbleSort(intarr[],intn) {for (inti=0;i<n-1;i++) {for (intj=0;j<n-i-1;j++) {if (arr[j]>arr[j+1]) {// Swap arr[j] and arr[j+1]inttemp=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.
voidmerge(intarr[],intl,intm,intr) {// Merge two subarrays of arr[]// ... }voidmergeSort(intarr[],intl,intr) {if (l<r) {intm=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>intmain() {intmatrix[3][3]= { {1,2,3}, {4,5,6}, {7,8,9} };// Accessing and printing elementsfor (inti=0;i<3;i++) {for (intj=0;j<3;j++) {printf("%d ",matrix[i][j]); }printf("\n"); }return0; }
// 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 matrixvoidaddMatrices(intfirst[10][10],intsecond[10][10],intresult[10][10],introws,intcols) {for (inti=0;i<rows;i++) {for (intj=0;j<cols;j++) {result[i][j]=first[i][j]+second[i][j]; } } }// Function to display a matrixvoiddisplayMatrix(intmatrix[10][10],introws,intcols) {for (inti=0;i<rows;i++) {for (intj=0;j<cols;j++) {printf("%d ",matrix[i][j]); }printf("\n"); } }intmain() {intfirstMatrix[10][10],secondMatrix[10][10],resultMatrix[10][10];introws,cols;printf("Enter the number of rows: ");scanf("%d",&rows);printf("Enter the number of columns: ");scanf("%d",&cols);// Input for the first matrixprintf("Enter elements of the first matrix:\n");for (inti=0;i<rows;i++) {for (intj=0;j<cols;j++) {scanf("%d",&firstMatrix[i][j]); } }// Input for the second matrixprintf("Enter elements of the second matrix:\n");for (inti=0;i<rows;i++) {for (intj=0;j<cols;j++) {scanf("%d",&secondMatrix[i][j]); } }// Call the function to add matricesaddMatrices(firstMatrix,secondMatrix,resultMatrix,rows,cols);// Display the matrices and their sumprintf("\nFirst Matrix:\n");displayMatrix(firstMatrix,rows,cols);printf("\nSecond Matrix:\n");displayMatrix(secondMatrix,rows,cols);printf("\nSum of Matrices:\n");displayMatrix(resultMatrix,rows,cols);return0; }
#include<stdio.h>#defineMAX 10intisIdentityMatrix(intmatrix[MAX][MAX],intn) {// Check for square matrixif (n!=n)return0;// Check for identity matrixfor (inti=0;i<n;i++)for (intj=0;j<n;j++)if ((i==j&&matrix[i][j]!=1)|| (i!=j&&matrix[i][j]!=0))return0;return1;}intmain() {intmatrix[MAX][MAX];intn;printf("Enter the size of the square matrix: ");scanf("%d",&n);printf("Enter the elements of the matrix:\n");for (inti=0;i<n;i++)for (intj=0;j<n;j++)scanf("%d",&matrix[i][j]);if (isIdentityMatrix(matrix,n))printf("The matrix is an identity matrix.\n");elseprintf("The matrix is not an identity matrix.\n");return0;}
Multi dimensional array (>2D)Arrays with more than two dimensions.Used for complex data structures.
intpartition(intarr[],intlow,inthigh) {// ... }voidquickSort(intarr[],intlow,inthigh) {if (low<high) {intpi=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>intmain(){charname[5];name[0]='a';name[1]='n';name[2]='i';name[3]='s';name[4]='\0';// null characterprintf("Name = %s\n",name);return0;}// method 2#include<stdio.h>#include<ctype.h>intmain(){charname[5]= {'A','n','i','s','\0'};printf("Name = %s\n",name);return0;}// method 3#include<stdio.h>#include<ctype.h>intmain(){charname[5]="Anis";printf("Name = %s\n",name);return0;}// method 4 - multiple line#include<stdio.h>#include<ctype.h>intmain(){charname[5]="Anis \ Islam";// line breakprintf("Name = %s\n",name);return0;}
- how to take string as user input
// method 1#include<stdio.h>#include<ctype.h>intmain(){charname[20];printf("Enter your Full name: ");gets(name);printf("Full Name: %s\n",name);return0;}// method 2#include<stdio.h>#include<ctype.h>intmain(){charname[20];printf("Enter your Full name: ");fgets(name,sizeof(name),stdin);printf("Full Name: %s\n",name);return0;}
#include<stdio.h>#include<ctype.h>intmain() {charstr[100];intvowelsCount=0;intconsonantsCount=0;intdigitsCount=0;intwordsCount=0;intspecialCharsCount=0;intspacesCount=0;intuppercaseCount=0;intlowercaseCount=0;// Input a string from the userprintf("Enter a string: ");fgets(str,sizeof(str),stdin);// Iterate through each character in the stringfor (inti=0;str[i]!='\0';++i) {charcurrentChar=str[i];// Check for vowels (case-insensitive)charlowerChar=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 digitsif (isdigit(currentChar)) {++digitsCount; }// Check for spacesif (isspace(currentChar)) {++spacesCount; }// Check for wordsif (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 lettersif (isalpha(currentChar)) {if (isupper(currentChar)) {++uppercaseCount; }else {++lowercaseCount; } } }// Output the resultsprintf("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);return0;}intisvowel(charc) {return (c=='a'||c=='e'||c=='i'||c=='o'||c=='u');}
#include<stdio.h>#include<string.h>intmain() {// Example 1: strlencharstr1[]="Hello, World!";printf("Length of '%s': %zu\n",str1,strlen(str1));// Example 2: strcpycharstr2[20];strcpy(str2,"Copy me!");printf("Copied string: %s\n",str2);// Example 3: strcatcharstr3[30]="Hello";strcat(str3,", World!");printf("Concatenated string: %s\n",str3);// Example 4: strcmpcharstr4[]="apple";charstr5[]="orange";intresult=strcmp(str4,str5);printf("Comparison result: %d\n",result);// Example 5: strchrcharstr6[]="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: strstrcharstr7[]="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: strtokcharstr8[]="apple,orange,banana";char*token=strtok(str8,",");while (token!=NULL) {printf("Token: %s\n",token);token=strtok(NULL,","); }return0;}
- my program that I have created during the live session
#include<stdio.h>#include<ctype.h>#include<string.h>intisVowel(charletter){return (letter=='a'||letter=='e'||letter=='i'||letter=='o'||letter=='u');}intisLetter(charch){return (ch >='a'&&ch <='z')|| (ch >='A'&&ch <='Z');}intisDigit(charch){returnch >='0'&&ch <='9';}intisSpace(charch){returnch==' ';}intmain(){chartext[]="I love";printf("Length of text : %d\n",strlen(text));chartext2[30];printf("text2 = %s\n",strcpy(text2,text));charpassword[]="A123456";charconfirmedPassword[]="A123456";intresult=strcmp(password,confirmedPassword);printf("comparision result = %d\n",result);intnumberOfLetters=0;intnumberOfDigits=0;intnumberOfSpaces=0;intnumberOfWords=0;intnumberOfVowels=0;intnumberOfConsonants=0;intnumberOfSpecialCharacters=0;for (intindex=0;text[index]!='\0';index++) {charcurrentCharacter=text[index];// is letter or notif (isLetter(currentCharacter)) {numberOfLetters++; }if (isdigit(currentCharacter)) {numberOfDigits++; }if (isspace(currentCharacter)) {numberOfSpaces++; }// convert lowercasecurrentCharacter=tolower(currentCharacter);if (isVowel(currentCharacter)) {numberOfVowels++; }if (isLetter(currentCharacter)&& !isVowel(currentCharacter)) {numberOfConsonants++; }// not alphanumeric -> letter and digit and not spaceif (!(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);return0;}// 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 Declarationintadd(inta,intb);// Function Definitionintadd(inta,intb) {returna+b;}
In the above example,add
is a function that takes two integer parameters (a
andb
) and returns an integer result.
intresult=add(5,3);
This line calls theadd
function with arguments5
and3
and assigns the result (8
) to the variableresult
.
// Function with no parameters and no return valuevoidgreet() {printf("Hello, World!\n");}// Function with parameters and a return valueintmultiply(intx,inty) {returnx*y;}
// Function Prototypeintdivide(intx,inty);// Function Definitionintdivide(intx,inty) {returnx /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 consonantvoidcheckVowelOrConsonant(charch) {// Convert the character to lowercase for case-insensitive comparisonch=tolower(ch);// Check if the character is a vowel or consonantif ((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"); }}intmain() {charuserInput;// Get a character from the userprintf("Enter a character: ");scanf(" %c",&userInput);// Call the function and pass the charactercheckVowelOrConsonant(userInput);return0;}
#include<stdio.h>// Function to print the elements of an integer arrayvoidprintArray(intarr[],intsize) {for (inti=0;i<size;i++) {printf("%d ",arr[i]); }printf("\n");}intmain() {// Declare and initialize an arrayintnumbers[]= {1,2,3,4,5};// Calculate the size of the arrayintsize=sizeof(numbers) /sizeof(numbers[0]);// Call the function and pass the arrayprintArray(numbers,size);return0;}
#include<stdio.h>// Function to print the elements of a 2D arrayvoidprint2DArray(intarr[][3],introws,intcols) {for (inti=0;i<rows;i++) {for (intj=0;j<cols;j++) {printf("%d ",arr[i][j]); }printf("\n"); }}intmain() {// Declare and initialize a 2D arrayintmatrix[][3]= {{1,2,3}, {4,5,6}, {7,8,9}};// Call the function and pass the 2D array along with its dimensionsprint2DArray(matrix,3,3);return0;}
// Recursive Function to calculate factorialintfactorial(intn) {if (n==0||n==1) {return1; }else {returnn*factorial(n-1); }}
A recursive function is a function that calls itself. Thefactorial
function calculates the factorial of a number using recursion.
intglobalVariable=10;// Global variablevoidexampleFunction() {intlocalVariable=5;// Local variableprintf("%d\n",globalVariable+localVariable);}intmain() {exampleFunction();return0;}
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>structPerson{intage;floatsalary;};intmain(){structPersonanis,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);return0;}// number of letters
- how to get input for structure
#include<stdio.h>#include<ctype.h>structPerson{charname[50];intage;floatsalary;};intmain(){structPersonanis,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);return0;}// number of letters
- how to initialize structure directly
#include<stdio.h>#include<ctype.h>structPerson{charname[50];intage;floatsalary;};intmain(){structPersonp1= {"anis",33,3100};structPersonp2=p1;printf("Age: %d\n",p1.age);printf("Salary: %.2f\n",p1.salary);return0;}
- struct comparison
#include<stdio.h>#include<ctype.h>structPerson{charname[50];intage;floatsalary;};intmain(){structPersonp1= {"anis",33,3100};structPersonp2=p1;if (p1.age==p2.age&&p1.name==p2.name) {printf("Equal"); }else {printf("Not Equal"); }return0;}// number of letters
- Array of structure & structure passing to a function
#include<stdio.h>#include<ctype.h>structPerson{charname[50];intage;floatsalary;};voiddisplay(structPersonperson){printf("Name = %s\n",person.name);printf("Age = %d\n",person.age);printf("Salary = %.2f\n",person.salary);}intmain(){structPersonperson[4];inti;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]) }return0;}// number of letters
- Example of a structure
#include<stdio.h>#include<ctype.h>structStudent{charname[50];intage;floatcgpa;};voidprintStudentInfo(structStudentstudent){// printing student infoprintf("Name = %s\n",student.name);printf("Age = %d\n",student.age);printf("CGPA = %.2f\n",student.cgpa);}intmain(){structStudentstudents[4];for (intindex=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 (intindex=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 integerintx=10;int*ptr=&x;// Intitializing a pointer. Pointer ptr now holds the address of variable xintx=10;int*ptr=&x;// Accessing values through a pointerprintf("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>intmain(){intnumber1=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>voidswap(int*ptr1,int*ptr2){inttemp=*ptr1;*ptr1=*ptr2;*ptr2=temp;}intmain(){intnumber1=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>intmain(){intnumber1=10;intnumber2=20;int*ptr1=&number1;int*ptr2=&number2;intsum=*ptr1+*ptr2;printf("Sum of numbers = %d\n",sum);}// Another version#include<stdio.h>// Function to calculate the sum of two numbers using pointersintsum(int*ptr1,int*ptr2) {return (*ptr1)+ (*ptr2);}intmain() {intnumber1=10;intnumber2=20;int*ptr1=&number1;// Pointer to number1int*ptr2=&number2;// Pointer to number2// Call the sum function with pointers as argumentsintresult=sum(ptr1,ptr2);printf("Sum of numbers = %d\n",result);return0;}
- accessing arrays using pointer and arithmetic operation
#include<stdio.h>#include<stdlib.h>intmain(){intnumbers[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 memoryfree(ptr);// Deallocates the memory#include<stdio.h>#include<stdlib.h>intmain(){int*ptr1= (int*)malloc(sizeof(int));// Allocates memory for an integerint*ptr2= (int*)malloc(sizeof(int));*ptr1=10;// Assigns a value to the allocated memory*ptr2=20;intsum=*ptr1+*ptr2;printf("Sum of numbers = %d\n",sum);free(ptr1);// Deallocates the memoryfree(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>intmain() {int*dynamicArray=NULL;// Pointer to dynamically allocated memoryintsize=0;// Current size of the dynamic arrayintcapacity=2;// Initial capacity of the dynamic array// Allocate memory for the dynamic arraydynamicArray= (int*)malloc(capacity*sizeof(int));// Check if memory allocation was successfulif (dynamicArray==NULL) {printf("Memory allocation failed\n");return1; }// Prompt the user to enter numbers until they input -1intnum;printf("Enter numbers (-1 to stop):\n");while (1) {scanf("%d",&num);if (num==-1) {break; }// Resize the dynamic array if necessaryif (size==capacity) {capacity *=2;dynamicArray= (int*)realloc(dynamicArray,capacity*sizeof(int));if (dynamicArray==NULL) {printf("Memory reallocation failed\n");return1; } }// Add the new number to the dynamic arraydynamicArray[size++]=num; }// Print the elements of the dynamic arrayprintf("Dynamic array elements:\n");for (inti=0;i<size;i++) {printf("%d ",dynamicArray[i]); }printf("\n");// Free dynamically allocated memoryfree(dynamicArray);return0; }}
- 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>intmain() {charname[50];charphone[50];charemail[50];printf("Enter Name: ");fgets(name,sizeofname,stdin);printf("Enter Phone: ");fgets(phone,sizeofphone,stdin);printf("Enter Email: ");fgets(email,sizeofemail,stdin);printf("Contacts.\n ");printf("Name: %s\nPhone: %s\nEmail: %s\n",name,phone,email);return0; } ```
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 variablehow to create and close a file in c
#include<stdio.h>intmain() {FILE*file;// `FILE *nameOfTheFile` file pointer variablefile=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>intmain() {charname[50];charphone[50];charemail[50];FILE*file;file=fopen("contact.txt","a");if (file==NULL) {printf("Unable to open the contact file.\n");return0; }else {// writing to a fileprintf("The contact file is open.\n");fflush(stdin);printf("Enter Name: ");fgets(name,sizeofname,stdin);printf("Enter Phone: ");fgets(phone,sizeofphone,stdin);printf("Enter Email: ");fgets(email,sizeofemail,stdin);// Write contact details to filefprintf(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>intmain(){charname[50];charphone[50];charemail[50];FILE*file;file=fopen("contact.txt","r");if (file==NULL) {printf("Unable to open the contact file.\n");return0; }else {// read from a fileprintf("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>voidaddContact() {charname[50];charphone[50];charemail[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 filefflush(stdin);printf("Enter Name: ");fgets(name,sizeofname,stdin);printf("Enter Phone: ");fgets(phone,sizeofphone,stdin);printf("Enter Email: ");fgets(email,sizeofemail,stdin);// Write contact details to filefprintf(file,"%s%s%s\n",name,phone,email);fclose(file);printf("Contact added successfully.\n"); } }voiddisplayContacts() {charname[50];charphone[50];charemail[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); } }intmain() {addContact();displayContacts(); }
create a structure to make this more easier
#include<stdio.h>// Structure to represent a contacttypedefstruct{charname[50];charphone[20];charemail[50];}Contact;voidaddContact(){ContactnewContact;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 filefflush(stdin);printf("Enter Name: ");fgets(newContact.name,sizeofnewContact.name,stdin);printf("Enter Phone: ");fgets(newContact.phone,sizeofnewContact.phone,stdin);printf("Enter Email: ");fgets(newContact.email,sizeofnewContact.email,stdin);// Write contact details to filefprintf(file,"%s%s%s\n",newContact.name,newContact.phone,newContact.email);fclose(file);printf("Contact added successfully.\n"); }}voiddisplayContacts(){Contactcontact;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); }}intmain(){addContact();displayContacts();}
- Finally lets add some choices here
intmain(){intchoice;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) {case1:addContact();break;case2:displayContacts();break;case3:printf("Exiting...\n");break;default:printf("Invalid choice. Please try again.\n"); } }while (choice!=3);return0;}
- Final version of Contact Management System
#include<stdio.h>structContact{charname[50];charphone[50];charemail[50];};voidaddContact(){FILE*file;file=fopen("contact.txt","a");if (file==NULL) {printf("File does not exist or could not be created"); }else {structContactcontact;fflush(stdin);printf("Enter Name: ");fgets(contact.name,sizeofcontact.name,stdin);printf("Enter Phone: ");fgets(contact.phone,sizeofcontact.phone,stdin);printf("Enter Email: ");fgets(contact.email,sizeofcontact.email,stdin);// write to the filefprintf(file,"%s%s%s\n",contact.name,contact.phone,contact.email);fclose(file);printf("Added to Contact Management System\n"); }}voiddisplayContacts(){structContactcontact;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); }}intmain(){intchoice;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) {case1:addContact();break;case2:displayContacts();break;case3:printf("Exiting...\n");break;default:printf("Invalid Choice. Please try again.\n"); } }while (choice!=3);}
About
c-programming-documentation [learnwithfair, Learn with fair, Rahatul Rabbi, Md Rahatul Rabbi ,rahatulrabbi]
Topics
Resources
Uh oh!
There was an error while loading.Please reload this page.