C Programming cs25c01
C Programming cs25c01
MODULE-1
Introduction to C: Problem Solving, Problem Analysis Chart, Developing an Algorithm,
Flowchart and Pseudocode, program structure, Compilation & Execution process, Interactive
and Script mode, Comments, Indentation, Error messages, Primitive data types, Constants,
Variables, Reserved words, Arithmetic, Relational, Logical, Bitwise, Assignment, Conditional
operators, Input/Output Functions, Built-in Functions.
Practical: Create Problem Analysis Charts, Flowcharts and Pseudocode for simple C programs
(Minimum three).
Define Computer:
Computer is a calculating machine, which accepts data through input device, processes it using
processing device and give the result through output device. Computer is an electro-
mechanical machine. It consists of electronic parts (IC‟S) electrical (motors, fan) and
Mechanical parts (Outer cover, keyboard).
Characteristics of Computer:
The following are the characteristics of a computer:
1. Speed: Computer can process the data at an extremely high speed.
2. Accuracy: Computer will produce accurate result.
3. Reliability: It is the measurement of performance of computer.
4. Versatile: Computer can be used for different purpose.
5. Storage capacity: computer can store large amount of data.
Hardware: All the physical parts of the computer is called hardware. You can touch and feel.
Example: Keyboard, Mouse, outer cover, IC‟s
Software:Programs written for the computer is called software. Ex: MS-Word, C program,
Windows 10 OS
Operating System:It is the interface between user of the computer and computer hardware.
Text Editor: It is an application program which allows user to type text and edit it.
Computer Languages:
Machine Level Language (MLL) : Binary language it use 1 and 0. It is the only language
understood by the computer.
Assembly Level Language (ALL) : It uses short notations like add, sub, mul and div etc.
It cannot be understood by the computer. Hence ALL needs to be converted into MLL
Assembler: is the program, which converts ALL to MLL and vice versa.
Example for ALL: ALL 8085, ALL 8086
High Level Language (HLL) : It is English like language. It is easy to understand by the
programmer.
It cannot be understood by the computer.
HLL needs to be converted into MLL.
Compiler or Interpreter will be used to convert HLL to MLL and vice versa.
Compiler: converts HLL to MLL in one step.
1.Problem solving
Problem solving in computer programming is the iterative process of understanding a problem,
devising a detailed step-by-step solution (an algorithm), and translating that solution into a
computer program. Key stages include defining and analyzing the problem to determine inputs
and outputs, developing an algorithm using natural language or flowcharts, coding the
algorithm into a programming language, and testing and debugging the program to ensure it
works correctly. This core skill allows programmers to break down complex issues into
manageable steps for a computer to execute.
Evaluate the overall effectiveness of the solution and refine it for clarity, efficiency, and
completeness.
3.Algorithm:It is the step-by-step procedure to solve a given problem. It will accept input,
processes and gives output. It is simple to represent and it is independent of programming
language.
Example:
I. Write an algorithm to exchange the contents of two variable.
1. [Start]
y <- t
4. [Output – to print the swapped numbers]
Write (x,y)
5. [Stop]
II. Write an algorithm to find the area of a triangle given base and height.
1. [Start]
2. [Input – Base and height of the triangle]
Read(b,h)
3. [Process – to compute the area of the triangle]
a <- 0.5*b*h
4. [Output the area]
Write (a)
5. [Stop]
III. Write an algorithm to find the area of a triangle given its 3 sides.
1. [Start]
2. [Input – 3 sides of the triangle]
Read(a,b,c)
3. [Process – to compute half perimeter]
s<- (a+b+c)/2.0
4. [Process to compute the area ]
a <- sqrt( s * (s-a) * (s-b) * (s-c) )
5. [Output the area]
Write (a)
6. [Stop]
VI. Write an algorithm to compute the sum of first ‘n’ natural numbers
1. [Start]
2. [Input a number]
Read(n)
3. [Initialize]
sum < - 0
4. [compute the sum of first „n‟ numbers ]
for i <- 1 to n step 1
sum <- sum + i
end for
5. [Display the sum]
Write(sum)
6. [Stop]
VII. Write an algorithm to compute the factorial of the given number
1. [Start]
2. [Input a number]
Read(n)
3. [Initialize]
fact < - 1
4. [compute the factorial of „n‟ ]
for i <- 1 to n step 1
fact <- fact* i
end for
5. [Display the sum]
Write(fact)
Downloaded by divya rani ([email protected])
lOMoARcPSD|48469774
6. [Stop]
4. Flow chart:
It is the pictorial representation of an algorithm. All the steps are drawn in the form of
different shapes. Commonly used symbols for flow chart are :
5. Pseudocode
Pseudocode is an informal, high-level description of an algorithm or program logic. It uses a
mix of natural language (like English) and common programming constructs to outline the
steps involved in a process, without adhering to the strict syntax rules of any specific
programming language.
Human-readable:
It is designed for human understanding, not for execution by a computer.
Language-independent:
It can be understood by programmers regardless of their preferred programming language.
Focus on logic:
It emphasizes the sequence of operations and decision-making within an algorithm.
Informal syntax:
While it often uses keywords like IF, ELSE, FOR, WHILE, PRINT, etc., it does not require
precise punctuation or grammar like actual code.
Algorithm design:
It helps in planning and structuring algorithms before writing actual code.
Communication:
It facilitates communication and understanding of algorithms among developers, designers,
and project managers.
Problem-solving:
It allows focusing on the logical steps to solve a problem without getting bogged down by
language-specific syntax.
Documentation:
It can serve as a form of documentation for algorithms.
Example
START
DECLARE variable 'number'
GET input from user and STORE in 'number'
A Pseudocode is a step-by-step
A Flowchart is pictorial representation of
description of an algorithm in code like
flow of an algorithm.
structure using plain English text.
Flowchart Pseudocode
This is a way of visually representing data, These are fake codes as the word pseudo
these are nothing but the graphical means fake, using code like structure but
representation of the algorithm for a better plain English text instead of programming
understanding of the code language
6. Introduction to C
C is a programming language developed at AT & T‟s Bell Laboratories of USA in 1972. It
was designed and written by a man named Dennis Ritchie. In the late seventies C began to
replace the more familiar languages of that time like PL/I, ALGOL, etc.
Interpreter
Assembler
Compiler and interpreter are used to convert the high level language into machine
level language. The program written in high level language is known as source program and
the corresponding machine level language program is called as object program. Both
compiler and interpreter perform the same task but there working is different. Compiler read
the program at-a-time and searches the error and lists them. If the program is error free then
it is converted into object program. When program size is large then compiler is preferred.
Whereas interpreter read only one line of the source code and convert it to object code. If it
check error, statement by statement and hence of take more time.
On Mac OS X, CodeWarrior and Xcode are two IDEs that are used by many programmers.
Under Windows, Microsoft Visual Studio is a good example of a popular IDE. Kylix is a
popular IDE for developing applications under Linux. Most IDEs also support program
development in several different programming languages in addition to C, such as C# and
C++.
Example:
// Documentation
/**
* file: sum.c
* author: you
* description: program to find sum.
*/
// Link
#include <stdio.h>
// Definition
#define X 20
// Global Declaration
int sum(int y);
// Main() Function
int main(void)
{
int y = 55;
printf("Sum: %d", sum(y));
return 0;
// Subprogram
int sum(int y)
{
return y + X;
}
The compilation is the process of converting the source code of the C language into
machine code. As C is a mid-level language, it needs a compiler to convert it into an
executable code so that the program can be run on our machine.
The C program goes through the following phases during compilation:
Working Process
In the context of C programming, "interactive mode" and "script mode" refer to how
C programs are typically developed and executed, although the terminology is more
commonly associated with interpreted languages like Python.
In a C debugger, you can set breakpoints, step through code line by line, inspect
variable values, and even modify variables during runtime. This provides immediate
feedback on specific parts of your code.
Debugging, testing small code snippets, understanding program flow, and exploring
variable states during execution.
The C source code is compiled into an executable binary file using a C compiler (like
GCC). This executable is then run as a complete program.
8. Comments
Comments in C programming are non-executable statements within the source code that are
ignored by the compiler. Their primary purpose is to provide explanations, documentation,
and notes for human readers of the code, improving readability and maintainability.
9. Indentation in C
10.Errors Meassages
In C programming, "errors" refer to issues that prevent a program from compiling or
executing correctly. These errors can be categorized into several types:
Syntax Errors:
Occur when the code violates the grammatical rules of the C language.
Examples include missing semicolons, unbalanced brackets, or misspelled keywords.
Detected by the compiler during the compilation phase, preventing the creation of an
executable.
Linker Errors:
Arise during the linking phase, when the linker attempts to combine object files and
libraries to create a final executable.
Occur if the linker cannot find the definitions for functions or variables that have been
declared in the code but not defined (e.g., missing library files).
Runtime Errors:
Happen while the program is executing.
Often caused by illegal operations, such as division by zero, accessing invalid memory
locations, or attempting to open a non-existent file.
Can lead to program crashes or unexpected behavior.
Logical Errors:
The program compiles and runs without crashing, but it produces incorrect or
unexpected output.
Result from flaws in the program's algorithm or logic, where the code does not correctly
implement the intended functionality.
Compiler Warnings:
Not strictly errors, but indications of potential issues in the code that might lead to
problems later.
Examples include uninitialized variables or non-standard coding practices.
While warnings do not prevent compilation, it is best practice to address them to avoid
future errors.
Preprocessor Errors:
Occur during the preprocessor stage, before compilation.
Can be caused by issues with preprocessor directives, such as incorrect use
of #include or inability to locate a referenced header file.
Memory Errors:
A specific type of runtime error related to memory management.
Examples include memory leaks (failure to free dynamically allocated memory) or
attempting to access memory that has already been freed.
11.C Tokens: Character set, Identifiers, Keywords, constants, Data types, type
qualifiers, Declaration and Initialization of variables.
Token: The smallest individual units in a program are called tokens. The „C‟
1. Character set
2. Keywords
3. Identifiers
4. Constants
5. Operators
Character set:
\b backspace
\a audible bell
\v vertical tab
\t horizontal tab
\f form feed
\r carriage return
\” double quotes
\‟ single quotes
\\ back slash
\r is a carriage return character; it tells your terminal emulator to move the cursor at the
start of the line.
The cursor is the position where the next characters will be rendered.
So, printing a \r allows overriding the current line of the terminal emulator.
Example Program:
#include<stdio.h> main()
{
printf("Backspace Character\b");
Downloaded by divya rani ([email protected])
lOMoARcPSD|48469774
Output:
12.1 Keywords:
Keywords are reserved words. All keywords have fixed meanings. Keywords serve as
basic building blocks for program statements. In „C‟, there are 32 keywords. All
keywords must be written in lower case.
12.2 Identifiers: Identifier refers to the names of the variables, functions and arrays.
12.3 Constants:
Constants refer to fixed values that do not change during the execution of a program.
Integer constants:
Real constants:
Note: Character constants have integer values known as ASCII values. Since each
character constant represent an integer value, so character arithmetic is possible.
Example Program:
#include<stdio.h> main()
{
char ch='a'; printf("ch=%c\n",ch);
Output:
ch=a
ASCII value of 'a'=97
//Character Arithmetic
#include<stdio.h> main()
{
Output:
ch=a
ASCII value of c=99
12.4 variables in C:
In C programming, a variable is a named storage location in memory used to hold
data. Variables are fundamental for storing and manipulating information during
program execution.
Initialization: Variables can be assigned a value at the time of declaration or later in the
program.
Naming Rules:
Variable names must follow specific rules:
They can contain letters (A-Z, a-z), digits (0-9), and underscores (\_).
They must begin with a letter or an underscore.
They are case-sensitive (e.g., myVar and myvar are different).
They cannot be C reserved keywords (e.g., int, float, if).
They cannot contain spaces or other special characters.
Scope and Lifetime:
Variables have a defined scope (where they are accessible in the code) and lifetime (how
long they exist in memory). Common types include:
Local variables: Declared inside a function, accessible only within that function,
and exist only while the function is executing.
Global variables: Declared outside any function, accessible throughout the entire
program, and exist for the program's entire execution.
Static variables: Retain their value between function calls.
Usage:
Once declared and potentially initialized, variables can be used in expressions,
assignments, function calls, and input/output operations.
Example:
int num1 = 5;
int num2 = 3;
int sum = num1 + num2; // Using variables in an expression
printf("Sum: %d\n", sum); // Displaying the variable's value
12.5 Data types:
Data type specifies which type of data that we are storing in a variable. There are 3 types
of data types.
i. Integer
ii. Floating point
iii. Character
iv. Double precision floating point
Integer:
Signed integer uses one bit for sign and 15 bits for the magnitude of the number.
Formula to find number of bits occupied by data type when number of bytes is known:
-2n-1 to 2n-1 - 1
Floating point or real numbers are stored in 32 bits (on all 16 bit and 32 bit machines)
with 6 bits precision.
3 classes of floating point types:
i. float
ii. double
iii. long double
Character types:
#include<stdio.h> main()
{
'C' supports a feature known as “type definition” that allows users to define an
identifier that would represent an existing data type.
The user defined data type identifier can later be used to declare variables.
General form:
where type is any existing data type, identifier is a new name given to the data
type.
Example program:
#include<stdio.h> int main()
{
Output:
Enter 2 values
5
Downloaded by divya rani ([email protected])
lOMoARcPSD|48469774
6
Enter 2 values
1.9
6.7
a=5 b=6
x=1.900000 y=6.700000
Where identifier is a user defined enumerated data type, which can be used to
declare variables which can have one of the values enclosed within the braces
(known as enumeration constants).
After this definition, we can declare variables to be of this 'new' type.
enum identifier v1,v2,…,vn can only have one of the values value1, value2, …, valuen.
The assignments are:
v1=value3;
v5=value1;
Example:
Example program:
#include<stdio.h> main()
{
enum day {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};
enum day weekst,weekend;
weekst=Monday;
weekend=Thursday;
printf("weekst=%d\nweekend=%d\n",weekst,weekend);
}
Output:
weekst=0
weekend=3
1 for value2,
2 for value3,
3 for value4,
4 for value5,
5 for value6,
6 for value7
Example program:
#include<stdio.h> main()
{
Output:
weekst=5
weekend=7
#include<stdio.h> main()
{
Type qualifiers:
We can change the properties of primitive or fundamental data type. There are
two type qualifiers:
Downloaded by divya rani ([email protected])
lOMoARcPSD|48469774
const:
Example program:
1. #include<stdio.h>
2. main()
3. {
4. const int classsize=60;
5. printf("classsize=%d\n",classsize);
6. classsize=classsize*3;
7. printf("classsize=%d\n",classsize);
8. }
Note: The compiler gives an error at line number 6: assignment of read-onlyvariable 'a'.
volatile:
ANSI standard defines qualifier volatile that could be used tell explicitly the compiler that
a variable‟s value may be changed at any time by some external sources (from outside the
program).
Example:
volatile int a;
Example program:
#include<stdio.h>
main()
{
volatile int a=5;
printf("a=%d\n",a);
a=a*4;
printf("a=%d\n",a);
}
Output: a=5 a=20
13. Operator
Downloaded by divya rani ([email protected])
lOMoARcPSD|48469774
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.
Several operators are there those are, arithmetic operator, assignment, increment ,
decrement, logical, conditional, comma, size of , bitwise and others.
1. Arithmetic Operator
This operator used for numeric calculation. These are of either Unary arithmetic
operator, Binary arithmetic operator. Where Unary arithmetic operator required
only one operand such as +,-, ++, --,!, tiled. And these operators are addition,
subtraction, multiplication, division. Binary arithmetic operator on other hand
required two operand and its operators are +(addition), -(subtraction),
*(multiplication), /(division), %(modulus). But modulus cannot applied with
floating point operand as well as there are no exponent operator in c.
Unary (+) and Unary (-) is different from addition and subtraction.
When both the operand are integer then it is called integer arithmetic and the result is
always integer. When both the operand are floating point then it is called floating
arithmetic and when operand is of integer and floating point then it is called mix type
or mixed mode arithmetic . And the result is in float type.
2.Assignment Operator
A value can be stored in a variable with the use of assignment operator. The
assignment operator(=) is used in assignment statement and assignment expression.
Operand on the left hand side should be variable and the operand on the right hand
side should be variable or constant or any expression. When variable on the left hand
side is occur on the right hand side then we can avoid by writing the compound
statement. For example,
int x= y;
int Sum=x+y+z;
The Unary operator ++, --, is used as increment and decrement which acts upon single
operand. Increment operator increases the value of variable by one
.Similarly decrement operator decrease the value of the variable by one. And these
operator can only used with the variable, but cann't use with expression and constant
as ++6 or ++(x+y+z)
It again categories into prefix post fix . In the prefix the value of the variable is
incremented 1st, then the new value is used, where as in postfix the operator is written
after the operand(such as m++,m--).
EXAMPLE
let y=12; z=
++y; y= y+1;
z= y;
Similarly in the postfix increment and decrement operator is used in the operation . And
then increment and decrement is perform.
EXAMPLE
let x= 5; y=
x++; y=x;
x= x+1;
4.Relational Operator
5. Conditional Operator
void main()
{
Downloaded by divya rani ([email protected])
lOMoARcPSD|48469774
is:%d”);
}
Output:
Value is:10
6. Comma Operator
Comma operator is use to permit different expression to be appear in a situation where
only one expression would be used. All the expression are separator by comma and are
evaluated from left to right.
EXAMPLE
int i, j, k, l;
for(i=1,j=2;i<=5;j<=10;i++;j++)
7. Sizeof Operator
Size of operator is a Unary operator, which gives size of operand in terms of byte
that occupied in the memory. An operand may be variable, constant or data type
qualifier.
These operator can operate on integer and character value but not on float and double.
In bitwise operator the function showbits( ) function is used to display the binary
representation of any integer or character value.
In one's complement all 0 changes to 1 and all 1 changes to 0. In the bitwise OR its
value would obtaining by 0 to 2 bits.
As the bitwise OR operator is used to set on a particular bit in a number. Bitwise
AND the logical AND.
It operate on 2operands and operands are compared on bit by bit basic. And hence both
the operands are of same type.
Operator used with one or more operand and return either value zero (for false) or one
(for true). The operand may be constant, variables or expressions. And the expression
that combines two r more expressions is termed as logical expression.
C has three logical operators :
Operator Meaning
&& AND
|| OR
! NOT
Where logical NOT is a unary operator and other two are binary operator. Logical
AND gives result true if both the conditions are true, otherwise result is false. And
logial OR gives result false if both the condition false, otherwise result is true.
15.Input/Output Functions
C programming relies on a set of standard input/output (I/O) functions, primarily found in
the <stdio.h> header file, to interact with the user and external files. These functions facilitate
receiving data from input devices (like the keyboard) and displaying information to output
devices (like the monitor).
#include <stdio.h>
int main() {
int age = 30;
printf("Your age is: %d\n", age);
return 0;
}
scanf(): This is a formatted input function used to read data from the console. It also uses a
format string to specify the expected data type and requires the address of the variable where
the input should be stored (using the & operator).
#include <stdio.h>
int main() {
Downloaded by divya rani ([email protected])
lOMoARcPSD|48469774
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("You entered: %d\n", num);
return 0;
}
getchar(): Reads a single character from the standard input.
putchar(): Writes a single character to the standard output.
gets(): Reads a line of text (including spaces) from the standard input into a character
array. Note: gets() is considered unsafe due to potential buffer overflows and is generally
discouraged in favor of fgets().
puts(): Writes a string to the standard output, followed by a newline character.
START
DECLARE integer num1, num2, sum
DISPLAY "Enter first number: "
READ num1
DISPLAY "Enter second number: "
READ num2
CALCULATE sum = num1 + num2
DISPLAY "The sum is: ", sum
END
2. Program to Find the Larger of Two Numbers
START
DECLARE integer num1, num2
DISPLAY "Enter first number: "
READ num1
DISPLAY "Enter second number: "
READ num2
IF num1 > num2 THEN
DISPLAY num1, " is larger."
Downloaded by divya rani ([email protected])
lOMoARcPSD|48469774
*************************************************************************