0% found this document useful (0 votes)
6 views69 pages

Problem Solving Using C Unit-1

The document outlines a lecture note on problem-solving using the C programming language, detailing course outcomes, syllabus units, and fundamental concepts. It covers programming basics, including algorithms, flowcharts, and the history and features of C, along with practical applications and structured programming principles. The content is structured into units that address various programming constructs, data types, and memory management techniques.

Uploaded by

Saurbh Jha
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views69 pages

Problem Solving Using C Unit-1

The document outlines a lecture note on problem-solving using the C programming language, detailing course outcomes, syllabus units, and fundamental concepts. It covers programming basics, including algorithms, flowcharts, and the history and features of C, along with practical applications and structured programming principles. The content is structured into units that address various programming constructs, data types, and memory management techniques.

Uploaded by

Saurbh Jha
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

LECTURE NOTE on

Problem Solving USING C


COURSE: Mca,Msc(IT),Msc(CSE)
By
Asst. Prof. Ms Sudha
Course Outcome

• CO1: Understand basic terminology of computers, problem solving, programming Languages and their evolution (Understand)

• CO2: Create specification from problem requirements by asking questions to disambiguate the requirement statement. (Create)

• CO3: Design the solution from specification of a problem and write pseudo code of the algorithm using basic building blocks or
structured programming constructs (Sequence, Selection and Repetition statement). (Create)

• CO4: Translate an algorithm into a C computer program (Create)

• CO5: Testing and analysing programs using debugging tools. (Analyze)


UNIT-I

• Basics of programming: Approaches to problem solving, Use of high level programming language for systematic development of
programs, Concept of algorithm and flowchart, Concept and role of structured programming.

• Basics of C: History of C, Salient features of C, Structure of C Program,


Compiling C Program, Link and Run C Program, Character set, Tokens,
Keywords, Identifiers, Constants, Variables, Instructions, Data types,
Standard Input/Output, Operators and expressions
Syllabus

UNIT-II

• Conditional Program Execution: if, if-else, and nested if-else statements, Switch statements, Use of break and default with switch,
Comparison of switch and if-else.

• Loops and Iteration: for, while and do-while loops, Multiple loop variables, Nested loops, break and continue statement.

• Functions: Introduction, Types, Declaration of a Function, Function calls, Defining functions, Function Prototypes, Passing arguments to
a function Return values and their types, Writing multifunction program, Calling function by value, Recursive functions.
UNIT-III

• Arrays: Array notation and representation, Declaring one-dimensional array, Initializing arrays, Accessing array elements, Manipulating
array elements, Arrays of unknown or varying size, Two-dimensional arrays, Multidimensional arrays.

• Pointers: Introduction, Characteristics, * and & operators, Pointer type declaration and assignment, Pointer arithmetic, Call by reference,
Passing pointers to functions, arrayof pointers, Pointers to functions, Pointer to pointer, Array of pointers.

• Strings: Introduction, Initializing strings, Accessing string elements, Array of strings, Passing strings to functions, String functions.
Syllabus

UNIT-IV

• Structure: Introduction, Initializing, defining and declaring structure, Accessing members, Operations on individual members,
Operations on structures, Structure within structure, Array of structure, Pointers to structure.

• Union: Introduction, Declaring union, Usage of unions, Operations on union. Enumerated data types.

• Storage classes: Introduction, Types- automatic, register, static and external


UNIT-V

• Dynamic Memory Allocation: Introduction, Library functions – malloc, calloc, realloc and free.

• File Handling: Basics, File types, File operations, File pointer, File opening modes, File handling functions.
Unit-1

Problem Solving is a scientific technique to discover and implement the answer to a problem. The computer is the symbol manipulating device that
follows the set of commands known as program.

Program:

Program is the set of instructions which is run by the computer to perform specific task. The task of developing program is called programming.

Problem Solving Technique:

Sometimes it is not sufficient just to cope with problems. We have to solve that problems. Most people are involving to solve the problem. These
problem are occur while performing small task or making small decision. So, Here are the some basic steps to solve the problems
Step 1: Identify and Define Problem
Explain you problem clearly as possible as you can.

Step 2: Generate Possible Solutions

 List out all the solution that you find. Don’t focus on the quality of the solution

 Generate the maximum number of solution as you can without considering the quality of the solution

Step 3: Evaluate Alternatives

After generating the maximum solution, Remove the undesired solutions.

Step 4: Decide a Solution

After filtering all the solution, you have the best solution only. Then choose on of the best solution and make a decision to make it as a perfect solution.

Step 5: Implement a Solution:

After getting the best solution, Implement that solution to solve a problem.

Step 6: Evaluate the result

After implementing a best solution, Evaluate how much you solution solve the problem. If your solution will not solve the problem then you can again
start with Step 2.
Algorithm:

Algorithm is the set of rules that define how particular problem can be solved in finite number of steps. Any good algorithm must have following
characteristics

1. Input: Specify and require input


2. Output: Solution of any problem
3. Definite: Solution must be clearly defined
4. Effective
5. Finite: Steps must be finite
6. Correct: Correct output must be generated

Advantages of Algorithms:

1. It is the way to sole a problem step-wise so it is easy to understand.


2. It uses definite procedure.
3. It is not dependent with any programming language.
4. Each step has it own meaning so it is easy to debug

Disadvantage of Algorithms:

1. It is time consuming
2. Difficult to show branching and looping statement
3. Large problems are difficult to implement

Flowchart:

The solution of any problem in picture form is called flowchart. It is the one of the most important technique to depict an algorithm.

Advantage of Flowchart:

1. Easier to understand
2. Helps to understand logic of problem
3. Easy to draw flowchart in any software like MS-Word
4. Complex problem can be represent using less symbols
5. It is the way to documenting any problem
6. Helps in debugging process

Disadvantage of Flowchart:

1. For any change, Flowchart have to redrawn


2. Showing many looping and branching become complex
3. Modification of flowchart is time consuming
Example: Algorithm and Flowchart to check odd or even

Solution:

Algorithm:
Step 1: Start
Step 2: Declare a variable x
Step 3: Take a input from user and store in x
Step 4: IF x % 2 == 0 THEN
PRINT Even
ELSE
PRINT Odd
Step 5: End

Flowchart:
What is a Programming Language?
A programming language is a way for people to give instructions to a computer. It uses special words and rules to create programs that tell the
computer what to do. These instructions can make the computer perform tasks like solving problems, playing games, or running apps. Examples of
programming languages are Python, Java, and C++.
There are Two Types of Programming languages:
 High-Level Language
 Low-Level Language
High-Level Language
A high-level language (HLL) is a human-readable programming language that simplifies coding by hiding complex hardware details, letting
developers focus on logic and functionality.
 Designed to make writing code simpler and faster.
 Allow developers to build large programs more easily.
 Easier to find and fix mistakes.
 Can work on different computers with minimal adjustments.
 Usually slower in performance compared to machine-oriented languages.
 Provide many ready-made features to speed up coding.
 Good for beginners and widely used for everyday software.
 Examples include JavaScript, Ruby, Swift, and PHP.
Low-Level Language
A low-level language is a machine-oriented programming language that provides minimal abstraction from hardware, offering direct control over
memory and system resources for maximum performance and efficiency.
 Provide direct access to the computer’s hardware.
 Require detailed knowledge of how a computer works.
 Less user-friendly, making programming more challenging.
 Harder to find and solve errors in code.
 Not easily adapted for use on different hardware.
 Used mostly for specific tasks needing high performance or precise control.
 Often faster and use fewer system resources.
 Examples include Binary code and Assembly languages like MIPS or ARM.
High-Level Language Vs Low-Level Language
The table below shows the key differences between high-level and low-level languages.
Parameters High-Level Language Low-Level Language

Abstraction Level High abstraction, closer to human language Low abstraction, closer to machine code

Ease of Use Easier to learn and use More complex and harder to learn

Portability Highly portable across different systems Less portable, often system-specific

Development Speed Faster development time Slower development time

Examples Python, Java, C++, JavaScript Assembly language, Machine code

Memory Management Automatic memory management Manual memory management

Error Handling Built-in error handling features Limited error handling, requires manual checks

Performance Generally slower execution Generally faster execution


Parameters High-Level Language Low-Level Language

Use Cases Application development, scripting, web development System programming, embedded systems, device drivers

Role of Structured programming:-


The primary role of structured programming is to simplify and organize code, making it more readable, maintainable, and efficient by using logical
structures like sequences, selections (if/else), and iterations (loops), instead of unstructured jumps (like goto). This approach breaks down large,
complex programs into smaller, manageable, and reusable modules or functions, leading to higher quality software with less development time and
easier debugging.

Key Roles and Principles


 Clarity and Readability:
Structured programming emphasizes clear control flow, using standard structures to make the code's logic easy for developers to follow and
understand.
 Modularity:
It promotes dividing a program into smaller, self-contained blocks (functions or modules) that perform specific tasks, reducing complexity and
improving organization.
 Maintainability:
With clearer structure and modularity, it's easier to locate and fix errors (debugging), update, and modify the program over time.
 Efficiency:
By using logical control structures and avoiding complex "spaghetti code" caused by goto statements, the software becomes more reliable and
efficient.
 Reusability:
Modules or functions developed with this approach can be reused in other parts of the program or in different applications, saving development
time.
 Top-Down Approach:
It often involves breaking down a large problem into smaller, more manageable subproblems, solving each one individually to build up the complete
solution.
 Structured Control Flow:
The use of specific control structures (Sequence, Selection, Iteration) to control the order of execution is central to its role in managing program
logic.

History of C:-
C is a general-purpose high level language that was originally developed at Bell laboratories in 1972, by Dennis M. Ritchie for the Unix operating
system. It was first implemented on the Digital Equipment Corporation PDP-11 computer in 1972.
C programming language features were derived from an earlier language called “B” (Basic Combined Programming Language – BCPL) .
C language was invented for implementing UNIX operating system.

 In 1978, Dennis Ritchie and Brian Kernighan published the first edition “The C Programming Language” and is commonly known as K&R C.

 In 1983, the American National Standards Institute (ANSI) established a committee to provide a modern, comprehensive definition of C. The
resulting definition, the ANSI standard, or “ANSI C”, was completed late 1988.

 Many of C’s ideas & principles were derived from the earlier language B, thereby naming this new language “C”.

Features of C Language
The following are the standard features of C Language as follows.
[Link]: Programs written in C language can be run on any compiler with little or no modifications of a program.
#include <stdio.h> int main() { printf("Hello,
World!"); return 0;
}
This simple program will run on Windows, Linux, Mac, or any C compiler.

2. Flexibility: C has 32 keywords and many operators, allowing programmers to control program flow and structure.
#include <stdio.h> int main() { int age = 20; if
(age >= 18) { printf("Eligible to Vote");
} else { printf("Not Eligible");
} return 0;
}
Here if and else (keywords) give us flexibility in decision-making.
• 3. Modularity
Large programs can be broken into smaller modules (functions) → makes code easier to read, debug, and reuse.
#include <stdio.h> void add(int a, int b) { printf("Sum =
%d\n", a + b);
} int main() { add(5, 10); // Calling module (function) return 0;
}

4. Robustness
C has a rich set of built-in functions & operators → helps in writing complex programs reliably.
#include <stdio.h> #include
<math.h> int main() {
double num = 25.0;
printf("Square Root = %.2f", sqrt(num)); // Built-in function return 0;
}

• 5. Extensibility
New features or modules can be added anytime without affecting the existing program. #include <stdio.h> int main() {
printf("Welcome to C!\n");

// Later we add a new feature printf("Now adding more features...\n"); return


0;
}

6. Efficiency and Effectiveness

• C programs are fast and memory-efficient, because:

• It supports low-level operations (close to hardware).

• It provides variety of data types (int, float, char, etc.).

• Operators make computations fast #include <stdio.h> int main() {


int a = 10, b = 20;
printf("Multiplication = %d", a * b); // Fast calculation return 0;
}

Some of applications of the C language are:


1. Operating Systems – C is used to make OS like Windows, Linux, UNIX.

2. Embedded Systems – Used in washing machines, microwaves, cars, smart devices.

3. Game Development – Used for making games and game engines.


4. Compilers & Interpreters – Many programming compilers are written in C.

5. Database Systems – Databases like Oracle, MySQL are built using C.

6. System Programming – Used for drivers, kernels, device controllers.

7. IoT & Robotics – Used in microcontrollers and IoT devices.

8. Scientific Applications – For simulations, calculations, and analysis.

Structure of a C Program:
1. Documentation Section

2. Link Section

3. Definition Section

4. Global Declaration Section5. main() Function Section

- Variable Declaration
- Body of main()
6. Subprogram Section
- User-defined functions

1. Documentation Section
Used to write comments about the program (what it does, author name, date).
/* Program to add two numbers Date: 15 Sept 2025 */

2. Link Section
Used to link header files (library files) for built-in functions.
#include <stdio.h> // For printf, scanf
#include <math.h> // For mathematical functions

3. Definition Section
Used to define constants and macros before the program starts.
#define PI 3.14
#define MAX 100
4. Global Declaration Section
Variables and functions declared here can be used anywhere in the program.
int total; // Global variable

5. main() Function Section


This is the starting point of every C program.
It has two parts:
Variable Declaration Part int a, b, sum;
Body Part (Logic of the program) sum = a + b;
printf("Sum = %d", sum);
6. Subprogram Section (User-defined functions)
Functions written by the programmer to perform specific tasks.
int add(int x, int y) {
return x + y;
}
/* Documentation Section }
Program to add two numbers int main() { // main() Function Section
*/ int a, b; // Variable Declaration printf("Enter two
#include <stdio.h> // Link Section numbers: "); scanf("%d %d", &a, &b); total = add(a, b); //
Body of main printf("Sum = %d", total);
#define PI 3.14 // Definition Section
int total; // Global Declaration Section
// Subprogram (User-defined function) int add(int return 0;
x, int y) { }
return x + y;
First C Program:
#include <stdio.h> int
main() { int number;
printf( "Please enter a number: " );
scanf( "%d", &number ); printf( "You entered
%d", number ); return 0;
}
1. #include <stdio.h>
This is a preprocessor directive.
It tells the compiler: “Before compiling, include the Standard Input/Output header file.” The file stdio.h contains functions like
printf() and scanf().
Without it, the compiler wouldn’t know what printf() means.
2. int main()
This is the main function of the program.
Execution of every C program starts from main().
The word int means this function will return an integer value to the operating system (usually 0 if successful).
3. { ... } (curly braces)
They mark the beginning { and end } of the main() function.
All the instructions of main() are written inside these braces.

4. { (Brace)
This is a brace (or curly bracket). As the name implies, braces come in packs of two - for every open brace there must be a matching close one.
5. printf("Hello C Language"); printf() is a function defined in
stdio.h.
It is used to print/display text on the screen.
"Hello C Language" is a string constant written inside double quotes.
6. Scanf
The standard input/output library contains a number of functions for formatted data transfer; the two we are going to use are scanf (scan formatted) and
printf (print formatted)
6. return 0;
This ends the main() function and returns 0 to the operating system.
0 usually means the program executed successfully.
If we return some other value, it may indicate an error code.
C Programming Development Cycle
C Programming Development Cycle
1. Write/Edit Source Code
You write the program in C language (e.g., program.c).
You can use an editor like Notepad, VS Code, Code::Blocks, or Turbo C.
Example code: #include <stdio.h> int
main() { printf("Hello, World!"); return 0;
}

2. Compile Source Code (C Compiler)

• The C compiler (like GCC) converts the human-readable code into machine language.

• It checks for syntax errors (missing semicolon, wrong spelling of keywords, etc.).

• If there are errors, you must correct them before moving on.

3. Syntax Error?
If errors exist → Go back to edit source code and fix them.
If no errors → The compiler produces an object file (e.g., program.o).
4. Linker & Loader

• Linker: Combines your object file with required library functions (like printf, scanf from stdio.h).

• Loader: Loads the final executable into memory so it can run.

• Result → Executable file ([Link] on Windows, [Link] on Linux).ors → The compiler produces an object file (e.g., program.o).

5. Execute Object Code

• The executable file runs with input (if required).

• Example: If program asks for two numbers, you enter them during execution.

6. Logic/Data Errors?

• Sometimes program runs but output is wrong due to mistakes in logic. Example: Writing a - b instead of a + b.

• Sometimes user enters wrong input data (like entering text instead of a number).
• If error found → Go back and fix the source code.

• If no error → Continue.

7. See Output
• The correct result of your program is displayed.
Example:
Hello, World!
1. Every program starts with main()
int main() { //
code return 0;
}

2. Statements end with a semicolon (;)


int a = 5; printf("%d", a);

3. Case-sensitive language
Uppercase and lowercase letters are treated differently.
int number = 10; int Number = 20; // Different
variable

4. Use of curly braces { }


int main() { int a = 5; int b
= 10; printf("%d", a+b);
}
5. Preprocessor directives start with #
#include <stdio.h>
#define PI 3.14

6. Comments in C
Used to explain code, ignored by compiler.
// Single-line comment
/* Multi-linecomment */

7. Identifiers (names)
Rules for naming variables, functions, etc.
Must start with a letter or _
Can contain letters, digits, _
❌ No spaces, special characters
int age; float total_marks;

8. Keywords
Reserved words in C (cannot be used as variable names).
Examples: int, float, if, while, return

9. White Spaces
Spaces, tabs, and newlines are ignored by the compiler but used for readability.
int x = 5; // valid int y=10; //
also valid

10. Functions and Headers


Standard functions (like printf, scanf) require header files.
#include <stdio.h> int main()
{ printf("Hello"); return 0;
}
Character set
A character set is the collection of valid characters that the C language recognizes and can use to form programs. Types of Character Set in C
1. Letters (Alphabets)
• Uppercase letters: A to Z

• Lowercase letters: a to z

• Example:
int Age; // uses uppercase 'A' float rate; // uses
lowercase ‘r’
[Link]
• Numbers 0 to 9

• Used in numeric constants, array sizes, etc.


Example: int x = 100; // uses digits

3. Special Characters
These are symbols that have special meaning in C.
Some examples:
+ - * / = < > % & # ^ ! | ~ ? : ; , . _ ( ) { } [ ] " " ' ' \ printf("Hello, World!\n"); // uses " , , ; ,
( ) , \n
4. White Spaces
• Blank space, tab, newline.

• Used to separate tokens (keywords, identifiers, constants).

• Example: int number = 5; // spaces between int, number, =, 5


5. Escape Sequences
Special characters represented with a backslash (\).

Examples:
\n → new line
\t → tab space
\\ → backslash
\" → double quote printf("Hello\nWorld"); // prints Hello in one line, World in next line

C TOKENS
C programs contain many elements which are identified by the compiler, are known as tokens. Just like English sentences are made of words, a C
program is made of tokens. Example:
int age = 20;
Here:
int → keyword age →
identifier = → operator
20 → constant
; → special symbol
All of these are tokens.

Tokens can be categorized as,

1) Keywords

2) Identifiers

3) Variables

4) Constants

5) Special symbols

6) Operators
Tokens can be categorized as,
1. Keywords
A keyword is a reserved word. All keywords have fixed meaning that means we cannot change. C keywords are the words that convey a special
meaning to the c compiler. The keywords cannot be used as variable names, constant name.
A list of 32 keywords in c language is given below:
2. IDENTIFIERS
In C language identifiers are the names, which are given to variables, user-defined functions and arrays.
Syntax Rules:

1. An identifier should only have alphanumeric characters (a-z, A-Z, 0-9) and underscore (_) symbol.

2. The first character of an identifier should only have alphabets (a-z, A-Z) or underscore (_) symbol.

3. Identifiers are case sensitive in C language. For example, “name” and “Name”are two different identifiers in C language.

4. Keywords are not allowed to be used as identifiers.

5. Special characters (Ex: ;, ., white spaces, slash etc.,) are not permitted to use as identifiers.
Example:
int age; // "age" is an identifier float salary; //
"salary" is an identifier

3. Variables
A variable is a name that is used to store a value. Variable are simply names used to refer some locations in memory i.e. a location that holds a
value Variable declaration:
Declaration of variable must be done before they are used in the program. It dones three things:
• It tells the compiler what the variable name it is.

• It specifies what type of data the variable will hold.

• It tells the scope or lifetime of a variable.


Declaration of Variables :
A variable can be used to store a value of any data type. The
declaration of variables must be done before they are used in the program. The general format for declaring a variable. Syntax : data_type variable;
data_type variable-1,variable-2,------, variable-n;
Variables are separated by commas and declaration statement ends with a semicolon.
Ex : int x; float b;
char m,n;
Assigning values to variables : values can be assigned to variables using the assignment
operator (=). The general format statement is :
Syntax : variable = constant; Ex : x=100; a=
12.25; m=‟f‟;
Rules of variables declaration:

1. All variables must be declared before they can be appeared in executable statements.

2. A variable name must not start with digits.

3. Keywords are not allowed as variable names.

4. White spaces are not allowed in variable names.

5. Variable names can consists of alphabets, digits and only permitted special symbol underscore (_).

4. Constants
C Constants are like normal variables. But, only difference is their values cannot be modified by the program once they are defined.
Constants refer to fixed values. They are also called as literals.
Constants may be belonging to any of the data type.
1. Numeric Constant Integer constants:
Integer constants are whole numbers (without a decimal point). They can be positive, negative, or zero.
They can be written in three number systems:

• Decimal (Base 10): Digits 0–9

• Octal (Base 8): Begins with 0 (zero), digits 0–7

• Hexadecimal (Base 16): Begins with 0x or 0X, digits 0–9 and letters A–F Examples: int a = 10; // Decimal constant
int b = -9; // Decimal constant int c = 021; // Octal constant (17 in decimal) int d = 0x7F; // Hexadecimal constant
(127 in decimal)
Real Constants (Floating-point):
Numbers that have a fractional (decimal) part or are written in exponential notation.

• real constant must have at least one digit.

• It must have a decimal point.

• It could be either positive or negative.

• Default sign is positive.

• No commas or blanks are allowed within a real constant. Ex.: +325.34


426.0
-32.76
Examples:
float pi = 3.14; // Decimal form double g = -9.81; // Negative real constant double exp
= 1.23e3; // Exponential form (1.23 × 10³ = 1230.0)
2. Character Constants
These represent characters enclosed within single or double quotes.
Single Character Constants:
A single character enclosed in single quotes ' '.
Internally, it is stored using its ASCII value.
Examples:
char grade = 'A'; // Character constant char digit = '9'; // Character
constant char symbol = '$'; // Character constant
String Constants:
A sequence of characters enclosed in double quotes " ".
Automatically ends with a null character '\0'.
Examples:
printf("Hello, World!"); // String constant char name[] = "Praveen"; // Stored as an array of characters
6. Special symbols
Symbols other than the alphabets and digits and white-spaces are called special symbols. C has following list of special symbols.
Unit-1
6. Operators
Symbols other than the alphabets and digits and white-spaces are called special symbols. C has following list of special symbols.
This is a symbol use to perform some operation on variables, operands or with the constant. Some operator required 2 operand to perform
operation or Some required single operation
Ex : a+b; Where a,b are operands and + is the operator. Types of Operator :

1) Arithmetic Operators. 5). Increment And Decrement Operators.

2) Relational Operators. 6) Conditional Operators.

3) Logical Operators. 7) Special Operators.

4) Assignment Operators. 8) Bitwise Operators.


1. Arithmatic Operator
These are used to perform mathematical calculations like addition, subtraction, multiplication, division and modulus.
Following table shows all the arithmetic operators supported by C language. Assume variable A holds 10 and variable B holds 20 then:
Unit-1
Operators
1. Arithmatic Operator
#include <stdio.h> void main()
{ int a = 9,b = 4, c; printf("a/b = %d \n",c); c = a+b;
printf("a+b = %d \n",c); c=a%b; printf("Remainder when a divided by b = %d \n",c);
c = a-b; printf("a-b = %d \n",c); c =
a*b; printf("a*b = %d \n",c);
c=a/b;
2. Relational Operators
These operators are used to compare the value
of two variables.
Following table shows all the relational
operators supported by C language. Assume
variable A holds 10 and variable B holds 20,
then:
3. Logical Operators:
These operators are used to perform logical operations on the given two variables.
Following table shows all the logical operators supported by C language. Assume variable A holds 1 and variable B holds 0, then:

6. Assignment Operators:
In C programs, values for the variables are assigned using assignment operators.
There are following assignment operators supported by C language:
Operators
7. INCREMENT AND DECREMENT OPERATOR
These operators are used to increment or decrement by 1 in an expression.
#include<stdio.h> void main()
{
int i = 1; printf("%d %d %d", i, ++i, i++);
}
Output : 3 3 1
Postfix and Prefix Expression in Same Statement
#include<stdio.h>
#include<conio.h>
void main() {
int i = 0, j = 0;
j = i++ + ++i;
printf("%d\n", i);
printf("%d\n", j);
}
Output :
2
2

Conditional Operator / Ternary operator:


It sometimes called as ternary operator. Since it required three expressions as operand and it is represented as (? , :).
Syntax : condition ? exp1 : exp2;
It first evaluate the condition, if it is true (non-zero) then the “exp1” is evaluated, if the condition is false (zero) then the “exp2” is evaluated.
EXAMPLE:
void main() Output: Value is:10
{
int a=10, b=2 int s= (a>b) ?
a:b; printf(“value is:%d”);
}
Operators
9. Special operators:
C supports some special operators as shown below
Data Types
To store data the program must reserve space which is done using datatype. A datatype is a keyword/predefined instruction used for allocating memory
for data. A data type specifies the type of data that a variable can store such as integer, floating, character etc.
There are 4 types of data types in C language:
Basic/Primitive data type
These are predefined data types, which are supported by the programming language.

Derived Data Types: The data types which derived from fundamental or primitive data types is known as derived data
types. For example, arrays, functions, structures and unions etc.

Void Data Type: void data type means “no values” (or) “empty” i.e. it take or returns empty value. The void data type usually
used with functions to specify its return type or with parameters list.
Enumerated Data Type:
Enumerated data type consists of named integer constants as a list.
It starts with zero by default and increments by one for the sequential identities in the list.
Syntax: enum identifier{enumerators_list};
Example: enum month{ jan, feb, march};
Variable:-
A variable is a name of memory location. It is used to store data. Variables are changeable,
we can change value of a variable during execution of a program. . It can be reused many times.
Note: Variable are nothing but identifiers.
Rules to write variable names:

1. A variable name contains maximum of 30 characters/ Variablename must be upto 8 characters.

2. A variable name includes alphabets and numbers, but it must startwith an alphabet.

3. It cannot accept any special characters, blank spaces except underscore( _ ).

4. It should not be a reserved word.


Ex : i rank1 MAX min Student_name
StudentName class_mark

1. Local Variables
A local variable is declared inside a function or block (like inside { }).
It is created when the function is called and destroyed when the function ends.
Scope → only inside that function/block.
Lifetime → exists only while the function is running.
Default value → garbage (random value) until initialized.
1. Local Variables #include <stdio.h>
void test() {
int a = 10; // local variable printf("Local variable a = %d\n", a);
} int main() {
test();
// printf("%d", a); // ❌ Error: 'a' not available here return 0;
}
2. Global Variables
A global variable is declared outside all functions.
It can be accessed by any function in the program.
Scope → available throughout the program.
Lifetime → exists as long as the program runs.
Default value → 0 if not initialized.

2. Global Variables #include <stdio.h> int g = 100; //


global variable void test() {
printf("Global variable g = %d\n", g);
} int main() {
printf("Accessing g in main = %d\n", g); test(); // also works inside another function return
0;
}

ALGORITHM
An algorithm is a description of a procedure which terminates with a result. Algorithm is a step-by-step method of solving a problem.
Properties of an Algorithm:

1) Finiteness: - An algorithm terminates after a finite numbers of steps.


2) Definiteness: - Each step in algorithm is unambiguous. This means that the action specified by the step cannot be interpreted (explain the meaning
of) in multiple ways & can be performed without any confusion.

3) Input: - An algorithm accepts zero or more inputs

4) Output:- An algorithm should produce at least one output

5) Effectiveness: - It consists of basic instructions that are realizable. This means that the instructions can be performed by using the given inputs in
a finite amount of time.

ALGORITHM
Example
Q. Write a algorithem to find out number is odd or even?
step 1 : start step 2 : inputnumber step 3 : rem=number mod 2 step 4 : if
rem=0then print "number even" else print "number odd" endif step 5 :stop
FLOWCHART
Flowchart is a diagrammatic representation of an algorithm. Flowchart is very helpful in writing program and explaining program to others. Symbols
Used In Flowchart Different symbols are used for different states in flowchart,
Draw a flowchart to add two numbers entered by user.
Input-Output in C
Output Functions

• printf() → Print formatted output printf("Age = %d", age);

• putchar() → Print a single character putchar('A');

• puts() → Print a string (auto newline) puts("Hello World");


Input Functions

• scanf() → Read formatted input scanf("%d", &age);

• getchar() → Read a single character ch = getchar();


Expression: An expression is a combination of operators, constants and variables. An expression may consist of one or more
operands, and zero or more operators to produce a

Types of Expressions in C
There are four types of Expressions in C programming:
1. Arithmetic Expression
2. Relational Expression
3. Logical Expression
4. Conditional Expression

1. Arithmetic Expression in C
An arithmetic expression consists of operands and arithmetic operators. It performs computations on the int, float, or double type values.
Arithmetic operations can be performed in a single line of code or multiple lines combined with arithmetic operations such
as addition, subtraction, multiplication, and division.
The following types of arithmetic expressions are there:
 integer expression - an expression containing only integral operands,
 real expression - an expression containing only real operands

 mixed mode expression - an expression containing both integral and real operands

The arithmetic expression makes it easier to calculate computationally intensive tasks by programming each operation step-by-step.
The precedence and associativity of operators decide the order of the evaluation of individual operations.
Type of results after evaluation of an arithmetic expression:
 When both the operands are of integer type, the result of the operation would be an integer value. The fractional part of the result is
ignored.
 When both the operands are of float data type, the result of the operation would be a real value.

 If one operand is of type integer and another of type real, the first operand is converted into a real operand, and then the operation is
performed, producing a real value as the result.

Example
Evaluation of expression Description of each operation

6*2/( 2+1 * 2/3 +6) +8 * (8/4) An expression is given.

6*2/(2+2/3 + 6) + 8 * (8/4) 2 is multiplied by 1, giving the value 2.

6*2/(2+0+6) + 8 * (8/4) 2 is divided by 3, giving a value 0

6*2/ 8+ 8 * (8/4) 2 is added to 6, giving a value 8.

6*2/8 + 8 * 2 8 is divided by 4, giving a value 2.

12/8 +8 * 2 6 is multiplied by 2, giving a value 12.

1+8*2 12 is divided by 8, giving a value 1.

1 + 16 8 is multiplied by 2, giving a value 16.

17 1 is added to 16, giving a value 17.

2. Relational Expression in C
Relational expressions use comparison operators such as '>' (greater than) and '<' (less than) to compare two operands. The result of the
comparison is a boolean value i.e. 0(false) or non-zero (true).
It is a condition that decides whether the action should be taken or not. Relational expressions are used in decision-making
statements and looping statements in the C language.

Relational
Description
Expression

The given condition checks whether the x is an even number or not. This relational
x%2 = = 0
expression shows the result as the value 1 if x is an even number otherwise as the value 0

This relational expression is used to check if a is not equal to b and it results in 1 if a is not
a!=b
equal to b otherwise 0.

a+b = = x+y It is used to check if this particular expression "a+b" is equal to the expression "x+y"

a>=9 It is used to check if the value of a is greater than or equal to 9.

Example

#include <stdio.h>
int main()
{
int x = 5, y = 10;
if (x == y) {
printf("x is equal to y\n");
} else {
printf("x is not equal to y\n");
}
return 0;
}
Run Code >>
The above code in C Compiler checks if x is equal to y or not

Output
x is not equal to y
3. Logical Expression in C
Logical expressions in C are a powerful tool for controlling the logic of the flow of the program. They are made by combining as many relational
expressions as the programmer wants. It then determines if certain statements or groups of statements should be executed or not.

Logical
Description
Expressions

( x > 4 ) && ( x < This logical expression is used as a test condition to check if the x is greater than 4 and the
6) x is less than 6. The result of the condition is true only when both conditions are true.

This logical expression is used as a test condition to check if x is greater than 10 or y is less
x > 10 || y <11
than 11. The result of the test condition is true if either of the conditions holds true value.
! ( x > 10 ) && ( y This logical expression is used as a test condition to check if x is not greater than 10 and y is
==2) equal to 2. The result of the condition is true if both the conditions are true

Example

#include <stdio.h>
int main()
{
int x = 10;
int y = 2;
if ( (x >10) || (y<5))
{
printf("Condition is true");
}
else
printf("Condition is false");
return 0;
}
Run Code >>
OUTPUT
Condition is true
4. Conditional Expression in C
The conditional expression consists of three operands. It returns 1 if the condition is true otherwise 0. We had seen the conditional operator in
the section, Operators in C. We will look at ternary operators in detail in the section Ternary Operator in C.
Example

#include <stdio.h>
#include <string.h>
int main()
{
int age = 29;
char status;
status = (age>22) ? 'M': 'U';
if(status == 'M')
printf("Married");
else
printf("Unmarried");
return 0; }
Run Code >>

Output
Married

You might also like