0% found this document useful (0 votes)
48 views16 pages

Module I - C

Programming in c

Uploaded by

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

Module I - C

Programming in c

Uploaded by

Smitha Rajesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Programming in c

INTRODUCTION TO C LANGUAGE
C is a procedural programming language. C is a general-purpose high level language that was
originally developed by Dennis Ritchie for the Unix operating system.
Features of C
 Easy to learn
 Structured language
 It produces efficient programs.
 It can handle low-level activities.
 It can be compiled on a variety of computers.

Characteristics of a good program


 Portable − The program or software should run on all computers of same type. By
same type we mean a software developed for personal computers should run on all
PCs. Or a software for written for tablets should run on all tablets having the right
specifications.
 Efficient − A software that does the assigned tasks quickly is said to be efficient.
Code optimization and memory optimization are some of the ways of raising
program efficiency.
 Effective − The software should assist in solving the problem at hand. A software
that does that is said to be effective.
 Reliable − The program should give the same output every time the same set of
inputs is given.
 User friendly − Program interface, clickable links and icons, etc. should be user
friendly.
 Self-documenting − Any program or software whose identifier names, module
names, etc. can describe itself due to use of explicit names.

Programming Techniques
Software designing is very anesthetic phase of software development cycle. The beauty of heart, skill
of mind and practical thinking is mixed with system objective to implement design.

The designing process is not simple, but complex, cumbersome and frustrating with many curves in
the way of successful design.

Here are some approaches:

 Structural Programming
 Modular Designing
 Top Down Designing
 Bottom Up Designing
 Object Oriented Programming

The objective of Program design are:

(i) Replace old system: The new system is used to replace old system because maintenance
cost is high in old system and efficiency level low.

(ii) Demand of Organization: The new system is developed and installed on the demand of
organization and working groups.

(iii) Productivity: The new system is installed to increase productivity of company or


organization.

(iv) Competition: The new system is a matter of status also. In the age of roaring
competition, if organization does not cope with modem technology failed to face
competitions.

(v) Maintenance: The new system is needed to maintain organization status.

1. Structured Programming

This is the first programming approach used widely in beginning. The program is divided
into several basic structures. These structures are called building blocks.

These are following:

(a) Sequence Structure: This module contains program statements one after another. This is
a very simple module of Structured Programming.
b) Selection or Conditional Structure: The Program has many conditions from which
correct condition is selected to solve problems.
(c) Repetition or loop Structure: The process of repetition or iteration repeats statements
blocks several times when condition is matched, if condition is not matched, looping process
is terminated.

2. Modular Programming

In modular approach, large program is divided into many small discrete components called
Modules.
It is logically separable part of program. Modules are independent and easily manageable.
Generally modules of 20 to 50 lines considered as good modules when lines are increased,
the controlling of module become complex.

3. Top down Approach

(a) The large program is divided into many small module or subprogram or function or
procedure from top to bottom.
(b) At first supervisor program is identified to control other sub modules. Main modules are
divided into sub modules, sub-modules into sub- sub- modules. The decomposition of
modules is continuing whenever desired module level is not obtained.

(c) Top module is tested first, and then sub-modules are combined one by one and tested.

4. Bottom up Approach

 In this approach designing is started from bottom and advanced stepwise to top. So,
this approach is called Bottom up approach.
 At first bottom layer modules are designed and tested, second layer modules are
designed and combined with bottom layer and combined modules are tested. In this
way, designing and testing progressed from bottom to top.

5. Object oriented programming

In the object-oriented programming, program is divided into a set of objects. The emphasis
given on objects. All the programming activities revolve around objects. An object is a real
world entity. It may be airplane, ship, car, house, horse, customer, bank Account, loan, petrol,
fee, courses, and Registration number etc. Objects are tied with functions. Objects are not
free for walk without leg of functions. One object talks with other through earphone of
functions. Object is a boss but captive of functions.

Features of Object oriented Language

 The program is decomposed into several objects. In this language, emphasis is given
to the objects and objects are central points of programming. All the activities are
object centered.
 Objects occupy spaces in memory and have memory address like as records in
PASCAL and structure in C language.
 Data and its functions are encapsulated into a single entity.
 Reusability: In C++, we create classes and these classes have power of reusability.
Other programmers can use these classes.
 It supports bottom up approach of programming. In this approach designing is started
from bottom and advanced stepwise to top.

Algorithm:
The word Algorithm means “a process or set of rules to be followed in calculations or other
problem-solving operations”. Therefore Algorithm refers to a set of rules/instructions that step-
by-step define how a work is to be executed upon in order to get the expected results.
Flowchart:
A flowchart is a graphical representation of an algorithm. Programmers often use it as a
program-planning tool to solve a problem. It makes use of symbols which are connected among
them to indicate the flow of information and processing.

Difference between algorithm and flow chart:-

S.N
O ALGORITHM FLOWCHART

Algorithm is step by step Flowchart is a diagram created by


1. procedure to solve the problem. different shapes to show the flow of data.

Algorithm is complex to
2. understand. Flowchart is easy to understand.

3. In algorithm plain text are used. In flowchart, symbols/shapes are used.

4. Algorithm is easy to debug. Flowchart it is hard to debug.

Algorithm is difficult to
5. construct. Flowchart is simple to construct.

Algorithm does not follow any


6. rules. Flowchart follows rules to be constructed.

Algorithm is the pseudo code for Flowchart is just graphical representation


7. the program. of that logic.

Flowchart Symbols

Terminal: The terminal symbol indicates the Start and End points of the
system.

It usually contains the words start, begin, end inside the terminal design/shape to make
process/things more obvious.Also, it is the first and the last symbol in program
logic. Represented as the shape of rounded rectangle, oval.
Input/Output: It indicates the input and output of data in process/program
logic.Represented as a shape of a Parallelogram.This symbol represents a step where a
programmer/user is prompted to enter information/data manually and displaying the result as
output.

Compute/Process: This symbol represents a set of operations that change


value, form, the location of data.It represents arithmetic and data movement instruction, it is
like a workhorse of a flowchart diagram. This symbol looks like a shape of a rectangle.

Decision: It indicates a question/point at which the decision has to be made


and answered in the format of (yes/No, True/False).In this symbol, the Flowchart path may
then split off into different branches depending on the answer.This flowchart symbol
represented as the shape of Diamond (Rhombus).

Flowlines(Arrowhead): This Flowchart symbol shows the process’s order of


the operation and the exact sequence in which instructions are to be executed in a flowchart.

In a flowchart line coming from one symbol and pointing at another.The arrowheads are
added to represents the flow, whether it is right-to-left, left-to-right, top-to-bottom, etc.

Connector: In Flowchart, this symbol is typically small and used as a


connector to show a jump from one point in the process flow to another.This symbol
particularly useful for the large flowchart. This symbol is represented by a small circle with a
letter inside.

These connectors usually labelled with capital letters (A, B, AA) to show matching jump
points.
1. Write algorithm and flowchart to find area of rectangle

Algorithm
Step 1: start
Step 2: Define the width of the rectangle.
Step 3: Define the Height of the rectangle.
Step 4: Define Area of the rectangle.
Step 5 Calculate the area of the rectangle by multiplying the width and height of
the rectangle.
Step 6: Assign the area of the rectangle to the area variable.
Step 7: print the area of the rectangle.
Step 8: stop

Flowchart
2. Write an algorithm to add two numbers

Step 1: Start.
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum.
Step 5: print sum
Step 6: stop

Flowchart

3. Write an algorithm and flowchart to find the largest among 2 numbers

Algorithm

Step 1: Start.
Step 2: Read a, b .
Step 3: If a>b then Display (print) “a is the largest number”.else
Step 4: Display “b is the largest number”.
Step 5: stop
C Character Sets
C TOKENS
C tokens are the basic buildings blocks in C language which are constructed together to write
a C program.
Each and every smallest individual unit in a C program is known as C tokens.
C tokens are of six types. They are
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special symbols
6. Operators
C KEYWORDS
C keywords are the words that convey a special meaning to the c compiler. The keywords
cannot be used as variable names.

The list of C keywords is given below:


auto break case char const
continue default do double else
enum extern float for goto
if int long register return
short signed sizeof static struct
switch typedef union unsigned void
volatile while

C IDENTIFIERS
Identifiers are used as the general terminology for the names of variables, functions and
arrays.
These are user defined names consisting of arbitrarily long sequence of letters and digits with
either a letter or the underscore(_) as a first character.
There are certain rules that should be followed while naming c identifiers:
1. They must begin with a letter or underscore (_).
2. They must consist of only letters, digits, or underscore. No other special character is
allowed.
3. It should not be a keyword.
4. It must not contain white space.
5. It should be up to 31 characters long as only first 31 characters are significant.
Some examples of c identifiers:
Name Remark

C CONSTANTS
A C constant refers to the data items that do not change their value during the program
execution. Several types of C constants that are allowed in C are:
Integer Constants
Integer constants are whole numbers without any fractional part. It must have at least one
digit
and may contain either + or – sign. A number with no sign is assumed to be positive.
There are three types of integer constants:
Decimal Integer Constants
Integer constants consisting of a set of digits, 0 through 9, preceded by an optional – or +
sign.
Example of valid decimal integer constants
341, -341, 0, 8972
Octal Integer Constants
Integer constants consisting of sequence of digits from the set 0 through 7 starting with 0 is
said to be octal integer constants.
example of valid octal integer constants
010, 0424, 0, 0540
Hexadecimal Integer Constants
Hexadecimal integer constants are integer constants having sequence of digits preceded by
0x or 0X. They may also include alphabets from A to F representing numbers 10 to 15.
Example of valid hexadecimal integer constants
0xD, 0X8d, 0X, 0xbD
It should be noted that, octal and hexadecimal integer constants are rarely used in
programming.
Real Constants
The numbers having fractional parts are called real or floating point constants. These may be
represented in one of the two forms called fractional form or the exponent form and may also
have either + or – sign preceding it.
Example of valid real constants in fractional form or decimal notation
0.05, -0.905, 562.05, 0.015
Character Constants
A character constant contains one single character enclosed within single quotes.
Examples of valid character constants
‘a‘ , ‘Z‘, ‘5‘
string constants
String constants are sequence of characters enclosed within double quotes. For example,
“hello”
Special Symbols
The following special symbols are used in C
 Braces{}: These opening and ending curly braces marks the start and end of a block
of code containing more than one executable statement.
 Parentheses(): These special symbols are used to indicate function calls and function
parameters.
 Brackets[]: Opening and closing brackets are used as array element reference. These
indicate single and multidimensional subscripts.
VARIABLES
A variable is nothing but a name given to a storage area that our programs can manipulate.
Each variable in C has a specific type, which determines the size and layout of the variable's
memory; the range of values that can be stored within that memory; and the set of operations
that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It
must begin with either a letter or an underscore. Upper and lowercase letters are distinct
because C is case-sensitive.
Variable Definition in C
A variable definition tells the compiler where and how much storage to create for the
variable.
A variable definition specifies a data type and contains a list of one or more variables of that
type as follows −
type variable_list;
variable_list may consist of one or more identifier names separated by commas.
Eg., int i, j, k;
char c, ch;
float f, salary;
double d;
Variables can be initialized (assigned an initial value) in their declaration. The initializer
consists of an equal sign followed by a constant expression as follows −
type variable_name = value;
Some examples are −
int d = 3, f = 5; // declaration of d and f.
int d = 3, f = 5; // definition and initializing d and f.
char x = 'x'; // the variable x has the value 'x'.

DATA TYPES
In C programming, data types determines the type and size of data associated with variables.

char: The most basic data type in C. It stores a single character and requires a single byte of
memory in almost all compilers.
int: As the name suggests, an int variable is used to store an integer.
float: It is used to store decimal numbers (numbers with floating point value) with single
precision.
double: It is used to store decimal numbers (numbers with floating point value) with double
precision.

Data Types Memory Format


Size Specifier

char 1 byte %c

signed char 1 byte %c

unsigned char 1 byte %c

int 2 byte %d, %i

unsigned int 2 byte %u

short int 2 byte %hd

long int 4 byte %li

float 4 byte %f

double 8 byte %lf

OPERATORS AND EXPRESSIONS


C language offers many types of operators. They are,
1 Arithmetic_operators
These are used to perform mathematical calculations like addition, subtraction,
multiplication, division and modulus

Operator Description

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus
2 Assignment_operators
These are used to assign the values for the variables in C programs.
Operator Description

= Assign

+= Increments then assign

-= Decrements then assign

*= Multiplies then assign

/= Divides then assign

%= Modulus then assign

<<= Left shift and assign

>>= Right shift and assign

&= Bitwise AND assign

^= Bitwise exclusive OR and assign

|= Bitwise inclusive OR and assign

3 Relational operators
These operators are used to compare the value of two variables.

Operator Description

== Is equal to

!= Is not equal to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to


4 Logical operators
These operators are used to perform logical operations on the given two variables.

Operator Description

&& And operator. It performs logical conjunction of two expressions. (if both
expressions evaluate to True, result is True. If either expression evaluates
to False, the result is False)

|| Or operator. It performs a logical disjunction on two expressions. (if either or


both expressions evaluate to True, the result is True)

! Not operator. It performs logical negation on an expression.

5 Bit wise operators


These operators are used to perform bit operations on given two variables.

per Operator Description


atr

<< Binary Left Shift Operator

>> Binary Right Shift Operator

~ Binary Ones Complement Operator

& Binary AND Operator

^ Binary XOR Operator

| Binary OR Operator

6 Conditional (ternary) operators


Conditional operators return one value if condition is true and returns another value is
condition is false.
Operator Description
?: Conditional Expression

7 Increment/decrement operators
These operators are used to either increase or decrease the value of the variable by one.
Operato Description
r

++ Increment

−− Decrement

8 Special operators
&, *, sizeof( ) and ternary operators.
Operator Description

sizeof() Returns the size of a memory location.

& Returns the address of a memory location.

* Pointer to a variable.

Input Output functions in C


Input means to provide the program with some data to be used in the program and Output
means to display data on the screen or write the data to a printer or a file.
The C programming language provides standard library functions to read any given input and
to display data on the console.

Following are the functions used for standard input and output:
1. printf() function - Show Output
2. scanf() function - Take Input
3. getchar() and putchar() function
4. gets() and puts() function
printf() function - Show Output
The printf() function is the most used function in the C language. This function is defined in
the stdio.h header file and is used to show output on the console (standard output).
This function is used to print a simple text sentence or value of any variable which can be of
int, char, float, or any other datatype.

Eg.
#include <stdio.h>
Void main()
{
printf("Welcome to C programming);
}

scanf() function - Take Input


When we want to take input from the user, we use the scanf() function. When we take input
from the user, we store the input value into a variable.
The scanf() function can be used to take any datatype input from user, all we have to take
care is that the variable in which we store the value has the same datatype.
Eg.
#include <stdio.h>
void main() {
int user_input;
printf("Please enter a number: ");
scanf("%d", &user_input);
printf("You entered: %d", user_input);
}
getchar() & putchar() functions
The getchar() function reads a character from the terminal and returns it as an integer. This
function reads only a single character at a time.
The putchar() function displays the character passed to it on the screen and returns the same
character. This function too displays only a single character at a time.
#include <stdio.h>
void main( )
{
int c;
printf("Enter a character");
c = getchar();
putchar(c);
}

You might also like