Module-1 Problem Solving
using C Programming.
Department of
Computer Science &
Engineering
www.cambridge.edu.in
What is a Programming Language?
“A programming language is a computer language that is used by programmers
(developers) to communicate with computers.”
A programming language is mainly used to develop desktop applications,
websites, and mobile applications.
Department of Computer Science & Engineering www.cambridge.edu.in
What is a Compiler ???
“The compiler is software that converts a program written in a high-level language (Source
Language) to a low-level language (Object/Target/Machine Language/0, 1’s).”
• The program written in a high-level language is known as a source program, and the program
converted into a low-level language is known as an object (or target) program.
• Without compilation, no program written in a high-level language can be executed.
• For every programming language, we have a different compiler; however, the basic tasks
performed by every compiler are the same
Why study C Programming ????????
(Dennis Ritchie developed C at Bell Laboratories)
• C is widely used in developing firmware, middleware, and operating systems,
making it a crucial language in the embedded software industry.
• Additionally, many real-time operating systems (RTOS) are written in C,
making it an essential skill for developers working in this field.
• For those interested in building electronic products or using microcontrollers to
automate tasks, learning C programming language is a valuable skill to have.
Operating systems: Unix, Linux kernel, Android kernel still has C, RTOSs( Real time
operating system) which are used in aerospace, automotive and medical devices are written
using C/C++.
DBMS: MySQL, PostgreSQL, SQLite
Editor: Notepad++
Embedded Systems:
Microcontroller programming (e.g., ARM, AVR, PIC)
Automotive control systems (ECUs, ABS)
Consumer electronics (TVs, washing machines, smart thermostats)
Department of Computer Science & Engineering www.cambridge.edu.in
Designing Tools used in Problem Solving
(Algorithms, Psuedocode and Flowchart)
1. Algorithms:
Definition:
An algorithm is a step-by-step procedure for solving a problem
or
A Systematic logical approach which is a well-defined, step-by-step procedure that allows a
computer to solve a problem.
Characteristics:
• Finite: Must have a finite number of steps.
• Clear: Each step must be unambiguous.
• Effective: Steps must be executable and result in a solution.
• Input/Output: Should have zero or more inputs and one or more outputs.
Example Algorithm (Finding the Maximum of Two Numbers):
1.Begin
2.Read two numbers, A and B.
3.If A > B, then the maximum is A.
4.Otherwise, the maximum is B.
5.Output the maximum.
6.End
OR
Designing Tools used in Problem Solving
2. Flowcharts:
Definition:
A flowchart is a visual representation of an
algorithm or process using various symbols
connected by arrows.
Symbols used in Flowchart
Flowchart
Algorithm , Flowchart & Pseudocode
What is an Algorithm?
Algorithm is a set of well-defined instructions in sequence to solve a problem.
Qualities of a good algorithm
1. Input and output should be defined precisely.
2. Each step in the algorithm should be clear and unambiguous.
3. Algorithms should be most effective among many different ways to solve a
problem.
4. An algorithm shouldn't include computer code. Instead, the algorithm
should be written in such a way that it can be used in different
programming languages.
Flowchart
A flowchart is a diagrammatic representation of an algorithm. A
flowchart can be helpful for both writing programs and explaining the
program to others.
Main Symbols Used in Flowcharts
Start/End Symbols (Terminal Symbols):
Represented as circles, ovals, or rounded rectangles.
Indicate the beginning and the end of the flowchart.
Arrows:
Show the flow of control.
Illustrate the sequence of instructions.
Processing Step (Activity):
Represented by a rectangle.
Includes instructions like arithmetic operations or data movements.
Input/Output Symbols:
Represented by a parallelogram.
Used to get inputs from users or display results.
Flowchart
Decision Symbol:
Represented by a diamond.
Used to depict Yes/No or True/False decisions, with labeled arrows indicating
the outcomes.
Labeled Connectors:
Represented by a circle with an identifying label.
Used in complex or multi-sheet diagrams to replace arrows and maintain
clarity.
Symbols used in Flowchart
Flowchart
Algorithm Flowchart
Write a C Program to add 2 numbers.
Algorithm
Step 1: [ Initialization ]
Start
Step 2: [ Input 2 no’s from the user ]
Read num1, num2
Step 3: [ Add num1 and num2 and
assign the result to a variable sum ]
Sum = num1 + num2
Step 4: [ Display sum ]
Print Sum
Step 5: [ Finished ]
Stop
Algorithm Flowchart
Write a C Program to find area of circle.
Step 1: [ Initialization ]
Start
Step 2: [ Input radius from the user ]
Read radius
Step 3: [ Compute Area ]
area =PI * radius*radius
Step 4: [ Display Area ]
Print area
Step 5: [ Finished ]
Stop
Algorithm Flowchart
Design and develop a C program to read a year as an input and find whether it is leap
year or not.
Step1: [Initialization]
Start
Step2: [Input year]
Read year
Step3:[Check whether
given year is leap year
or not]
if ( ((year%4==0) &&(year%100!=0))||
(year%400 == 0))
Display leap year
else
Display not a leap year
Step 4:[finished]
stop
Pseudocode
Definition: Pseudocode is a simplified, informal high-level description of an
algorithm using structural conventions of a programming language.
Key Points:
Complete Logic: Describes the entire logic of the algorithm.
Human-Readable: Omits non-essential details like variable
declarations, system-specific code, and subroutines.
Language-Agnostic: Should not include keywords from any specific
programming language.
Purpose: Enhances human understanding of the solution.
Usage: Commonly found in textbooks and scientific publications to
outline program structure before coding.
Pseudocode Example: Calculating Price After Adding Sales Tax
Pseudocode:
Begin
Read the price of the product.
Read the sales tax rate.
Calculate sales tax = price of the product × sales tax rate.
Calculate total price = price of the product + sales tax.
Print total price.
End.
Variables:
price of the product , sales tax rate
sales tax , total price
Exercises
Sum, difference and product of two numbers.
Area of a circle.
Area of a triangle.
Area of a rectangle.
Convert the given Celsius to Fahrenheit and vice-versa. F=C*9/5+32.
Simple interest.
Largest of two numbers.
Largest of three numbers.
To check if two entered numbers are equal.
1. To check if a given number is even or odd.
To check if a given number is positive or negative.
To check if a person is eligible to vote.
1. Display the quotient and remainder of the division 10/4.
Check if an entered character is a vowel.
1. To check if a given year is a leap year.
Creating and Running Programs
1. Writing and Editing:
Objective: Write the C program using a text editor.
Key Tools: IDEs (e.g., Visual Studio Code, Code::Blocks) or basic text editors
Task: Develop the program logic and write the code.
2. Compiling:
Objective: Convert source code into machine-readable object code.
Key Tools: C compiler (e.g., GCC, Clang).
Task: Check for syntax errors and produce intermediate object files.
3. Linking:
Objective: Combine object code with required libraries.
Key Tools: Linker (often part of the compiler).
Task: Resolve external references and create an executable file.
4. Executing:
Objective: Run the compiled and linked program.
Key Tools: Command-line interface or IDE’s built-in run feature.
Task: Observe the output and test the program.
Creating and Running Programs
Basic Structure Of C Programs
Basic Structure Of C Programs
Every C program consists of:
One or more preprocessor commands
A global declaration section
One or more functions
The global declaration section:
Comes at the beginning of the program
Is visible to all parts of the program
Functions in a C program:
Perform the tasks within the program
One function must be named main
The main function is the starting point of the program
Basic Structure Of C Programs
Structure of functions:
Divided into two sections:
Declaration section: Describes the data used in the function (local
o
declarations, visible only within the function)
o Statement section: Contains instructions for the computer, written as
statements
Preprocessor commands:
Special instructions to the preprocessor for preparing the program for
o
compilation
o One common preprocessor command is include
The include command:
o Tells the preprocessor to include information from selected libraries
(header files)
o Essential for using library functions in programs, such as i/o operations
Tokens
n C Programming
Definition:
The smallest individual unit in a C program, recognized by the
compiler.
Types of Tokens
Keywords – Reserved words with special meaning (e.g., int, if,
return).
Identifiers – Names given to variables, functions, arrays, etc.
Constants – Fixed values (e.g., 10, 3.14, 'A').
Strings – Sequence of characters in double quotes (e.g., "Hello").
Operators – Symbols that perform operations (e.g., +, -, *, /).
Punctuators (Separators) – Symbols like ;, {}, (), ,.
Identifiers
Identifiers in Programming Languages:
Identifiers allow us to name data and objects in programs.
Each identified object is stored at a unique address.
Identifiers symbolically represent data locations, avoiding the need to use
object's addresses directly.
Syntax Rules for Identifiers in C:
Valid symbols: A-Z, a-z, 0-9, and underscore (_).
The first character cannot be a digit.
Typically, the first character is not an underscore to avoid conflict with
system library identifiers.
Identifiers cannot be keywords (reserved words).
Identifiers
Identify valid or Invalid Identifier
Sum_total , _name , average ,
@name , name-detail , product_no_ ,
people@bangalore , total amount
Identifiers
Identifiers in Programming Languages:
Identifiers allow us to name data and objects in programs.
Each identified object is stored at a unique address.
Identifiers symbolically represent data locations, avoiding the need to use
object's addresses directly.
Syntax Rules for Identifiers in C:
Valid symbols: A-Z, a-z, 0-9, and underscore (_).
The first character cannot be a digit.
Typically, the first character is not an underscore to avoid conflict with
system library identifiers.
Identifiers cannot be keywords (reserved words).
Range of data-types
Range of data-types
Range of data-types
Range of data-types
Range of data-types
Range of data-types
What Is A Variable ??
C variable is a named location in a memory where a program
can manipulate the data. This location is used to hold the
value of the variable.
C VARIABLE
The value of the C variable may get change in the program.
C variable might be belonging to any of the data type like int,
float, char etc.
Rules For Naming C Variable:
Variable name must begin with letter or underscore.
Variables are case sensitive.
They can be constructed with digits, letters.
No special symbols are allowed other than underscore.
sum, height, _value are some examples for variable name.
C VARIABLE
Declaring & Initializing C Variable:
Variables should be declared in the C program before to use.
Memory space is not allocated for a variable while
C VARIABLE
declaration. It happens only on variable definition.
Variable initialization means assigning a value to the variable.
Assigning Value to the
Variable
Constants
Constants : Constants are data values that cannot be changed during the execution of a
program. Like variables, constants have a type. In this section, we discuss Boolean,
character, integer, real, complex, and string constants.
Boolean Constants
Character Constants
Integer Constants
Real Constants in C
String Constants in C
Constants
Constants : Constants are data values that cannot be changed during the execution of a
program. Like variables, constants have a type. In this section, we discuss Boolean,
character, integer, real, complex, and string constants.
Boolean Constants : In C, the bool type and Boolean constants true and false.
1.Including <stdbool.h>:
To use bool, true, and false, include the header: #include <stdbool.h>
Boolean Type and Constants:
bool: Alias for Bool, a data type in C.
true: Represents the integer 1.
false: Represents the integer 0.
Example:##include <stdbool.h>
bool isValid = true;
if (isValid)
{
printf("The value is true.\n");
}
Constants
Character Constants:
• Represent individual characters in C.
• Enclosed in single quotes (' ‘).
Character Constants in C
Example : char ch = ‘A’;
Value Representation
Stored as ASCII Value:
Character constants are stored as integers corresponding
to their ASCII values.
'A' has an ASCII value of 65.
Special Character Constants:
Escape Sequences:
•Examples:
•\n: Newline
•\t: Tab
•\\: Backslash
char newline = ‘\n’
Syntax and Example
Constants
Integer Constants in C
•Definition: An integer constant is a number without any fractional or decimal part.
•Types:
•Decimal: Base 10 (e.g., 10, -42)
•Octal: Base 8, prefixed with 0 (e.g., 012, 075)
•Hexadecimal: Base 16, prefixed with 0x or 0X (e.g., 0x1A, 0XFF)
•Rules:
•No commas or spaces.
•Can be positive or negative.
•Unsigned suffix (U) and long suffix (L) can be used (e.g., 10U, 123L).
•Examples:
•123 (Decimal)
•0123 (Octal)
•0x7B (Hexadecimal)
Constants
Real Constants in C
•Definition: A real constant (or floating-point constant) represents a number with a
fractional part.
•Types:
Decimal Form: (e.g., 3.14, -0.001)
Exponential Form: (e.g., 1.23e3 for 1.23×1031.23 \times 10^31.23×103,
4.56E-2 for 4.56×10−24.56 \times 10^{-2}4.56×10−2)
•Rules:
Must have at least one digit before and after the decimal point.
Can be positive or negative.
Use suffixes to define the precision:
•f or F for float (e.g., 3.14f)
•l or L for long double (e.g., 3.14L)
•Examples:
12.34 (Decimal)
0.001 (Small decimal)
2.5e3 (Exponential)
Constants
String Constants in C
•String Constants:
Definition: A sequence of characters enclosed in double quotes.
Characteristics:
•Stored as an array of characters, ending with a null character ('\0').
•Example: "Hello, World!" is a string constant of 13 characters (including '\0').
•Can include escape sequences like "\n" (newline) or "\t" (tab).
Examples:
•Integer: 100
•Real: 3.14
•Character: 'A'
•String: "C Programming"
Coding Constants in C
Literal Constants:
Definition: Unnamed constants coded directly in statements.
Usage: Ideal when the value is fixed and won’t change.
Example : a = b+5
Defined Constants:
Definition: Constants defined using the preprocessor directive #define.
Placement: Typically at the beginning of the program for easy
management.
Example: #define PI 3.14
Memory Constants:
Definition: Constants defined with the const keyword, making a variable's
value unchangeable.
Usage: When you need a constant with a specific name and type.
Example: const float PI = 3.14;
Input and Output Streams in C
Streams:
• Channels through which data flows between the program and external
devices.
• Can be associated with physical devices (e.g., keyboard, monitor) or files.
•Standard I/O: Standard Input: Keyboard (source of text stream).
Standard Output: Monitor (destination for text stream).
•Key Concepts:
•Terminals handle only text streams, not binary streams.
•The keyboard inputs text streams; the monitor outputs text streams.
Input and Output Streams in C
Input and Output Streams in C
Formatting Input/Output in C
•Formatting Functions:
• printf (output):
Formats and converts program data into a text stream for output to the monitor.
• scanf (input) :
Converts text streams from the keyboard into data values and stores them in
variables.
•Output Formatting with printf:
•Functionality: Converts data values into a formatted text stream based on a format
control string.
Input and Output Streams in C
.
Input and Output Streams in C
Basic Concept of printf in C
Function Design:
•The printf function converts data into text streams using a format control string.
Format Control String:
. •Conversion Specifications: Describe how each data value should be formatted (e.g.,
type, size, display width).
Conversion Specifications:
•Define how data values are displayed.
•The position in the format control string determines where data appears in the output.
Parameters for printf:
1.Format Control String: Contains textual data and conversion specifications.
2.Data Values: Correspond to the conversion specifications in the format string.
Input and Output Streams in C
Scanf (output) in C
•Purpose:
• The scanf function reads a text stream from the keyboard, extracts and formats data
according to a format control string, and stores the data in specified variables.
•Key Concepts:
1. Format Control String:
•Describes how data should be extracted and formatted.
. •Enclosed in quotation marks with conversion specifications.
2. Variable Addresses:
• scanf requires the memory addresses of variables to store the extracted data (e.g.,
&var).
Example:
• Format String: scanf(" %c %c %d", &c1, &c2, &num);
• Explanation: Spaces before %c skip preceding whitespace, ensuring accurate input
capture.
Understanding Expressions in Programming
1. What is an Expression?
A sequence of operands and operators that evaluates to a single value.
2. Types of Expressions:
Simple Expression: Contains only one operator.
Example: 2 + 5 (evaluates to 7)
Example: -a (unary operation)
.
Complex Expression: Contains more than one operator.
Example: 2 + 5 * 7
Explanation: First, 5 * 7 is evaluated, then 2 + 35, resulting in 37.
3. Operators and Operands:
Operator: A syntactical token that specifies an action (e.g., +, *, -).
Operand: The object upon which the operation is performed (e.g.,
numbers, variables).
Operators
Operators
Arithmetic Operators
Operators
Operators
Operators
Relational Operators
Operators
Logical Operators
Operators
Assignment Operators
Operators
Conditional Operators
Operators
Bitwise Operators
Operators
Bitwise Operators
Operators
Special Operators
Operators
Increment & Decrement
Operators
Increment And Decrement Operator :
Operators
Increment & Decrement
Operators Operators
Operator Precedence &
Associativity
Precedence &
Associativity
Operator Precedence &
Associativity
Precedence &
Associativity
Operator Precedence &
Associativity
Precedence &
Associativity
Operator Precedence &
Associativity
Precedence &
Associativity
Precedence & Associativity
Precedence &
Associaivity
Precedence & Associativity
Precedence &
Associativity
Precedence & Precedence & Associativity
Associativity
Type Conversion in C
Type cast is basically a conversion from one data type to another. There
are two types of type conversion:
1. Implicit Type Conversion :
Also known as ‘automatic type
Type Conversion
conversion’.
Done by the compiler on its own,
without any external trigger from the
user.
Generally takes place when in an
expression more than one data type is
present. In such condition type
conversion (type promotion) takes
place to avoid lose of data.
All the data types of the variables are
upgraded to the data type of the
variable with largest data type.
Implicit Type Conversion in C
It is possible for implicit conversions to lose information, signs can
be lost (when signed is implicitly converted to unsigned), and
overflow can occur (when long long is implicitly converted to float).
Type Conversion
Explicit Type Conversion in C
Explicit Type Conversion :
This process is also called type casting and it is user defined. Here the
user can type cast the result to make it of a particular data type.
The syntax in C: ( type ) expression
Type Conversion
Type indicated the data type to which the final result is
converted.
Thank you