Unit-1 : Problem solving with a Computer
Problem solving is thelogical and analytical processof finding a solution to a task or
problem using computational methods. It is foundational for writing efficient code and
developing software systems.
Algorithm and Flowchart
An algorithm is a set of finite, unambiguous instructions or a step-by-step procedure
designed to solve a problem or accomplish a specific task
Characteristics of a good algorithm
➢ Well-defined Inputs:Clearly states what data thealgorithm needs to function.
➢ Well-defined Outputs: Specifies what results the algorithmwill produce.
➢ Clear and Unambiguous: Each instruction must be precise and lead to only one
interpretation.
➢ Finiteness: Must terminate after a limited numberof steps for all possible inputs.
➢ Feasibility: Should be practical and executable withavailable resources.
➢ Language Independent: The logicshouldbetransferabletodifferentprogramming
languages.
Example 1: Algorithm for Area of a Circle
Step 1: Start
Step 2: Read radius r
Step 3: Compute area = π × r × r
Step 4: Display area
Step 5: Stop
Example 2: Find Largest of 3 Numbers
Step 1: Start
Step 2: Read values a, b, c
Step 3: Compare values and find largest
If a>b and a>c largest is a
If b>a and b>c, largest is b
If c>a and c>, largest is c
Step 4: Display largest value
Step 5: Stop
Example 3: Sum of N Numbers
Step 1: Start
Step 2: Read N
Step 3: Initialize sum = 0
Step 4: Loop from 1 to N
Step 5: Add current value to sum
Step 6: Display sum
Step 7: Stop
Flowchart Notations and Diagrams
A flowchart is a visual representation of an algorithm using standard symbols connected
by arrows to show the flow of data and control. It provides a graphical blueprint of the
solution.
Example 1: Area of a Circle
Example 2: Find Largest of 3 Numbers
Example 3: Sum of N Numbers
Overview of C Language
The C programming language is a powerful general-purpose programming language
developedintheearly1970s.Knownforitsefficiency,portability,andclose-to-hardware
capabilities, C has become the foundationformanymodernprogramminglanguagesand
operating systems.
History of C Language
Year Milestone
1960s ALGOL and BCPL developed—precursors to C
1967 Martin Richards develops BCPL (Basic Combined Programming
Language)
1970 Ken Thompson creates B language at Bell Labs
1972 Dennis Ritchie at Bell Labs develops C, evolving B and adding data types
1973 UNIX operating system rewritten in C
1978 Kernighan and Ritchie publish “The C Programming Language” (K&R C)
1989 ANSI standardizes C: ANSI C / C89
1990 ISO adopts the standard: ISO C / C90
1999 C99 – supports inline functions, new data types
2011 C11 standard released – includes multithreading support
Features of C Language
Simplicity:Chasasmallsetofkeywordsandsyntaxrules.Easytolearnandread,especially
for systems programming.
Portability:Cprogramscanbecompiledandrunondifferentmachineswithminimalorno
modification.
Speed and Efficiency:Programs written in C execute faster due to minimal overhead.
Structured Programming Language: Supports structured programming and modular code
(via functions).
Rich Library Support:Built-in functions in standard libraries simplify development.
Pointer Support: Direct memory manipulation is possible. Enables dynamic memory
allocation.
Extensibility:Users can create their own libraries and functions.
Recursion:Supports recursive function calls, essentialfor problems like tree traversal.
Bit-level Manipulation:Efficient for system-level or embedded programming.
Low-level Access:Close to assembly language, allowing hardware-level programming.
Structure of a C Program
A typical C program follows a well-defined structure that includes multiple sections.
Understandingthestructureiscrucialforwritingsyntacticallycorrectandwell-organized
code.
Basic Structure of a C Program
Section Description
1. Preprocessor Directives Lines beginning with #, such as #include <stdio.h>, are
instructions to the preprocessor.
2. Global Declarations Variables, constants, or function declarations that are
accessible throughout the program.
3. main() Function The starting point of any C program. Execution begins from
main().
4. Variable Declarations Variables must be declared before use, specifying data type.
5. Executable Statements The logic or tasks like calculations, loops, and I/O operations.
6. Return Statement Ends the main() function and returns control to the OS,
usually return 0.
Example C Program
#include <stdio.h> // Preprocessor directive
int x = 10; // Global declaration
int main()
{
int y = 20; // Variable declaration
int sum = x + y; // Executable statement
printf("Sum = %d\n", sum); // Output
return 0; // Return statement
}
Optional Sections in Larger Programs
•Function Definitions:User-defined functions canbe written outside main() for modularity.
•Comments:Use // for single-line or /* */ for multi-linecomments to describe the code.
•Macros / Constants:Defined using #define for reuse and clarity.
Creating and Executing a C Program
TodevelopandrunaCprogram,weneedatexteditortowritethecodeandacompilerto
translate the code into an executable file. Below are the steps involved in writing,
compiling, and running a C program.
Steps to Create and Execute a C Program
Step 1: Writing the Code
Write your C code using a texteditor(e.g.,Notepad,VSCode,Code::Blocks,oranyIDE).
Save the file with a '.c' extension.
Step 2: Compiling the Code
Use a C compiler like GCC (GNU Compiler Collection) to compile the code. (Alt+F9)
Step 3: Running the Executable
Run the compiled executable.(ctrl+F9)
Step 4: Debugging (if needed)
If there are errors, fix them in the source code and recompile. Warnings should also be
addressed for good practice.
C Character Set
ThecharactersetinCdefinesthevalidcharactersthatcanbeusedinwritingCprograms.
It includesletters, digits, special symbols, andwhite space characters.
Letters (Alphabets)
Uppercase:
Ato
Z
Lowercase:
ato
z
Used in identifiers, keywords, etc.
Digits:
0to
9
Used in numeric constants, variables, and expressions.
Special Characters: Symbols used for operations and syntax in C:
~ ! @ # $ % ^ & * ( ) - _ + = { } [ ] | \ : ; " ' < > , . ? / ~ ``
White Space Characters: Space ( ), Tab ( ), Newline (
\t ), Carriage Return (
\n \r)
Used to separate tokens and improve code readability.
Escape Sequences: Characters that begin with a backslash (
\)to represent non-printable
or special characters:
Escape Sequence Description
\n
New line
\t
Horizontal tab
\r
Carriage return
\b
Backspace
\\
Backslash (
\)
\"
Double quote (
" )
\'
Single quote (
')
\0
Null character
C Tokens
In C, the smallest individual units in a program are called tokens. Just like words and
punctuation form a sentence in English, tokens form the syntax and structure of a C
program.
Types of C Tokens
C tokens are categorized intosixbasic types:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Operators
6. Special Symbols
1. Keywords
● Reserved words predefined by the language.
● Cannot be used as identifiers (e.g., variable or function names).
● Examples: ,
int ,
float ,
return ,
if ,
else ,
while ,
for ,
break ,
continue ,
void
,
switch ,
case default
Note: There are 32 keywords in standard C (C89), though modern compilers
may support more.
2. Identifiers
● Thenamesgiven to variables, functions, arrays, etc.
● Must begin with a letter (A–Z, a–z) or underscore (
_), followed by letters, digits, or
underscores.
● Cannot be a keywordandshould not start with a digit.
● Examples:
,
total ,
main ,
sum1 _counter
Naming Rules:
● Case-sensitive (e.g.,
Totaland
totalare different).
● No spaces or special characters (except
_).
3. Constants
● Fixed values that donot changeduring program execution.
● Types:
○ Integer constants: ,
100 ,
-45 0
○ Floating-point constants: ,
3.14 -0.001
○ Character constants: ,
'a' ,
'Z' '0'
○ Enumeration constants:Defined using .
enum
4. Strings
● A sequence of characters enclosed indouble quotes.
● Stored as an array of characters ending with anullcharacter .
\0
● Examples:
,
"Hello" ,
"1234" "C Programming"
5. Operators
● Symbols used to perform operations on variables and values.
● Categories include:
○ Arithmetic:
+,
-,
*,
/,
%
○ Relational: ,
== ,
!= <,
>, ,
<= >=
○ Logical: ,
&& ,
|| !
○ Assignment:
=, ,
+= ,
-= ,
*= /=
○ Unary: ,
++ --
○ Bitwise:
&,
|,
^,
~, ,
<< >>
○ Ternary:
?:
6. Special Symbols
● Used for syntax control and grouping.
Examples:
{ }– Curly braces (code blocks)
( )– Parentheses (function calls, expressions)
[ ]– Square brackets (arrays)
;– Semicolon (statement terminator)
,– Comma (separator)
#– Preprocessor directive
Data Types
In C, data types define the type of data a variable can store. They help the compiler
allocate memory and interpret data properly.
Basic Data Types in C
Data Type Description Example Values
int
Integer values 1,
,
-42 0
float
Single-precision floating point ,
3.14 -0.001
double
Double-precision floating point 3.1415926535
char
Single characters ,
'A'
,
'z' '0'
void
No value (used for functions) N/A
Declaration of Variables
Declaring a variable means telling the compiler to reserve memory foritandspecifythe
data type.
Syntax:
data_typevariable_name;
Examples:
intage;
floatsalary;
chargrade;
Initialization of Variables
Initialization means assigning an initial value to a variable when it is declared.
Syntax:
data_typevariable_name = value;
Examples:
intage = 25;
floatpi = 3.14;
chargrade = 'A';
Multiple Variable Declaration
We can declare and initialize multiple variables of the same type on a single line.
intx = 10, y = 20, z = 30;
Symbolic Constants in C
Symbolic constants are identifiers that represent constant values. Once defined, their
values cannot be changed throughout the program. They make code more readable,
maintainable, andless error-prone.
In C, symbolic constants are defined using the
#definepreprocessor directive.
Syntax:
#defineCONSTANT_NAME value
Note:There isno semicolonat the end of a
#definestatement.
Examples:
#define PI 3.14159
#define MAX 100
#define NAME "Krishnamurthy"
#define TRUE 1
#define FALSE 0
Thesedefinitionstellthecompilertoreplaceeveryoccurrenceofthesymbolicnamewith
its value before compilation.
Example Program:
#include <stdio.h>
#define PI 3.14159
#define RADIUS 5
void main()
{
float area;
area = PI * RADIUS * RADIUS;
printf("Area of circle = %.2f\n", area);
}
Header Files in C
Header files in C contain declarations of functions, macros, and definitions used in
programs. They allow code reuse, modular programming, and simplify complex
operations by providing pre-written functions.
We can include a header file in a program using the
#includepreprocessor directive:
#include <header_file_name.h>
1.
stdio.h(Standard Input/Output Header)
This is one of the most commonly used header files inC.Itprovidesfunctionsforinput
and output operations.
Function Description
printf()
Prints output to the screen
scanf()
Takes input from the user
getchar()
Reads a single character
putchar()
Writes a single character
gets()/
puts() Reads/writes strings(deprecated in modern C)
Example:
#include <stdio.h>
void main()
{
printf("Hello, World!\n");
}
2.
conio.h(Console Input/Output Header)
This is a non-standard header file used in Turbo C/C++ and DOS-based compilers(not
available in GCC/Linux). It provides functions for console input and screen handling.
Function Description
clrscr()
Clears the screen
getch()
Reads a character (without echo)
getche()
Reads a character (with echo)
textcolor()/
textbackground() Sets color attributes
Example:
#include <conio.h>
int main() {
clrscr();
getch();
return 0;
}
3.
math.h(Mathematics Functions Header)
Provides functions to perform complex mathematical operations.
Function Description
sqrt(x)
Square root
pow(x, y)
x raised to the power y
,
sin(x)
,
cos(x) tan(x) Trigonometric functions
,
log(x)
exp(x) Logarithmic and exponential functions
fabs(x)
Absolute value of float
Example:
#include <math.h>
void main() {
double result = sqrt(25);
}
4.
string.h(String Handling Header)
Provides functions to manipulate strings (character arrays).
Function Description
strlen(s)
Returns the length of string
s
strcpy(a, b)
Copies string
binto
a
strcat(a, b)
Concatenates
bto end of
a
strcmp(a, b)
Compares two strings
strrev(s)
Reverses a string(compiler dependent)
Example:
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[] = " World";
strcat(str1, str2);
return 0;
}
5.
ctype.h(Character Handling Header)
Provides functions to test and manipulate characters.
Function Description
isalpha(ch)
Checks if character is a letter
isdigit(ch)
Checks if character is a digit
islower(ch)
Checks if lowercase
isupper(ch)
Checks if uppercase
toupper(ch)
Converts to uppercase
tolower(ch)
Converts to lowercase
Example:
#include <ctype.h>
int main() {
char ch = 'a';
ch = toupper(ch); // ch becomes 'A'
return 0;
}