C Program
C Program
C Program
1. Sequential Structure
• Sequential structure refers to line by line execution of statements in the same
order they appear. It is also known as straight line structure.
• It doesn’t have any jump, branch or looping statements.
• The flow of control passes from one statement to next in sequence. By which that
the control flows in straight line executing one statement to another sequentially
from top to down and left to right.
• For example
START
LOAD A
LOAD B
SUM A, B
STORE SUM
END
2. Selection or Branching Structure
• Selection is a two-way branching structure because the flow of control follows
either one of two paths.
• The control first tests the condition and makes decision. If the condition is “true”
or satisfied, then it follows the “true” path statement and if the condition doesn’t
satisfy, then if follows the “false” path statement.
• So, the selection is a method of selecting one of two or more paths of
computations. The decision can be based on comparison of two variables or sign
of two variables etc.
• The selection structure is similar to IF-THEN-ELSE statements as shown below.
IF percentage >= 60
THEN
Division = “first”
ELSE
Division = “second”
3. Iteration or Looping Structure
• Looping is a programming structure that repeats a sequence of instructions until a
specific condition is met.
• A loop is a statement that repeats over and over, while a certain condition is true.
Or, to state it another way, it runs until a condition is false.
• There are two types of loops.
1. If the operation is repeated for a fixed number of times, then the loop is
called ‘fixed loop’. In fixed loop, the values of the variable inside the loop
do not have any effect on the number of iterations.
2. The second loop is called ‘variable loop’ in which the operations are
repeated until a specific condition met. In ‘variable loop’ the number of
iterations may vary. For example, searching a number within a group of
number organized randomly.
• FOR, WHILE, DO-WHILE are some examples of looping structure. For example
WHILE (Percentage >= 80)
Distinction = Distinction + 1
ENDWHILE
5.6. Programming Design Tools
Computers are problem solving devices and it is an electronic programmable machine
that requires a set of instructions to perform tasks. To facilitate a computer to solve
problems effectively, clear and concise instructions must be provided to it. So, program
design tools are tool used to developed program.
Program development follows almost the same step for any problem-solving tasks. There
are five major steps in the process of program development. They are
1. Defining Problem: It involves the problem analysis, and specifying the input,
process and output required.
2. Planning the Solution: In this phase computer related work begins. It is a
structure or detail design phase. We plan the solution to the given problem using
standard program development tools. Program development tools helps to
visualize what the program is going to do and how it is going to do.
3. Coding the Program: Once the design has been developed and reviewed, the
next step is the actual writing of the program called coding. Coding is the process
of translation from a detailed design to program statements in a programming
language.
4. Testing/modifying The Program: Testing is the process of evaluating a newly
developed program to check if it generates desired output or not.
5. Documentation the Program: Documentation is the process of collecting,
storing and maintaining a complete record of system and other documents used or
prepared during the different phase of the life cycle of system.
There are many types of program design tools. Some of them are algorithm, flowchart
and pseudo code.
1. Algorithm
1. An algorithm is the step wise logical instructions written in any human
understandable language to solve particular problem in a finite amount of time. It
is written in simple English language.
2. General features of an algorithm
• Includes clear specification of input.
• Uses internal variables
• Provide clear prior specification of program steps.
• Use ‘goto’ to transfer the control to a step other than next.
• Use conditional (if… then… else) and looping (bounded loops, while and
until loops).
• Use of subroutines to perform subtasks.
• Use termination condition.
3. Algorithm to add 3 numbers and print their sum:
• START
• Declare 3 integer variables num1, num2 and num3.
• Declare an integer variable sum to store the resultant sum of the 3
numbers.
• Print the value of variable sum
• END
4. Write an algorithm to calculate simple interest
• Step 1: Start
• Step 2: Read Principal Amount, Rate and Time
• Step 3: Calculate Interest using formula SI= ((amount*rate*time)/100)
• Step 4: Print Simple Interest
• Step 5: Stop
Characteristics of an algorithm
1. Finiteness: An algorithm should use finite number of logical steps and
termination after executing those steps.
2. Definiteness: Each step must be defined precisely and unambiguously and must
be self-explanatory.
3. Input: An algorithm must have zero, one or more legal or valid input sets.
4. Output: An algorithm must have one or more outputs as a function of input and
process.
5. Effectiveness: Every step should be executed exactly and in finite time and give
the desire results.
6. Design Aid: An algorithm is a basis for developing the flowchart and helps
designing the solution effectively and efficiently.
7. No standard format or syntax
8. Language independent
2. Flowchart
A flowchart is simply a graphical representation of steps. It shows steps in sequential
order and is widely used in presenting the flow of algorithms, workflow or processes.
Typically, a flowchart shows the steps as boxes of various kinds, and their order by
connecting them with arrows.
Flowchart facilitates the communication between the programmer and business
people.
Flowchart plays a vital role in programming and quite helpful in understanding the
logic of complicated and lengthy problems.
Once the flowchart is drawn, it is easy to write the program in any high level
language.
Different flowchart shapes have different conventional meanings. The meanings of
some of the more common shapes are as follows:
Start Input/Output
Process Document
Connector
Decision Line
Draw a flowchart to add two numbers.
1. Absolute Binary
• It can be used to represent only the numbers. In absolute binary the whole number
is converted to binary number. For example, 45 is represented as 101101.
• A code that is used to represent the digital data converted from analog data is
called gray code or absolute binary code.
2. BCD (Bi nary Coded Decimal)
• In the BCD code, 4 bits represent a decimal number. For example, 2 is
represented as 0010. If decimal number consists of more than 1 digit, then each
digit is represented individually by its 4-bit binary equivalent. For example, 123 is
represented as 0001 0010 0011.
3. EBCDIC
• EBCDIC stands for extended binary coded decimal interchange code. It is
extended version of BCD. 6-bit BCT cold represent only the alphabets and
numbers. It can’t represent all characters and symbols. EBCIDC uses 8-bits
representation. So, it can represent all characters and symbols of the English. The
8 bits are divided into zone bit (first 4 bits) and digit (last 4 bits).
• For example, A is represented as 1100 0001, X as 1110 0111, + as 0100 0000, =
as 0111 1110, etc.
4. ASCII
• ASCII stands for American Standard Code for Information Interchange. It is used
to represent all the uppercase and lowercase, alphabets, numbers, punctuation
mark, and special symbols. Initially, it is used as 7-bit code but later it is modified
to 8-bit code. 8-bit ASCII can represent 256 characters.
• For example, C is represented as 01000011, was 01010111, $ as 00100100, etc.
5. Unicode
• The Unicode worldwide character standard uses 4 bytes i.e. 32 bits to represent
each letter, number and symbol. It can be used to represent more than 4 billions
(4,294,967,296) different characters and symbols. It is unique for every language
characters and symbols such as Devanagari, Newari, Maithali, Japanese, Russian,
etc.
• One major advantage of Unicode is that it is compatibility with ASCII code.
5.8.1. Introduction to C
• C programming is a general-purpose, procedural, imperative computer programming
language developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to
develop the UNIX operating system.
• C is the most widely used computer language.
5.8.2. Why to learn C?
• C programming language is a MUST for students and working professionals to become
a great Software Engineer specially when they are working in Software .
• some of the key advantages of learning C Programming:
1. Easy to learn
2. Structured language
3. It produces efficient programs
4. It can handle low-level activities
5. It can be compiled on a variety of computer platforms
5.8.3. Facts About C
• C was invented to write an operating system called UNIX.
• C is a successor of B language which was introduced around the early 1970s.
• The language was formalized in 1988 by the American National Standard Institute
(ANSI).
• The UNIX OS was totally written in C.
• Today C is the most widely used and popular System Programming Language.
• Most of the state-of-the-art software have been implemented using C.
5.8.4. Application of C Programming
• Operating Systems
• Language Compilers
• Assemblers
• Text Editors
• Print Spoolers
• Network Drivers
• Modern Programs
• Databases
• Language Interpreters
• Utilities
5.8.5. Structure of C Program
• A program is a sequence of instruction. Instruction of C program is written as statement.
• A Statement is terminated by semicolon (;).
• One or more statements form a block (compound) statement enclosed within a pair of
braces, i.e.{}.
• Every C program consists of one or more functions and every C program must contain a
special function name main().
• Comment is written within the delimiters /* and */
HELLO WORLD EXAMPLE
• A C program basically consists of the following parts −
1. Preprocessor Commands
2. Functions
3. Variables
4. Statements & Expressions
5. Comments
• Let us look at a simple code that would print the words “Hello World“
#include <stdio.h>
#include <conio.h>
#include <math.h> sqrt(5,2); 5*5=25
int main(){
/* my first program in c */
printf(“hello world”);
return 0;
}
• Let us take a look at the various parts of the above program –
1. The first line of the program #include <stdio.h> is a preprocessor command,
which tells a C compiler to include stdio.h file before going to actual compilation.
2. The next line int main() is the main function where the program execution begins.
3. The next line /*…*/ will be ignored by the compiler and it has been put to add
additional comments in the program. So such lines are called comments in the
program.
4. The next line printf(…) is another function available in C which causes the
message “Hello, World!” to be displayed on the screen.
5. The next line return 0; terminates the main() function and returns the value 0.
5.8.6. Compiling Process
1. Editor
• In general, an editor refers to any program capable of editing files. Good
examples are image editors, such as Notepad, WordPad, etc.
• The term editor is commonly used to refer to a text editor, which is a software
program that allows users to create or manipulate plain text computer files. They
are often used in the field of computer programming.
• Notepad and WordPad - Microsoft Windows included text editors
• TextEdit - Apple computer text editor
• Word - Word processor for Windows and Apple computers
• Microsoft Edit - MS-DOS text editor
• Notepad++ - Our favourite free text editor, Notepad++ is a powerful alternative
to Windows Notepad
2. Preprocessor
• In computer science, a preprocessor is a program that processes its input data to
produce output that is used as input to another program.
• The most common example of this is the C preprocessor, which takes lines
beginning with '#' as directives.
3. Compiler
• Compiler is a computer program that translates computer code written in
one programming language (the source language) into another language
(the target language).
• The name "compiler" is primarily used for programs that translate source
code from a high-level programming language to a lower level
language (e.g., assembly language, object code, or machine code) to create
an executable program.
• Compiler translates the pre-processed source code into machine language that
consists of sequence of 0s and 1s.
• If compiler find any error, the compilation may continue in order to detect further
error but computer won’t produce any compiled program. If it does not find any
error, then it produce object code
4. Linker
• A linker or link editor is a computer system program that takes one or
more object files (generated by a compiler or an assembler) and combines them
into a single executable file, library file, or another "object" file.
• Linkers can take objects from a collection called a library
• In case of C, the standard input and output function are contained in library file
stdio.h, so most basic program will require a library function. After compilation
of the program files, computer must somehow link these separate pieces to form
executable program. The linking is done by linker. The executable file will have
extension .exe.
5. Executable file
• The text editor produces .c source files, compiler converts this .c file to .obj
object file, linker produces .exe (executable file) from .obj file.
• We can then run .exe files as an application to generate simply output by typing
their names at the DOS prompt or run using windows menu.
• Many compilers provide the programmer with debugging tools, such as
displaying informative error messages indicating the source of many of the errors,
colored-coded source code, etc.
5.8.7. C Preprocessor and Header Files
• C preprocessor is often known as a macro processor and used automatically by the C
compiler to transform the program before compilation.
• All preprocessor commands begin with a hash symbol (#).
• It is called a macro processor because it allows us to define macros, which are brief
abbreviations for longer constructs. For example
• #define PRINT(x) printf(“#x = %d”, (x) )
• #define SQR(x) ( (x) * (x) )
• #define CUBE ( (x)*(x)*(x) )
• #define PER_CENT(x, y) ( (x) * 100.0 /(y) )
• Header file define certain values, symbols and operations which is included in the file to
obtain access to its contents. The header file has suffix .h.
• It contain only prototype of the function in the corresponding source file. For e.g., stdio.h
contain the prototype for printf while the corresponding source file contains its
definition.
• It saves time for writing and debugging the code.
5.8.8. Character Set Used in C
• A character set in C contains any alphabet, digit or special symbol used to represent
information.
• The following table shows the valid alphabets, numbers and special character allowed in
C.
Digits 0 to 9
1count count1
hi!there hi_there
high…level high_level
S.I. SI or S_I
5.8.12. Keywords
• Keywords is a reserved word that has standard and predefined meanings in C.
• Keywords are special words in C programming which have their own predefined meaning.
The functions and meanings of these words cannot be altered.
• Some keywords in C Programming are:
for float go if
float 4 byte
double 8 byte
5.8.15. Specifier
• The basic data type can have various specifiers preceding them. A type of specifier alters the
meaning of the data type to more precisely fit a specific need.
• The four specifiers are signed, unsigned, long and short.
• The data types int can be modified as signed, unsigned, short and long. The char can be
modified as unsigned and signed. The float can be modified as double or long double.
5.8.16. Statement
• A statement consists of single line of code called simple statement or a series of statement in
a block called compound statement. The statement is also known as expression as well as
sentence in English.
• For Example
1. Simple Statement
• printf(“value of x is %d”,x);
2. Compound statement
{
int l,b,Area_of_rectangle;
Area_of_rectangle = l*b;
printf(“Area of rectangle is %d”, Area_of_rectangle);
}
Escape Sequences
• Escape sequences are used in the programming languages C . An escape sequence is a
sequence of characters that does not represent itself when used inside a character or
string literal, but is translated into another character or a sequence of characters that may be
difficult or impossible to represent directly.
• In C, all escape sequences consist of two or more characters, the first of which is the
backslash, \ (called the "Escape character"); the remaining characters determine the
interpretation of the escape sequence.
• Some common escapes sequences are listed below.
1. \n : New Line
2. \t : Horizontal Tab
3. \r : Line Feed or Carriage Return (Takes the cursor to the beginning of line in which
it is currently placed)
4. \f : Form Feed
5. \b : Move cursor one position the left of its current position
6. \" : Double Quote
7. \\ : Display Backslash
8. \a : Alert (It alerts by sounding the speaker inside computer)
9. \0 : It represents NULL character
5.8.17. Operator and Expressions
Operator
An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. C language is rich in built-in operators and provides the following types of operators −
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Assignment Operators
• Conditional Operator
• Bitwise Operator
• Special Operator
1. Arithmetic Operator
Arithmetic operator is a symbol used for basic mathematical calculations.
The following table shows all the arithmetic operators supported by the C language. Assume
variable A holds 10 and variable B holds 20, then −
Example
Operator Description Example
2. Relational operator
Relational operator is a symbol that determines the relationship between two different
operands.
The following table shows all the relational operators supported by C. Assume
variable A holds 10 and variable B holds 20 then
• Examples
Operator Description Example
3. Logical Operator
Logical operator is a symbol that logically connects the logical expression i.e. it is used to
connect two or more expressions.
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then –
Examples
4. Assignment Operator
• Assignment operator is a symbol to assign value or a result of an expression to an identifier.
• Syntax, identifier = expression. Example x = 10; y = a+b;
• C also allows multiple assignment statement using =, for example, int a=b=3;
• The following table lists the assignment operators supported by the C language
= Simple assignment operator. Assigns values from C = A + B will assign the value of A
right side operands to left side operand + B to C
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
& Binary AND Operator copies a bit to the result if it exists in both (A & B)
operands. = 12,
i.e.,
0000
1100
^ Binary XOR Operator copies the bit if it is set in one operand but (A ^ B)
not both. = 49,
i.e.,
0011
0001
~ (~A ) =
Binary One's Complement Operator is unary and has the effect of ~(60),
'flipping' bits. i.e,. -
0111101
<< Binary Left Shift Operator. The left operands value is moved left A << 2
by the number of bits specified by the right operand. = 240
i.e.,
1111
0000
>> Binary Right Shift Operator. The left operands value is moved A >> 2
right by the number of bits specified by the right operand. = 15 i.e.,
0000
1111
6. Special Operator
• The following table lists the bitwise operators supported by C.
Operators Description
right-to-left
Prefix increment/decrement
Unary plus/minus
++ —
Logical negation/bitwise
+–
complement
!~
Cast (convert value to
2. (type)
temporary value of type)
*
Dereference
&
Address (of operand)
sizeof
Determine size in bytes on this
implementation
left-to-right
3. * / % Multiplication/division/modulus
left-to-right
4 + – Addition/subtraction
left-to-right
5 << >> Bitwise shift left, Bitwise shift right
left-to-right
7 == != Relational is equal to/is not equal to
left-to-right
8 & Bitwise AND
left-to-right
9 ^ Bitwise exclusive OR
left-to-right
10 | Bitwise inclusive OR
left-to-right
11 && Logical AND
left-to-right
12 || Logical OR
right-to-left
13 ?: Ternary conditional
Assignment right-to-left
=
Addition/subtraction assignment
+= -=
Multiplication/division assignment
*= /=
14 Modulus/bitwise AND assignment
%= &=
Bitwise exclusive/inclusive OR
^= |=
assignment
<<= >>=
Bitwise shift left/right assignment
left-to-right
15 , Comma (separate expressions)
Expressions
• An expression is a formula in which operands are linked to each other by the use of
operators to compute a value. An operand can be a function reference, a variable, an array
element or a constant.
• For Example, c = a+b
In the above expression, plus character (+) and assignment (=) are an operator, and a, b
and c are the three operands.
• There are four types of expressions exist in C:
1. Arithmetic expressions
2. Relational expressions
3. Logical expressions
4. Conditional expressions
• Each type of expression takes certain types of operands and uses a specific set of
operators. Evaluation of a particular expression produces a specific value.
5.8.18. Typecasting and Conversion
• Typecasting is converting one data type into another one. It is also called as data
conversion or type conversion.
• 'C' programming provides two types of typecasting operations. They are
1. Implicit
2. Explicit
1. Implicit int x =10; float b; b = x, 10.0000
• Implicit type casting means conversion of data types without losing its original
meaning. This type of typecasting is essential when you want to change data
types without changing the significance of the values stored inside the variable.
• This type of conversion is done automatically by the compiler itself.
2. Explicit
• The type conversion performed by the programmer by posing the data type of the
expression of specific type is known as explicit type conversion.
• The explicit type conversion is also known as type casting.
• Syntax, (data_type) expression; b = (float) x
C Program to Illustrate Typecasting and Conversion
#include<stdio.h>
int main(){
float x;
int num, den;
printf("Enter the value of numerator and denumerator");
scanf(“ %d %d”, &num, &den);
x = num/den
printf(“value of x by implicit conversion is %f”,x);
x = (float) num/ (float) den;
pintf(“value of x by explicit conversion is %f”, x);
return 0;
}
5.8.19. Introduction to Library Function
• Library functions are built-in functions that are grouped together and placed in a common
location called library.
• Each function here performs a specific operation. We can use this library functions to get
the pre-defined output.
• All C standard library functions are declared by using many header files. These library
functions are created at the time of designing the compilers.
• The prototype and data definitions of these functions are present in their respective
header files. To use these functions we need to include the header file in our program. For
example,
• If you want to use the printf() and scanf() functions, the header file <stdio.h> should be
included.
S.N. Function & Description
1 printf()
This function is used to print the all char, int, float, string etc., values onto the output
screen.
2 scanf()
This function is used to read data from keyboard.
3 getc()
It reads character from file.
4 gets()
It reads line from keyboard.
5 getchar()
It reads character from keyboard.
6 puts()
It writes line to o/p screen.
7 putchar()
It writes a character to screen.
8 fopen()
All file handling functions are defined in stdio.h header file.
9 fclose()
Closes an opened file.
10 getw()
Reads an integer from file.
11 putw()
Writes an integer to file.
12 fgetc()
Reads a character from file.
13 putc()
Writes a character to file.
14 fputc()
Writes a character to file.
15 fgets()
Reads string from a file, one line at a time.
16 f puts()
Writes string to a file.
17 feof()
Finds end of file.
18 fgetchar
Reads a character from keyboard.
19 fgetc()
Reads a character from file.
20 fprintf()
Writes formatted data to a file.
21 fscanf()
Reads formatted data from a file.
22 fputchar
Writes a character from keyboard.
23 fseek()
Moves file pointer to given location.
24 SEEK_SET
Moves file pointer at the beginning of the file.
25 SEEK_CUR
Moves file pointer at given location.
26 SEEK_END
Moves file pointer at the end of file.
27 ftell()
Gives current position of file pointer.
28 rewind()
Moves file pointer to the beginning of the file.
29 putc()
Writes a character to file.
30 sprint()
Writes formatted output to string.
31 sscanf()
Reads formatted input from a string.
32 remove()
Deletes a file.
33 flush()
Flushes a file.
%c Unsigned char
%s String
int main()
{
int n, s, c;
printf("Enter the number");
scanf("%d", &n);
s = pow(n,2);
c = n*n*n;
printf("Square of number is %f \nCube of number is %f",(float)s, (float)c);
return 0;
}
/*A
AB
ABC
ABCD
A B C D E */
#include<stdio.h>
int main()
{
printf("A");
printf("\nA\tB");
printf("\nA\tB\tC");
printf("\nA\tB\tC\tD");
printf("\nA\tB\tC\tD\tE");
return 0;
}
// program to find out remainder
#include<stdio.h>
int main()
{
int a, b, r;
printf("Enter the value of a and b");
scanf("%d %d",&a,&b);
r = a%b;
printf("The remainder of number is %d", r);
return 0;
}
//simple interest
#include<stdio.h>
int main()
{
float p, t, r,SI;
printf("Enter the principal amount:");
scanf("%f",&p);
printf("\nEnter the time in year:");
scanf("%f", &t);
printf("\nEnter the rate:");
scanf("%f",&r);
SI = p*t*r/100;
printf("\nSimple Interest amount:%f",SI);
return 0;
}
// Symbolic constant
#include<stdio.h>
#define PI 3.14
int main()
{
float r, area;
printf("Enter the radius of circle");
scanf("%f", &r);
area = 3.14*r*r; // literal constant
printf("\nArea of circle:%f",area);
return 0;
}
//Sum of n natural number
#include<stdio.h>
int main()
{
int n, sum = 0;
printf("Enter the value of n");
scanf("%d",&n);
sum = n*(n+1)/2;
printf("The sum of n natural number is %d",sum);
return 0;
}