Download as pdf or txt
Download as pdf or txt
You are on page 1of 110

UNIT - I

Introduction to Computing:
Computer Systems:
A computer is a system made of two major components: hardware and software. The computer
hardware is the physical equipment. The software is the collection of programs (instructions)
that allow the hardware to do its job.

Computer
System

Hardware Software

Computer Hardware
The hardware component of the computer system consists of five parts: input devices, central
processing unit (CPU) ,primary storage, output devices, and auxiliary storage devices.
The input device is usually a keyboard where programs and data are entered into the
computers. Examples of other input devices include a mouse, a pen or stylus, a touch screen, or
an audio input unit.

The central processing unit (CPU) is responsible for executing instructions such as arithmetic
calculations,comparisons among data, and movement of data inside the system. Today’s
computers may have one ,two, or more CPUs .Primary storage ,also known as main memory, is
a place where the programs and data are stored temporarily during processing. The data in
primary storage are erased when we turn off a personal computer or when we log off from a
time-sharing system.

The output device is usually a monitor or a printer to show output. If the output is shown on
the monitor, we say we have a soft copy. If it is printed on the printer, we say we have a hard
copy.

Auxiliary storage, also known as secondary storage, is used for both input and output. It is the
place where the programs and data are stored permanently. When we turn off the computer,
or programs and data remain in the secondary storage, ready for the next time we need them.

Computer Software
Computer software is divided in to two broad categories: system software and application
software .System software manages the computer resources .It provides the interface between
the hardware and the users. Application software, on the other hand is directly responsible for
helping users solve their problems.

Software

System Application
software software

System System General Application


Operating support Developmen Purpose Specific
Systems t

Fig: Types of software


System Software:

System software consists of programs that manage the hardware resources of a computer and
perform required information processing tasks. These programs are divided into three classes:
the operating system, system support, and system development.

The operating system provides services such as a user interface, file and database access, and
interfaces to communication systems such as Internet protocols. The primary purpose of this
software is to keep the system operating in an efficient manner while allowing the users access
to the system.

System support software provides system utilities and other operating services. Examples of
system utilities are sort programs and disk format programs. Operating services consists of
programs that provide performance statistics for the operational staff and security monitors to
protect the system and data.

The last system software category ,system development software, includes the language
translators that convert programs into machine language for execution ,debugging tools to
ensure that the programs are error free and computer –assisted software engineering(CASE)
systems.

Application software

Application software is broken in to two classes :general-purpose software and application –


specific software. General purpose software is purchased from a software developer and can
be used for more than one application. Examples of general purpose software include word
processors ,database management systems ,and computer aided design systems. They are
labeled general purpose because they can solve a variety of user computing problems.

Application –specific software can be used only for its intended purpose.

A general ledger system used by accountants and a material requirements planning system
used by a manufacturing organization are examples of application-specific software. They can
be used only for the task for which they were designed they cannot be used for other
generalized tasks.

The relation ship between system and application software is shown in fig-2.In this figure, each
circle represents an interface point .The inner core is hard ware. The user is represented by the
out layer. To work with the system,the typical user uses some form of application software. The
application software in turn interacts with the operating system ,which is apart of the system
software layer. The system software provides the direct interaction with the hard ware. The
opening at the bottom of the figure is the path followed by the user who interacts directly with
the operating system when necessary.
Computer Languages:
To write a program for a computer, we must use a computer language. Over the years
computer languages have evolved from machine languages to natural languages.

1940’s Machine level Languages

1950’s Symbolic Languages

1960’s High-Level Languages

Machine Languages

In the earliest days of computers, the only programming languages available were machine
languages. Each computer has its own machine language, which is made of streams of 0’s and
1’s.

Instructions in machine language must be in streams of 0’s and 1’s because the internal circuits
of a computer are made of switches transistors and other electronic devices that can be in one
of two states: off or on. The off state is represented by 0 , the on state is represented by 1.

The only language understood by computer hardware is machine language.

Symbolic Languages:

In early 1950’s Admiral Grace Hopper, A mathematician and naval officer developed the
concept of a special computer program that would convert programs into machine language.
The early programming languages simply mirror to the machine languages using symbols of
mnemonics to represent the various machine language instructions because they used symbols,
these languages were known as symbolic languages.

Computer does not understand symbolic language it must be translated to the machine
language. A special program called assembler translates symbolic code into machine language.
Because symbolic languages had to be assembled into machine language they soon became
known as assembly languages.

Symbolic language uses symbols or mnemonics to represent the various ,machine language
instructions.

High Level Languages:

Symbolic languages greatly improved programming effificiency; they still required programmers
to concentrate on the hardware that they were using. Working with symbolic languages was
also very tedious because each machine instruction has to be individually coded. The desire to
improve programmer efficiency and to change the focus from the computer to the problem
being solved led to the development of high-level language.

High level languages are portable to many different computers, allowing the programmer to
concentrate on the application problem at hand rather than the intricacies of the computer.
High-level languages are designed to relieve the programmer from the details of the assembly
language. High level languages share one thing with symbolic languages, They must be
converted into machine language. The process of converting them is known as compilation.

The first widely used high-level languages, FORTRAN (FORmula TRANslation)was created by
John Backus and an IBM team in 1957;it is still widely used today in scientific and engineering
applications. After FORTRAN was COBOL(Common Business-Oriented Language). Admiral
Hopper was played a key role in the development of the COBOL Business language.

C is a high-level language used for system software and new application code.

ALGORITHM:

Algorithms was developed by an Arab mathematician. It is chalked out step-by-step


approach to solve a given problem. It is represented in an English like language and has some
mathematical symbols like ->, >, <, = etc. To solve a given problem or to write a program you
approach towards solution of the problem in a systematic, disciplined, non-adhoc, step-by-step
way is called Algorithmic approach. Algorithm is a penned strategy(to write) to find a solution.
Example: Algorithm/pseudo code to add two numbers

Step 1: Start
Step 2:Read the two numbers in to a,b
Step 3: c=a+b
Step 4: write/print c
Step 5: Stop.

FLOW CHART :
A Flow chart is a Graphical representation of an Algorithm or a portion of an Algorithm.
Flow charts are drawn using certain special purpose symbols such as Rectangles, Diamonds,
Ovals and small circles. These symbols are connected by arrows called flow lines.

(or)

The diagrammatic representation of way to solve the given problem is called flow chart.

The following are the most common symbols used in Drawing flowcharts:

Oval Terminal start/stop/begin/end.

Parallelogram Input/output Making data available

For processing(input) or
recording of the process
information(output).

Rectangle Process Any processing to be

Done .A process changes or


moves data.An assignment
operation.
Diamond Decision Decision or switching

type of operations.

Circle Connector Used to connect

Different parts of flowchart.

Arrow Flow Joins two symbols

and also represents flow of


execution.

INTRODUCTION TO ‘C’ LANGUAGE:


C language facilitates a very efficient approach to the development and implementation
of computer programs. The History of C started in 1972 at the Bell Laboratories, USA where
Dennis M. Ritchie proposed this language. In 1983 the American National Standards Institute
(ANSI) established committee whose goal was to produce “an unambiguous and machine
independent definition of the language C “ while still retaining it’s spirit .

C is the programming language most frequently associated with UNIX. Since the 1970s, the bulk
of the UNIX operating system and its applications have been written in C. Because the C
language does not directly rely on any specific hardware architecture, UNIX was one of the first
portable operating systems. In other words, the majority of the code that makes up UNIX does
not know and does not care which computer it is actually running on. Machine-specific features
are isolated in a few modules within the UNIX kernel, which makes it easy for you to modify
them when you are porting to a different hardware architecture.
C was first designed by Dennis Ritchie for use with UNIX on DEC PDP-11 computers. The
language evolved from Martin Richard's BCPL, and one of its earlier forms was the B language,
which was written by Ken Thompson for the DEC PDP-7. The first book on C was The C
Programming Language by Brian Kernighan and Dennis Ritchie, published in 1978.

In 1983, the American National Standards Institute (ANSI) established a committee to


standardize the definition of C. The resulting standard is known as ANSI C, and it is the
recognized standard for the language, grammar, and a core set of libraries. The syntax is slightly
different from the original C language, which is frequently called K&R for Kernighan and Ritchie.
There is also an ISO (International Standards Organization) standard that is very similar to the
ANSI standard.

It appears that there will be yet another ANSI C standard officially dated 1999 or in the early
2000 years; it is currently known as "C9X."

BASIC STRUCTURE OF C LANGUAGE:


The program written in C language follows this basic structure. The sequence of sections
should be as they are in the basic structure. A C program should have one or more sections but
the sequence of sections is to be followed.

1. Documentation section

2. Linking section

3. Definition section

4. Global declaration section

5. Main function section

Declaration section

Executable section

6. Sub program or function section


1. DOCUMENTATION SECTION : comes first and is used to document the use of logic or reasons
in your program. It can be used to write the program's objective, developer and logic details.
The documentation is done in C language with /* and */ . Whatever is written between
these two are called comments.

2. LINKING SECTION : This section tells the compiler to link the certain occurrences of keywords
or functions in your program to the header files specified in this section.

e.g. #include <stdio.h>

3. DEFINITION SECTION : It is used to declare some constants and assign them some value.

e.g. #define MAX 25

Here #define is a compiler directive which tells the compiler whenever MAX is found in
the program replace it with 25.

4. GLOBAL DECLARATION SECTION : Here the variables which are used through out the
program (including main and other functions) are declared so as to make them global(i.e
accessible to all parts of program)

e.g. int i; (before main())

5. MAIN FUNCTION SECTION : It tells the compiler where to start the execution from

main()

point from execution starts

main function has two sections

1. declaration section : In this the variables and their data types are declared.

2. Executable section : This has the part of program which actually performs the task we
need.

6. SUB PROGRAM OR FUNCTION SECTION : This has all the sub programs or the functions
which our program needs.
SIMPLE ‘C’ PROGRAM:
/* simple program in c */

#include<stdio.h>

main()

printf(“welcome to c programming”);

} /* End of main */

C-TOKENS :
Tokens are individual words and punctuations marks in English language sentence. The
smallest individual units are known as C tokens.

OPERATORS
E.g. +, -, *

E.g. [ ], { }
SPECIAL SYMBOLS

E.g. “asifia”
STRINGS
C TOKENS

CONSTANTS
E.g. -15.4, ‘a’, 200

IDENTIFIERS
E.g. rate,no_of_hours

KEY WORDS E.g. int, printf


A C program can be divided into these tokens. A C program contains minimum 3 c
tokens no matter what the size of the program is.

KEYWORDS :
There are certain words, called keywords (reserved words) that have a
predefined meaning in ‘C’ language. These keywords are only to be used for their intended
purpose and not as identifiers.

The following table shows the standard ‘C’ keywords

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

IDENTIFIERS :
Names of the variables and other program elements such as functions, array,etc,are
known as identifiers.

There are few rules that govern the way variable are named(identifiers).

1. Identifiers can be named from the combination of A-Z, a-z, 0-9, _(Underscore).

2. The first alphabet of the identifier should be either an alphabet or an underscore.


digit are not allowed.

3. It should not be a keyword.

Eg: name,ptr,sum

After naming a variable we need to declare it to compiler of what data type it is .

The format of declaring a variable is


Data-type id1, id2,.....idn;

where data type could be float, int, char or any of the data types.

id1, id2, id3 are the names of variable we use. In case of single variable no commas are
required.

eg float a, b, c;

int e, f, grand total;

char present_or_absent;

ASSIGNING VALUES :

When we name and declare variables we need to assign value to the variable. In some
cases we assign value to the variable directly like

a=10;

in our program.

In some cases we need to assign values to variable after the user has given input for
that.

eg we ask user to enter any no and input it

/* write a program to show assigning of values to variables */

#include<stdio.h>

main()

int a;

float b;

printf("Enter any number\n");

b=190.5;

scanf("%d",&a);

printf("user entered %d", a);


printf("B's values is %f", b);

CONSTANTS :
A quantity that does not vary during the execution of a program is known as a constant
supports two types of constants namely Numeric constants and character constants.

NUMERIC CONSTANTS:

1. Example for an integer constant is 786,-127

2. Long constant is written with a terminal ‘l’or ‘L’,for example 1234567899L is a Long

constant.

3. Unsigned constants are written with a terminal ‘u’ or ‘U’,and the suffix ‘ul’ and ‘UL’

indicates unsigned long. for example 123456789u is a Unsigned constant and

1234567891ul is an unsigned long constant.

4. The advantage of declaring an unsigned constant is to increase the range of storage.

5. Floating point constants contain a decimal point or an exponent or both. For Eg :

123.4,1e-2,1.4E-4,etc.The suffixes f or F indicate a float constant while the absence of

f or F indicate the double, l or L indicate long double.

CHARACTER CONSTANTS:

A character constant is written as one character with in single quotes such as ‘a’. The
value of a character constant is the numerical value of the character in the machines character
set. certain character constants can be represented by escape sequences like ‘\n’. These
sequences look like two characters but represent only one.

The following are the some of the examples of escape sequences:


Escape sequence Description

\a Alert

\b Backspace

\f Form feed

\n New Line

\r Carriage return

\t Horizontal Tab

\v Vertical Tab

String constants or string literal is a sequence of zero or more characters surrounded by


a double quote. Example , “ I am a little boy”. quotes are not a part of the string.

To distinguish between a character constant and a string that contains a single character
ex: ‘a’ is not same as “a”. ‘a’ is an integer used to produce the numeric value of letter a in the
machine character set, while “a” is an array of characters containing one character and a ‘\0’ as
a string in C is an array of characters terminated by NULL.

There is one another kind of constant i.e Enumeration constant , it is a list of constant
integer values.

Ex.: enum color { RED, Green, BLUE }

The first name in the enum has the value 0 and the next 1 and so on unless explicit
values are specified.

If not all values specified , unspecified values continue the progression from the last
specified value. For example

Enum months { JAN=1, FEB,MAR, …, DEC -

Where the value of FEB is 2 and MAR is 3 and so on.

Enumerations provide a convenient way to associate constant values with names.

VARIABLES :
A quantity that can vary during the execution of a program is known as a variable. To
identify a quantity we name the variable for example if we are calculating a sum of two
numbers we will name the variable that will hold the value of sum of two numbers as 'sum'.

DATA TYPES :
To represent different types of data in C program we need different data types. A data type
is essential to identify the storage representation and the type of operations that can be
performed on that data. C supports four different classes of data types namely

1. Basic Data types


2. Derives data types
3. User defined data types
4. Pointer data types

BASIC DATA TYPES:

All arithmetic operations such as Addition , subtraction etc are possible on basic data
types.

E.g.: int a,b;

Char c;

The following table shows the Storage size and Range of basic data types:

TYPE LENGTH RANGE

Unsigned char 8 bits 0 to 255

Char 8 bits -128 to 127

Short int 16 bits -32768 to 32767

Unsigned int 32 bits 0 to 4,294,967,295


Int 32 bits -2,147,483,648 to 2,147,483,648

Unsigned long 32 bits 0 to 4,294,967,295

Enum 16 bits -2,147,483,648 to 2,147,483,648

Long 32 bits -2,147,483,648 to 2,147,483,648

Float 32 bits 3.4*10E-38 to 3.4*10E38

Double 64 bits 1.7*10E-308 to 1.7*10E308

Long double 80 bits 3.4*10E-4932 to 1.1*10E4932

DERIVED DATA TYPES:

Derived datatypes are used in ‘C’ to store a set of data values. Arrays and Structures are
examples for derived data types.

Ex: int a[10];

Char name[20];

USER DEFINED DATATYPES:

C Provides a facility called typedef for creating new data type names defined by the
user. For Example ,the declaration ,

typedef int Integer;

makes the name Integer a synonym of int.Now the type Integer can be used in declarations
,casts,etc,like,

Integer num1,num2;

Which will be treated by the C compiler as the declaration of num1,num2as int variables.

“typedef” ia more useful with structures and pointers.


POINTER DATA TYPES:

Pointer data type is necessary to store the address of a variable.

INPUT AND OUTPUT STATEMENTS :


The simplest of input operator is getchar to read a single character from the input
device.

varname=getchar();

you need to declare varname.

The simplest of output operator is putchar to output a single character on the output
device.

putchar(varname)

The getchar() is used only for one input and is not formatted. Formatted input refers to an input
data that has been arranged in a particular format, for that we have scanf.

scanf("control string", arg1, arg2,...argn);

Control string specifies field format in which data is to be entered.

arg1, arg2... argn specifies address of location or variable where data is stored.

eg scanf("%d%d",&a,&b);

%d used for integers

%f floats

%l long

%c character

for formatted output you use printf

printf("control string", arg1, arg2,...argn);

/* program to exhibit i/o */

#include<stdio.h>
main()

int a,b;

float c;

printf("Enter any number");

a=getchar();

printf("the char is ");

putchar(a);

printf("Exhibiting the use of scanf");

printf("Enter three numbers");

scanf("%d%d%f",&a,&b,&c);

printf("%d%d%f",a,b,c);

OPERATORS :

An operator is a symbol that tells the compiler to perform certain mathematical or


logical manipulations. They form expressions.

C operators can be classified as

1. Arithmetic operators

2. Relational operators

3. Logical operators

4. Assignment operators

5. Increment or Decrement operators

6. Conditional operator
Problem Solving and
Algorithmic Thinking
(PSAT)

Dr. Sumi Suresh M. S.


Assistant Professor
Department of Computer Science and Engineering

S1 B.Tech, 2022 Batch


What we are going to learn?

A new problem solving paradigm


• Solve problems using tools and techniques in computer
science.
• Advantage- automation

Specifically, we learn
• How to solve problems and write algorithms
• How to represent and store data
• How to write programs (C)
• How to refine the algorithm/code

2/18
Essence of computational problem solving
• To solve a problem computationally, two
things are required
1. Representation
2. Algorithm

• Representation captures all the relevant


aspects of the problem.

• Algorithm that solves the problem by


use of the representation.
Limits of Computational Problem Solving
• “Can a solution to the problem be found in a reasonable amount of time?”

10 cities - the number of possible


routes is 10! (10! =3,628,800).

20 cities - the number of possible


routes is 20!
(2,432,902,008,176,640,000)

Traveling Salesman Problem

Any algorithm that correctly solves a given problem must solve the problem in a reasonable amount of time,
What Is an Algorithm?

• An algorithm is a finite number of clearly described, unambiguous “doable” steps


that can be systematically followed to produce the desired result for a given input
in a finite amount of time.
• Algorithms solve general problems (determining whether any given number is a
prime number), and not specific ones (determining whether 30753 is a prime
number).
• Algorithms are general computational methods used for solving particular
problem instances.

Algorithms and Computers: A Perfect Match


Computers can execute instructions very quickly and reliably without error
Algorithms and Programs

What is an algorithm?
An algorithm is an ordered set of simple instructions to solve a
problem correctly, in finite time.

What is a program?
A program is a translated version of an algorithm, into some
programming language

Algorithms - Human friendly


Programs - Computer friendly

A program is an implementation of an algorithm.

8/18
Important Properties of an Algorithm
• Correct
Always returns the desired output for all legal instances of the problem
• Finiteness
The algorithm should terminate after performing required operations
• Non Ambiguity / Definiteness
Instruction should be clear and precise
• Multiplicity
To solve the same problem we can write several different algorithms
• Range of input
The range of input should be specified
• Efficient
Measured in terms of time or space
10/1
Expressing an algorithm

• Natural Language - Ambiguous and too vaguely defined


• Flow Charts - Explains the steps of a program in a graphical way
• Pseudo code - code that uses all the constructs of a programming
language, but doesn't actually run anywhere
• Programs – running code
Flow Chart
Flow Charts Pseudo code
• Visualize algorithms at a high level No syntax and specifics
Sample Questions
Write an algorithm to find area of a rectangle

Sample Question :- Write an algorithm for Calculating simple interest


Sample Questions
To check greatest of two numbers

Sample Questions:- 1. To check positive or negative number


2. To check odd or even number
Sample Questions
Write an algorithm to print all natural numbers up to n
Sample Questions
Write an algorithm to find factorial of a given number
Flow Chart Symbols
Sample Questions
To check greatest of three numbers

Write an algorithm to print n odd numbers

Write an algorithm to print squares of ‘n’ numbers

Check whether the given number is Armstrong or not

eg: 153 - 13 + 53 + 33 = 153.


Sample Questions
Check whether the given number is Armstrong or not
eg: 153 - 13 + 53 + 33 = 153.
References

• Charles Dierbach, Introduction to Computer Science using Python:


A computational Problem- Solving Focus, 2012.
• https://www.programiz.com/article/flowchart-programming
• https://www.brainkart.com/article/Examples-algorithms--pseudo-
code,-flow-chart,-programming-language_35900/
C Program to Print “Hello World”

The following C program displays “Hello World” in the output.

// Simple C program to display "Hello World"

// Header file for input output functions

#include <stdio.h>

// main function -

// where the execution of program begins

int main()

// prints hello world

printf("Hello World");

return 0;

Output

Hello World

Explanation of the Code

Let us now understand the terminologies of the above program:

Line 1:

// Simple C program to display “Hello World”

This is a single comment line. A comment is used to display additional information about the
program.

A comment does not contain any programming logic as it is not read by the compiler. When a
comment is encountered by a compiler, the compiler simply skips that line of code.

Any line beginning with ‘//’ without quotes OR in between /*…*/ in C is a comment.

More on Comments in C

Line 3:
#include

In C, all lines that start with the pound (#) sign are called directives. These statements are processed
by preprocessor program invoked by the compiler.

The #include directive tells the compiler to include a file and #include<stdio.h> tells the compiler to
include the header file for the Standard Input Output file which contains declarations of all the
standard input/output library functions.

More on Preprocessors in C.

Line 6:

int main()

This line is used to declare a function named “main” which returns data of integer type. A function is
a group of statements that are designed to perform a specific task. Execution of every C program
begins with the main() function, no matter where the function is located in the program. So, every C
program must have a main() function and this is the function where the execution of the program
begins.

{ and }: The opening braces ‘{‘ indicates the beginning of the main function and the closing braces ‘}’
indicates the ending of the main function. Everything between these two comprises the body of the
main function and are called the blocks.

More on main() function in C.

Line 10:

printf("Hello World");

This line tells the compiler to display the message “Hello World” on the screen. This line is called a
statement in C. Every statement is meant to perform some task. A semi-colon ‘;’ is used to end a
statement. The semi-colon character at the end of the statement is used to indicate that the
statement is ending there.

The printf() function is used to print a character stream of data on the stdout console. Everything
within ” ” is displayed on the output device.

More on Input/Output in C.

Line 12:

return 0;

This is also a statement. This statement is used to return a value from a function and indicates the
finishing of a function. This statement is basically used in functions to return the results of the
operations performed by a function.

Indentation: As you can see the printf and the return statement have been indented or moved to the
right side. This is done to make the code more readable. In a program as Hello World, it does not
seem to hold much relevance but as the program becomes more complex, it makes the code more
readable and less error-prone. Therefore, one must always use indentations and comments to make
the code more readable.
C Keywords and Identifiers
Character set
A character set is a set of alphabets, letters and some special characters
that are valid in C language.

Alphabets

Uppercase: A B C ................................... X Y Z

Lowercase: a b c ...................................... x y z

C accepts both lowercase and uppercase alphabets as variables and


functions.

Digits

0 1 2 3 4 5 6 7 8 9

Special Characters

Special Characters in C Programming

, < > . _

( ) ; $ :

% [ ] # ?

' & { } "

^ ! * / |

- \ ~ +

White space Characters


Blank space, newline, horizontal tab, carriage return and form feed.

C Keywords
Keywords are predefined, reserved words used in programming that have
special meanings to the compiler. Keywords are part of the syntax and they
cannot be used as an identifier. For example:

int money;

Here, int is a keyword that indicates money is a variable of type int (integer).
As C is a case sensitive language, all keywords must be written in
lowercase. Here is a list of all keywords allowed in ANSI C.

C Keywords

auto double int struct

break else long switch

case enum register typedef

char extern return union

continue for signed void

do if static while

default goto sizeof volatile

const float short unsigned

All these keywords, their syntax, and application will be discussed in their
respective topics. However, if you want a brief overview of these keywords
without going further, visit List of all keywords in C programming.
C Identifiers
Identifier refers to name given to entities such as variables, functions,
structures etc.

Identifiers must be unique. They are created to give a unique name to an


entity to identify it during the execution of the program. For example:

int money;
double accountBalance;

Here, money and accountBalance are identifiers.


Also remember, identifier names must be different from keywords. You
cannot use int as an identifier because int is a keyword.

Rules for naming identifiers

1. A valid identifier can have letters (both uppercase and lowercase


letters), digits and underscores.

2. The first letter of an identifier should be either a letter or an


underscore.

3. You cannot use keywords like int , while etc. as identifiers.


4. There is no rule on how long an identifier can be. However, you may
run into problems in some compilers if the identifier is longer than 31
characters.

You can choose any name as an identifier if you follow the above rule,
however, give meaningful names to identifiers that make sense
C Variables, Constants and
Literals
Variables
In programming, a variable is a container (storage area) to hold data.

To indicate the storage area, each variable should be given a unique name
(identifier). Variable names are just the symbolic representation of a
memory location. For example:

int playerScore = 95;

Here, playerScore is a variable of int type. Here, the variable is assigned an


integer value 95 .

The value of a variable can be changed, hence the name variable.

char ch = 'a';
// some code
ch = 'l';

Rules for naming a variable

1. A variable name can only have letters (both uppercase and


lowercase letters), digits and underscore.

2. The first letter of a variable should be either a letter or an underscore.

3. There is no rule on how long a variable name (identifier) can be.


However, you may run into problems in some compilers if the
variable name is longer than 31 characters.
Note: You should always try to give meaningful names to variables. For
example: firstName is a better variable name than fn .

C is a strongly typed language. This means that the variable type cannot be
changed once it is declared. For example:

int number = 5; // integer variable


number = 5.5; // error
double number; // error

Here, the type of number variable is int . You cannot assign a floating-point
(decimal) value 5.5 to this variable. Also, you cannot redefine the data type
of the variable to double . By the way, to store the decimal values in C, you
need to declare its type to either double or float .

Visit this page to learn more about different types of data a variable can
store.

Literals
Literals are data used for representing fixed values. They can be used
directly in the code. For example: 1 , 2.5 , 'c' etc.
Here, 1 , 2.5 and 'c' are literals. Why? You cannot assign different values to
these terms.

1. Integers
An integer is a numeric literal(associated with numbers) without any
fractional or exponential part. There are three types of integer literals in C
programming:

• decimal (base 10)

• octal (base 8)

• hexadecimal (base 16)

For example:

Decimal: 0, -9, 22 etc

Octal: 021, 077, 033 etc

Hexadecimal: 0x7f, 0x2a, 0x521 etc

In C programming, octal starts with a 0 , and hexadecimal starts with a 0x .

2. Floating-point Literals

A floating-point literal is a numeric literal that has either a fractional form or


an exponent form. For example:

-2.0

0.0000234

-0.22E-5

Note: E-5 = 10-5


3. Characters

A character literal is created by enclosing a single character inside single


quotation marks. For example: 'a' , 'm' , 'F' , '2' , '}' etc.

4. Escape Sequences

Sometimes, it is necessary to use characters that cannot be typed or has


special meaning in C programming. For example: newline(enter), tab,
question mark etc.

In order to use these characters, escape sequences are used.

Escape Sequences

Escape Sequences Character

\b Backspace

\f Form feed

\n Newline

\r Return

\t Horizontal tab

\v Vertical tab

\\ Backslash

\' Single quotation mark

\" Double quotation mark


Escape Sequences

Escape Sequences Character

\? Question mark

\0 Null character

For example: \n is used for a newline. The backslash \ causes escape from
the normal way the characters are handled by the compiler.

5. String Literals

A string literal is a sequence of characters enclosed in double-quote marks.


For example:

"good" //string constant

"" //null string constant

" " //string constant of six white space

"x" //string constant having a single character.

"Earth is round\n" //prints string with a newline

Constants
If you want to define a variable whose value cannot be changed, you can
use the const keyword. This will create a constant. For example,

const double PI = 3.14;

Notice, we have added keyword const .

Here, PI is a symbolic constant; its value cannot be changed.

const double PI = 3.14;


PI = 2.9; //Error

C Data Types
In C programming, data types are declarations for variables. This
determines the type and size of data associated with variables. For
example,

int myVar;

Here, myVar is a variable of int (integer) type. The size of int is 4 bytes.

Basic types
Here's a table containing commonly used types in C programming for quick
access.

Type Size (bytes) Format Specifier

int at least 2, usually 4 %d , %i

char 1 %c
Type Size (bytes) Format Specifier

float 4 %f

double 8 %lf

short int 2 usually %hd

unsigned int at least 2, usually 4 %u

long int at least 4, usually 8 %ld , %li

long long int at least 8 %lld , %lli

unsigned long int at least 4 %lu

unsigned long long int at least 8 %llu

signed char 1 %c

unsigned char 1 %c

long double at least 10, usually 12 or 16 %Lf

int

Integers are whole numbers that can have both zero, positive and negative
values but no decimal values. For example, 0 , -5 , 10

We can use int for declaring an integer variable.

int id;

Here, id is a variable of type integer.


You can declare multiple variables at once in C programming. For example,

int id, age;


The size of int is usually 4 bytes (32 bits). And, it can take 232 distinct states
from -2147483648 to 2147483647 .

float and double

float and double are used to hold real numbers.

float salary;
double price;

In C, floating-point numbers can also be represented in exponential. For


example,

float normalizationFactor = 22.442e2;

What's the difference between float and double ?

The size of float (single precision float data type) is 4 bytes. And the size
of double (double precision float data type) is 8 bytes.

char

Keyword char is used for declaring character type variables. For example,

char test = 'h';

The size of the character variable is 1 byte.

void
void is an incomplete type. It means "nothing" or "no type". You can think of
void as absent.
For example, if a function is not returning anything, its return type should
be void .

Note that, you cannot create variables of void type.

short and long

If you need to use a large number, you can use a type specifier long . Here's
how:

long a;
long long b;
long double c;

Here variables a and b can store integer values. And, c can store a floating-
point number.
If you are sure, only a small integer ( [−32,767, +32,767] range) will be used,
you can use short .

short d;

You can always check the size of a variable using the sizeof() operator.
#include <stdio.h>
int main() {
short a;
long b;
long long c;
long double d;

printf("size of short = %d bytes\n", sizeof(a));


printf("size of long = %d bytes\n", sizeof(b));
printf("size of long long = %d bytes\n", sizeof(c));
printf("size of long double= %d bytes\n", sizeof(d));
return 0;
}
Run Code

signed and unsigned

In C, signed and unsigned are type modifiers. You can alter the data storage
of a data type by using them:
• signed - allows for storage of both positive and negative numbers
• unsigned - allows for storage of only positive numbers
For example,

// valid codes
unsigned int x = 35;
int y = -35; // signed int
int z = 36; // signed int

// invalid code: unsigned int cannot hold negative integers


unsigned int num = -35;

Here, the variables x and num can hold only zero and positive values
because we have used the unsigned modifier.
Considering the size of int is 4 bytes, variable y can hold values from -

231 to 231-1 , whereas variable x can hold values from 0 to 232-1 .

Derived Data Types


Data types that are derived from fundamental data types are derived types.
For example: arrays, pointers, function types, structures, etc.

We will learn about these derived data types in later tutorials.

• bool type
• Enumerated type

• Complex types

C Input Output (I/O)


C Output
In C programming, printf() is one of the main output function. The function
sends formatted output to the screen. For example,

Example 1: C Output
#include <stdio.h>
int main()
{
// Displays the string inside quotations
printf("C Programming");
return 0;
}
Run Code

Output

C Programming

How does this program work?

• All valid C programs must contain the main() function. The code
execution begins from the start of the main() function.
• The printf() is a library function to send formatted output to the
screen. The function prints the string inside quotations.
• To use printf() in our program, we need to include stdio.h header file
using the #include <stdio.h> statement.
• The return 0; statement inside the main() function is the "Exit status" of
the program. It's optional.

Example 2: Integer Output


#include <stdio.h>
int main()
{
int testInteger = 5;
printf("Number = %d", testInteger);
return 0;
}
Run Code

Output

Number = 5

We use %d format specifier to print int types. Here, the %d inside the
quotations will be replaced by the value of testInteger .

Example 3: float and double Output


#include <stdio.h>
int main()
{
float number1 = 13.5;
double number2 = 12.4;

printf("number1 = %f\n", number1);


printf("number2 = %lf", number2);
return 0;
}
Run Code

Output
number1 = 13.500000
number2 = 12.400000

To print float , we use %f format specifier. Similarly, we use %lf to


print double values.

Example 4: Print Characters


#include <stdio.h>
int main()
{
char chr = 'a';
printf("character = %c", chr);
return 0;
}
Run Code

Output

character = a

To print char , we use %c format specifier.

C Input
In C programming, scanf() is one of the commonly used function to take
input from the user. The scanf() function reads formatted input from the
standard input such as keyboards.

Example 5: Integer Input/Output


#include <stdio.h>
int main()
{
int testInteger;
printf("Enter an integer: ");
scanf("%d", &testInteger);
printf("Number = %d",testInteger);
return 0;
}
Run Code

Output

Enter an integer: 4
Number = 4

Here, we have used %d format specifier inside the scanf() function to


take int input from the user. When the user enters an integer, it is stored in
the testInteger variable.

Notice, that we have used &testInteger inside scanf() . It is


because &testInteger gets the address of testInteger , and the value entered
by the user is stored in that address.

Example 6: Float and Double Input/Output


#include <stdio.h>
int main()
{
float num1;
double num2;

printf("Enter a number: ");


scanf("%f", &num1);
printf("Enter another number: ");
scanf("%lf", &num2);

printf("num1 = %f\n", num1);


printf("num2 = %lf", num2);
return 0;
}
Run Code

Output

Enter a number: 12.523


Enter another number: 10.2
num1 = 12.523000
num2 = 10.200000

We use %f and %lf format specifier for float and double respectively.

Example 7: C Character I/O


#include <stdio.h>
int main()
{
char chr;
printf("Enter a character: ");
scanf("%c",&chr);
printf("You entered %c.", chr);
return 0;
}
Run Code

Output

Enter a character: g
You entered g

When a character is entered by the user in the above program, the


character itself is not stored. Instead, an integer value (ASCII value) is
stored.

And when we display that value using %c text format, the entered character
is displayed. If we use %d to display the character, it's ASCII value is
printed.
Example 8: ASCII Value
#include <stdio.h>
int main()
{
char chr;
printf("Enter a character: ");
scanf("%c", &chr);

// When %c is used, a character is displayed


printf("You entered %c.\n",chr);

// When %d is used, ASCII value is displayed


printf("ASCII value is %d.", chr);
return 0;
}
Run Code

Output

Enter a character: g
You entered g.
ASCII value is 103.

I/O Multiple Values


Here's how you can take multiple inputs from the user and display them.

#include <stdio.h>
int main()
{
int a;
float b;

printf("Enter integer and then a float: ");

// Taking multiple inputs


scanf("%d%f", &a, &b);

printf("You entered %d and %f", a, b);


return 0;
}
Run Code

Output

Enter integer and then a float: -3


3.4
You entered -3 and 3.400000

Format Specifiers for I/O


As you can see from the above examples, we use

• %d for int

• %f for float

• %lf for double

• %c for char

Here's a list of commonly used C data types and their format specifiers.

Data Type Format Specifier

int %d

char %c

float %f

double %lf

short int %hd

unsigned int %u
Data Type Format Specifier

long int %li

long long int %lli

unsigned long int %lu

unsigned long long int %llu

signed char %c

unsigned char %c

long double %Lf

C Comments
In programming, comments are hints that a programmer can add to make
their code easier to read and understand. For example,

#include <stdio.h>

int main() {

// print Hello World to the screen


printf("Hello World");
return 0;
}
Run Code

Output

Hello World

Here, // print Hello World to the screen is a comment in C programming.


Comments are completely ignored by C compilers.
Types of Comments
There are two ways to add comments in C:

1. // - Single Line Comment


2. /*...*/ - Multi-line Comment

1. Single-line Comments in C
In C, a single line comment starts with // . It starts and ends in the same
line. For example,
#include <stdio.h>

int main() {

// create integer variable


int age = 25;

// print the age variable


printf("Age: %d", age);

return 0;
}
Run Code

Output

Age: 25

In the above example, // create integer variable and // print the age

variable are two single line comments.


We can also use the single line comment along with the code. For
example,

int age = 25; // create integer variable


Here, code before // are executed and code after // are ignored by the
compiler.

2. Multi-line Comments in C
In C programming, there is another type of comment that allows us to
comment on multiple lines at once, they are multi-line comments.

To write multi-line comments, we use the /*....*/ symbol. For example,


/* This program takes age input from the user
It stores it in the age variable
And, print the value using printf() */

#include <stdio.h>

int main() {

int age;

printf("Enter the age: ");


scanf("%d", &age);

printf("Age = %d", age);

return 0;
}
Run Code

Output

Enter the age: 24


Age = 24

In this type of comment, the C compiler ignores everything from /* to */.

Note: Remember the keyboard shortcut to use comments:


• Single Line comment: ctrl + / (windows) and cmd + / (mac)

• Multi line comment: ctrl + shift + / (windows) and cmd + shift + / (mac)
Use of Comments in C
1. Make Code Easier to Understand
If we write comments on our code, it will be easier to understand the code
in the future. Otherwise you will end up spending a lot of time looking at our
own code and trying to understand it.

Comments are even more important if you are working in a group. It makes
it easier for other developers to understand and use your code.

2. Using Comments for debugging


While debugging there might be situations where we don't want some part
of the code. For example,

In the program below, suppose we don't need data related to height. So,
instead of removing the code related to height, we can simply convert them
into comments.

// Program to take age and height input

#include <stdio.h>

int main() {

int age;
// double height;

printf("Enter the age: ");


scanf("%d", &age);

// printf("Enter the height: ");


// scanf("%lf", &height);

printf("Age = %d", age);


// printf("\nHeight = %.1lf", height);
return 0;
}
Run Code

Now later on, if we need height again, all you need to do is remove the
forward slashes. And, they will now become statements not comments.

C Programming Operators
An operator is a symbol that operates on a value or a variable. For
example: + is an operator to perform addition.
C has a wide range of operators to perform various operations.

C Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition,
subtraction, multiplication, division etc on numerical values (constants and
variables).

Operator Meaning of Operator

+ addition or unary plus

- subtraction or unary minus

* multiplication

/ division

% remainder after division (modulo division)

Example 1: Arithmetic Operators


// Working of arithmetic operators
#include <stdio.h>
int main()
{
int a = 9,b = 4, c;

c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);

return 0;
}
Run Code

Output

a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1

The operators + , - and * computes addition, subtraction, and multiplication


respectively as you might have expected.
In normal calculation, 9/4 = 2.25 . However, the output is 2 in the program.
It is because both the variables a and b are integers. Hence, the output is
also an integer. The compiler neglects the term after the decimal point and
shows answer 2 instead of 2.25 .

The modulo operator % computes the remainder. When a=9 is divided


by b=4 , the remainder is 1 . The % operator can only be used with integers.
Suppose a = 5.0 , b = 2.0 , c = 5 and d = 2. Then in C programming,

// Either one of the operands is a floating-point number

a/b = 2.5

a/d = 2.5
c/b = 2.5

// Both operands are integers

c/d = 2

C Increment and Decrement Operators


C programming has two operators increment ++ and decrement -- to
change the value of an operand (constant or variable) by 1.
Increment ++ increases the value by 1 whereas decrement -- decreases
the value by 1. These two operators are unary operators, meaning they
only operate on a single operand.
Example 2: Increment and Decrement Operators
// Working of increment and decrement operators
#include <stdio.h>
int main()
{
int a = 10, b = 100;
float c = 10.5, d = 100.5;

printf("++a = %d \n", ++a);


printf("--b = %d \n", --b);
printf("++c = %f \n", ++c);
printf("--d = %f \n", --d);

return 0;
}
Run Code

Output

++a = 11
--b = 99
++c = 11.500000
--d = 99.500000

Here, the operators ++ and -- are used as prefixes. These two operators
can also be used as postfixes like a++ and a-- . Visit this page to learn more
about how increment and decrement operators work when used as postfix.

C Assignment Operators
An assignment operator is used for assigning a value to a variable. The
most common assignment operator is =

Operator Example Same as

= a=b a=b

+= a += b a = a+b

-= a -= b a = a-b

*= a *= b a = a*b

/= a /= b a = a/b

%= a %= b a = a%b

Example 3: Assignment Operators


// Working of assignment operators
#include <stdio.h>
int main()
{
int a = 5, c;

c = a; // c is 5
printf("c = %d\n", c);
c += a; // c is 10
printf("c = %d\n", c);
c -= a; // c is 5
printf("c = %d\n", c);
c *= a; // c is 25
printf("c = %d\n", c);
c /= a; // c is 5
printf("c = %d\n", c);
c %= a; // c = 0
printf("c = %d\n", c);

return 0;
}
Run Code

Output

c = 5
c = 10
c = 5
c = 25
c = 5
c = 0

C Relational Operators

A relational operator checks the relationship between two operands. If the


relation is true, it returns 1; if the relation is false, it returns value 0.

Relational operators are used in decision making and loops.


Operator Meaning of Operator Example

== Equal to 5 == 3 is evaluated to 0

> Greater than 5 > 3 is evaluated to 1

< Less than 5 < 3 is evaluated to 0

!= Not equal to 5 != 3 is evaluated to 1

>= Greater than or equal to 5 >= 3 is evaluated to 1


Operator Meaning of Operator Example

<= Less than or equal to 5 <= 3 is evaluated to 0

Example 4: Relational Operators


// Working of relational operators
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10;

printf("%d == %d is %d \n", a, b, a == b);


printf("%d == %d is %d \n", a, c, a == c);
printf("%d > %d is %d \n", a, b, a > b);
printf("%d > %d is %d \n", a, c, a > c);
printf("%d < %d is %d \n", a, b, a < b);
printf("%d < %d is %d \n", a, c, a < c);
printf("%d != %d is %d \n", a, b, a != b);
printf("%d != %d is %d \n", a, c, a != c);
printf("%d >= %d is %d \n", a, b, a >= b);
printf("%d >= %d is %d \n", a, c, a >= c);
printf("%d <= %d is %d \n", a, b, a <= b);
printf("%d <= %d is %d \n", a, c, a <= c);

return 0;
}
Run Code

Output

5 == 5 is 1
5 == 10 is 0
5 > 5 is 0
5 > 10 is 0
5 < 5 is 0
5 < 10 is 1
5 != 5 is 0
5 != 10 is 1
5 >= 5 is 1
5 >= 10 is 0
5 <= 5 is 1
5 <= 10 is 1
C Logical Operators

An expression containing logical operator returns either 0 or 1 depending


upon whether expression results true or false. Logical operators are
commonly used in decision making in C programming.
Operator Meaning Example

Logical AND. True only if all If c = 5 and d = 2 then, expression ((c==5) &
&&
operands are true (d>5)) equals to 0.

Logical OR. True only if either one If c = 5 and d = 2 then, expression ((c==5) |
||
operand is true (d>5)) equals to 1.

Logical NOT. True only if the


! If c = 5 then, expression !(c==5) equals to 0.
operand is 0

Example 5: Logical Operators


// Working of logical operators

#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;

result = (a == b) && (c > b);


printf("(a == b) && (c > b) is %d \n", result);

result = (a == b) && (c < b);


printf("(a == b) && (c < b) is %d \n", result);

result = (a == b) || (c < b);


printf("(a == b) || (c < b) is %d \n", result);

result = (a != b) || (c < b);


printf("(a != b) || (c < b) is %d \n", result);

result = !(a != b);


printf("!(a != b) is %d \n", result);

result = !(a == b);


printf("!(a == b) is %d \n", result);

return 0;
}
Run Code

Output

(a == b) && (c > b) is 1
(a == b) && (c < b) is 0
(a == b) || (c < b) is 1
(a != b) || (c < b) is 0
!(a != b) is 1
!(a == b) is 0

Explanation of logical operator program


• (a == b) && (c > 5) evaluates to 1 because both operands (a ==

b) and (c > b) is 1 (true).


• (a == b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false).
• (a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
• (a != b) || (c < b) evaluates to 0 because both operand (a !=

b) and (c < b) are 0 (false).


• !(a != b) evaluates to 1 because operand (a != b) is 0 (false).
Hence, !(a != b) is 1 (true).
• !(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a ==

b) is 0 (false).

C Bitwise Operators

During computation, mathematical operations like: addition, subtraction,


multiplication, division, etc are converted to bit-level which makes
processing faster and saves power.

Bitwise operators are used in C programming to perform bit-level


operations.
Operators Meaning of operators

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

~ Bitwise complement

<< Shift left

>> Shift right

C "Hello, World!" Program


To understand this example, you should have the knowledge of the
following C programming topics:
• C Input Output (I/O)

Program to Display "Hello, World!"


#include <stdio.h>
int main() {
// printf() displays the string inside quotation
printf("Hello, World!");
return 0;
}
Run Code

Output

Hello, World!
How "Hello, World!" program works?
• The #include is a preprocessor command that tells the compiler to
include the contents of stdio.h (standard input and output) file in the
program.
• The stdio.h file contains functions such as scanf() and printf() to take
input and display output respectively.
• If you use the printf() function without writing #include <stdio.h> , the
program will not compile.
• The execution of a C program starts from the main() function.
• printf() is a library function to send formatted output to the screen. In
this program, printf() displays Hello, World! text on the screen.
• The return 0; statement is the "Exit status" of the program. In simple
terms, the program ends with this statement.

C Program to Print an Integer


(Entered by the User)
To understand this example, you should have the knowledge of the
following C programming topics:
• C Variables, Constants and Literals
• C Data Types
• C Input Output (I/O)

Program to Print an Integer


#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");

// reads and stores input


scanf("%d", &number);

// displays output
printf("You entered: %d", number);

return 0;
}
Run Code

Output

Enter an integer: 25
You entered: 25

In this program, an integer variable number is declared.

int number;

Then, the user is asked to enter an integer number. This number is stored
in the number variable.

printf("Enter an integer: ");


scanf("%d", &number);

Finally, the value stored in number is displayed on the screen using printf() .

printf("You entered: %d", number);

Program to Add Two Integers


#include <stdio.h>
int main() {

int number1, number2, sum;

printf("Enter two integers: ");


scanf("%d %d", &number1, &number2);
// calculate the sum
sum = number1 + number2;

printf("%d + %d = %d", number1, number2, sum);


return 0;
}
Run Code

Output

Enter two integers: 12


11
12 + 11 = 23

In this program, the user is asked to enter two integers. These two integers
are stored in variables number1 and number2 respectively.

printf("Enter two integers: ");


scanf("%d %d", &number1, &number2);

Then, these two numbers are added using the + operator, and the result is
stored in the sum variable.

sum = number1 + number2;

Add Two Numbers


Finally, the printf() function is used to display the sum of numbers.

printf("%d + %d = %d", number1, number2, sum);


Program to Multiply Two Numbers
#include <stdio.h>
int main() {
double a, b, product;
printf("Enter two numbers: ");
scanf("%lf %lf", &a, &b);

// Calculating product
product = a * b;

// %.2lf displays number up to 2 decimal point


printf("Product = %.2lf", product);

return 0;
}
Run Code

Output

Enter two numbers: 2.4


1.12
Product = 2.69

In this program, the user is asked to enter two numbers which are stored in
variables a and b respectively.

printf("Enter two numbers: ");


scanf("%lf %lf", &a, &b);

Then, the product of a and b is evaluated and the result is stored in product .

product = a * b;

Finally, product is displayed on the screen using printf() .

printf("Product = %.2lf", product);


Notice that, the result is rounded off to the second decimal place
using %.2lf conversion character.

In C programming, a character variable holds ASCII value (an integer


number between 0 and 127) rather than that character itself. This integer
value is the ASCII code of the character.

For example, the ASCII value of 'A' is 65.


What this means is that, if you assign 'A' to a character variable, 65 is
stored in the variable rather than 'A' itself.
Now, let's see how we can print the ASCII value of characters in C
programming.

Program to Print ASCII Value


#include <stdio.h>
int main() {
char c;
printf("Enter a character: ");
scanf("%c", &c);

// %d displays the integer value of a character


// %c displays the actual character
printf("ASCII value of %c = %d", c, c);

return 0;
}
Run Code

Output

Enter a character: G
ASCII value of G = 71
In this program, the user is asked to enter a character. The character is
stored in variable c .
When %d format string is used, 71 (the ASCII value of G ) is displayed.
When %c format string is used, 'G' itself is displayed.

The sizeof(variable) operator computes the size of a variable. And, to print


the result returned by sizeof , we use either %lu or %zu format specifier.
Program to Find the Size of Variables
#include<stdio.h>
int main() {
int intType;
float floatType;
double doubleType;
char charType;

// sizeof evaluates the size of a variable


printf("Size of int: %zu bytes\n", sizeof(intType));
printf("Size of float: %zu bytes\n", sizeof(floatType));
printf("Size of double: %zu bytes\n", sizeof(doubleType));
printf("Size of char: %zu byte\n", sizeof(charType));

return 0;
}
Run Code

Output

Size of int: 4 bytes


Size of float: 4 bytes
Size of double: 8 bytes
Size of char: 1 byte
In this program, 4 variables intType , floatType , doubleType and charType are
declared.
Then, the size of each variable is computed using the sizeof operator.
C if...else Statement
C if Statement
The syntax of the if statement in C programming is:

if (test expression)
{
// code
}

How if statement works?

The if statement evaluates the test expression inside the parenthesis () .

• If the test expression is evaluated to true, statements inside the body


of if are executed.
• If the test expression is evaluated to false, statements inside the
body of if are not executed.

Example 1: if statement
// Program to display a number if it is negative

#include <stdio.h>
int main() {
int number;

printf("Enter an integer: ");


scanf("%d", &number);
// true if number is less than 0
if (number < 0) {
printf("You entered %d.\n", number);
}

printf("The if statement is easy.");

return 0;
}
Run Code

Output 1

Enter an integer: -2
You entered -2.
The if statement is easy.

When the user enters -2, the test expression number<0 is evaluated to true.
Hence, You entered -2 is displayed on the screen.
Output 2

Enter an integer: 5
The if statement is easy.

When the user enters 5, the test expression number<0 is evaluated to false
and the statement inside the body of if is not executed

C if...else Statement
The if statement may have an optional else block. The syntax of
the if..else statement is:

if (test expression) {
// run code if test expression is true
}
else {
// run code if test expression is false
}
How if...else statement works?

If the test expression is evaluated to true,

• statements inside the body of if are executed.


• statements inside the body of else are skipped from execution.
If the test expression is evaluated to false,

• statements inside the body of else are executed


• statements inside the body of if are skipped from execution.

Example 2: if...else statement


// Check whether an integer is odd or even

#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);

// True if the remainder is 0


if (number%2 == 0) {
printf("%d is an even integer.",number);
}
else {
printf("%d is an odd integer.",number);
}

return 0;
}
Run Code

Output

Enter an integer: 7
7 is an odd integer.

When the user enters 7, the test expression number%2==0 is evaluated to false.
Hence, the statement inside the body of else is executed.

C if...else Ladder
The if...else statement executes two different codes depending upon
whether the test expression is true or false. Sometimes, a choice has to be
made from more than 2 possibilities.
The if...else ladder allows you to check between multiple test expressions
and execute different statements.

Syntax of if...else Ladder

if (test expression1) {
// statement(s)
}
else if(test expression2) {
// statement(s)
}
else if (test expression3) {
// statement(s)
}
.
.
else {
// statement(s)
}

Example 3: C if...else Ladder


// Program to relate two integers using =, > or < symbol

#include <stdio.h>
int main() {
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);

//checks if the two integers are equal.


if(number1 == number2) {
printf("Result: %d = %d",number1,number2);
}

//checks if number1 is greater than number2.


else if (number1 > number2) {
printf("Result: %d > %d", number1, number2);
}

//checks if both test expressions are false


else {
printf("Result: %d < %d",number1, number2);
}

return 0;
}
Run Code

Output

Enter two integers: 12


23
Result: 12 < 23

Nested if...else
It is possible to include an if...else statement inside the body of
another if...else statement.

Example 4: Nested if...else

This program given below relates two integers using


either < , > and = similar to the if...else ladder's example. However, we will
use a nested if...else statement to solve this problem.
#include <stdio.h>
int main() {
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);

if (number1 >= number2) {


if (number1 == number2) {
printf("Result: %d = %d",number1,number2);
}
else {
printf("Result: %d > %d", number1, number2);
}
}
else {
printf("Result: %d < %d",number1, number2);
}

return 0;
}
Run Code
If the body of an if...else statement has only one statement, you do not
need to use brackets {} .

For example, this code

if (a > b) {
printf("Hello");
}
printf("Hi");

is equivalent to

if (a > b)
printf("Hello");
printf("Hi");

C for Loop
In programming, a loop is used to repeat a block of code until the specified
condition is met.

C programming has three types of loops:

1. for loop

2. while loop

3. do...while loop

We will learn about for loop in this tutorial. In the next tutorial, we will learn
about while and do...while loop.
for Loop
The syntax of the for loop is:

for (initializationStatement; testExpression; updateStatement)


{
// statements inside the body of loop
}

How for loop works?

• The initialization statement is executed only once.

• Then, the test expression is evaluated. If the test expression is


evaluated to false, the for loop is terminated.
• However, if the test expression is evaluated to true, statements inside
the body of the for loop are executed, and the update expression is
updated.
• Again the test expression is evaluated.

This process goes on until the test expression is false. When the test
expression is false, the loop terminates.

To learn more about test expression (when the test expression is evaluated
to true and false), check out relational and logical operators.
for loop Flowchart

Working of for loop

Example 1: for loop


// Print numbers from 1 to 10
#include <stdio.h>

int main() {
int i;

for (i = 1; i < 11; ++i)


{
printf("%d ", i);
}
return 0;
}
Run Code
Output

1 2 3 4 5 6 7 8 9 10

1. i is initialized to 1.
2. The test expression i < 11 is evaluated. Since 1 less than 11 is true,
the body of for loop is executed. This will print the 1 (value of i ) on
the screen.
3. The update statement ++i is executed. Now, the value of i will be 2.
Again, the test expression is evaluated to true, and the body
of for loop is executed. This will print 2 (value of i ) on the screen.
4. Again, the update statement ++i is executed and the test
expression i < 11 is evaluated. This process goes on until i becomes
11.
5. When i becomes 11, i < 11 will be false, and the for loop terminates.

Example 2: for loop


// Program to calculate the sum of first n natural numbers
// Positive integers 1,2,3...n are known as natural numbers

#include <stdio.h>
int main()
{
int num, count, sum = 0;

printf("Enter a positive integer: ");


scanf("%d", &num);

// for loop terminates when num is less than count


for(count = 1; count <= num; ++count)
{
sum += count;
}

printf("Sum = %d", sum);


return 0;
}
Run Code

Output

Enter a positive integer: 10


Sum = 55

The value entered by the user is stored in the variable num . Suppose, the
user entered 10.
The count is initialized to 1 and the test expression is evaluated. Since the
test expression count<=num (1 less than or equal to 10) is true, the body
of for loop is executed and the value of sum will equal to 1.
Then, the update statement ++count is executed and count will equal to 2.
Again, the test expression is evaluated. Since 2 is also less than 10, the
test expression is evaluated to true and the body of the for loop is
executed. Now, sum will equal 3.
This process goes on and the sum is calculated until the count reaches 11.
When the count is 11, the test expression is evaluated to 0 (false), and the
loop terminates.
Then, the value of sum is printed on the screen.

C while and do...while Loop


In programming, loops are used to repeat a block of code until a specified
condition is met.

C programming has three types of loops.

1. for loop

2. while loop

3. do...while loop
In the previous tutorial, we learned about for loop. In this tutorial, we will
learn about while and do..while loop.

while loop
The syntax of the while loop is:

while (testExpression) {
// the body of the loop
}

How while loop works?

• The while loop evaluates the testExpression inside the parentheses () .

• If testExpression is true, statements inside the body of while loop are


executed. Then, testExpression is evaluated again.
• The process goes on until testExpression is evaluated to false.
• If testExpression is false, the loop terminates (ends).
To learn more about test expressions (when testExpression is evaluated
to true and false), check out relational and logical operators.
Flowchart of while loop

Working of while loop

Example 1: while loop


// Print numbers from 1 to 5

#include <stdio.h>
int main() {
int i = 1;

while (i <= 5) {
printf("%d\n", i);
++i;
}

return 0;
}
Run Code

Output

1
2
3
4
5

Here, we have initialized i to 1.


1. When i = 1, the test expression i <= 5 is true. Hence, the body of
the while loop is executed. This prints 1 on the screen and the value
of i is increased to 2 .
2. Now, i = 2, the test expression i <= 5 is again true. The body of
the while loop is executed again. This prints 2 on the screen and the
value of i is increased to 3 .
3. This process goes on until i becomes 6. Then, the test expression i

<= 5 will be false and the loop terminates.

do...while loop
The do..while loop is similar to the while loop with one important difference.
The body of do...while loop is executed at least once. Only then, the test
expression is evaluated.
The syntax of the do...while loop is:

do {
// the body of the loop
}
while (testExpression);

How do...while loop works?

• The body of do...while loop is executed once. Only then,


the testExpression is evaluated.
• If testExpression is true, the body of the loop is executed
again and testExpression is evaluated once more.
• This process goes on until testExpression becomes false.
• If testExpression is false, the loop ends.

Flowchart of do...while Loop

Working of do...while loop

Example 2: do...while loop


// Program to add numbers until the user enters zero

#include <stdio.h>
int main() {
double number, sum = 0;

// the body of the loop is executed at least once


do {
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
}
while(number != 0.0);

printf("Sum = %.2lf",sum);

return 0;
}
Run Code

Output

Enter a number: 1.5


Enter a number: 2.4
Enter a number: -3.4
Enter a number: 4.2
Enter a number: 0
Sum = 4.70

Here, we have used a do...while loop to prompt the user to enter a number.
The loop works as long as the input number is not 0 .
The do...while loop executes at least once i.e. the first iteration runs without
checking the condition. The condition is checked only after the first iteration
has been executed.

do {
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
}
while(number != 0.0);

So, if the first input is a non-zero number, that number is added to


the sum variable and the loop continues to the next iteration. This process is
repeated until the user enters 0 .
But if the first input is 0, there will be no second iteration of the loop
and sum becomes 0.0 .

Outside the loop, we print the value of sum .


C break and continue
C break
The break statement ends the loop immediately when it is encountered. Its
syntax is:

break;

The break statement is almost always used with if...else statement inside
the loop.

How break statement works?

Working of break in C
Example 1: break statement
// Program to calculate the sum of numbers (10 numbers max)
// If the user enters a negative number, the loop terminates

#include <stdio.h>

int main() {
int i;
double number, sum = 0.0;

for (i = 1; i <= 10; ++i) {


printf("Enter n%d: ", i);
scanf("%lf", &number);

// if the user enters a negative number, break the loop


if (number < 0.0) {
break;
}

sum += number; // sum = sum + number;


}

printf("Sum = %.2lf", sum);

return 0;
}
Run Code

Output

Enter n1: 2.4


Enter n2: 4.5
Enter n3: 3.4
Enter n4: -3
Sum = 10.30

This program calculates the sum of a maximum of 10 numbers. Why a


maximum of 10 numbers? It's because if the user enters a negative
number, the break statement is executed. This will end the for loop, and
the sum is displayed.
In C, break is also used with the switch statement. This will be discussed in
the next tutorial.
C continue
The continue statement skips the current iteration of the loop and continues
with the next iteration. Its syntax is:

continue;

The continue statement is almost always used with the if...else statement.

How continue statement works?

Working of
Continue in C

Example 2: continue statement


// Program to calculate the sum of numbers (10 numbers max)
// If the user enters a negative number, it's not added to the result

#include <stdio.h>
int main() {
int i;
double number, sum = 0.0;

for (i = 1; i <= 10; ++i) {


printf("Enter a n%d: ", i);
scanf("%lf", &number);

if (number < 0.0) {


continue;
}

sum += number; // sum = sum + number;


}

printf("Sum = %.2lf", sum);

return 0;
}
Run Code

Output

Enter n1: 1.1


Enter n2: 2.2
Enter n3: 5.5
Enter n4: 4.4
Enter n5: -3.4
Enter n6: -45.5
Enter n7: 34.5
Enter n8: -4.2
Enter n9: -1000
Enter n10: 12
Sum = 59.70

In this program, when the user enters a positive number, the sum is
calculated using sum += number; statement.
When the user enters a negative number, the continue statement is
executed and it skips the negative number from the calculation.
C switch Statement
The switch statement allows us to execute one code block among many
alternatives.

You can do the same thing with the if...else..if ladder. However, the
syntax of the switch statement is much easier to read and write.

Syntax of switch...case

switch (expression)
{
case constant1:
// statements
break;

case constant2:
// statements
break;
.
.
.
default:
// default statements
}

How does the switch statement work?


The expression is evaluated once and compared with the values of
each case label.
• If there is a match, the corresponding statements after the matching
label are executed. For example, if the value of the expression is
equal to constant2 , statements after case constant2: are executed
until break is encountered.
• If there is no match, the default statements are executed.
Notes:
• If we do not use the break statement, all statements after the matching
label are also executed.
• The default clause inside the switch statement is optional.
switch Statement Flowchart

switch Statement
Flowchart

Example: Simple Calculator


// Program to create a simple calculator
#include <stdio.h>
int main() {
char operation;
double n1, n2;

printf("Enter an operator (+, -, *, /): ");


scanf("%c", &operation);
printf("Enter two operands: ");
scanf("%lf %lf",&n1, &n2);

switch(operation)
{
case '+':
printf("%.1lf + %.1lf = %.1lf",n1, n2, n1+n2);
break;

case '-':
printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2);
break;

case '*':
printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2);
break;

case '/':
printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2);
break;

// operator doesn't match any case constant +, -, *, /


default:
printf("Error! operator is not correct");
}

return 0;
}
Run Code

Output

Enter an operator (+, -, *, /): -


Enter two operands: 32.5
12.4
32.5 - 12.4 = 20.1

The - operator entered by the user is stored in the operation variable. And,
two operands 32.5 and 12.4 are stored in variables n1 and n2 respectively.
Since the operation is - , the control of the program jumps to

printf("%.1lf - %.1lf = %.1lf", n1, n2, n1-n2);

Finally, the break statement terminates the switch statement.


\

C goto Statement
The goto statement allows us to transfer control of the program to the
specified label .

Syntax of goto Statement

goto label;
... .. ...
... .. ...
label:
statement;

The label is an identifier. When the goto statement is encountered, the


control of the program jumps to label: and starts executing the code.

Working of goto Statement


Example: goto Statement
// Program to calculate the sum and average of positive numbers
// If the user enters a negative number, the sum and average are displayed.

#include <stdio.h>

int main() {

const int maxInput = 100;


int i;
double number, average, sum = 0.0;

for (i = 1; i <= maxInput; ++i) {


printf("%d. Enter a number: ", i);
scanf("%lf", &number);

// go to jump if the user enters a negative number


if (number < 0.0) {
goto jump;
}
sum += number;
}

jump:
average = sum / (i - 1);
printf("Sum = %.2f\n", sum);
printf("Average = %.2f", average);

return 0;
}
Run Code

Output

1. Enter a number: 3
2. Enter a number: 4.3
3. Enter a number: 9.3
4. Enter a number: -2.9
Sum = 16.60
Average = 5.53
Reasons to avoid goto

The use of goto statement may lead to code that is buggy and hard to
follow. For example,

one:
for (i = 0; i < number; ++i)
{
test += i;
goto two;
}
two:
if (test > 5) {
goto three;
}
... .. ...

Also, the goto statement allows you to do bad stuff such as jump out of the
scope.
That being said, goto can be useful sometimes. For example: to break from
nested loops.

Program to Check Even or Odd


#include <stdio.h>
int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);

// true if num is perfectly divisible by 2


if(num % 2 == 0)
printf("%d is even.", num);
else
printf("%d is odd.", num);

return 0;
}
Run Code

Output
Enter an integer: -7
-7 is odd.

In the program, the integer entered by the user is stored in the variable num .

Then, whether num is perfectly divisible by 2 or not is checked using the


modulus % operator.
If the number is perfectly divisible by 2 , test expression number%2 ==

0 evaluates to 1 (true). This means the number is even.


However, if the test expression evaluates to 0 (false), the number is odd.
The five letters A , E , I , O and U are called vowels. All other alphabets except
these 5 vowels are called consonants.
This program assumes that the user will always enter an alphabet
character.

Program to Check Vowel or consonant


#include <stdio.h>
int main() {
char c;
int lowercase_vowel, uppercase_vowel;
printf("Enter an alphabet: ");
scanf("%c", &c);

// evaluates to 1 if variable c is a lowercase vowel


lowercase_vowel = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');

// evaluates to 1 if variable c is a uppercase vowel


uppercase_vowel = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');

// evaluates to 1 (true) if c is a vowel


if (lowercase_vowel || uppercase_vowel)
printf("%c is a vowel.", c);
else
printf("%c is a consonant.", c);
return 0;
}
Run Code

Output

Enter an alphabet: G
G is a consonant.

The character entered by the user is stored in variable c .


The lowercase_vowel variable evaluates to 1 (true) if c is a lowercase vowel
and 0 (false) for any other characters.
Similarly, the uppercase_vowel variable evaluates to 1 (true) if c is an
uppercase vowel and 0 (false) for any other character.
If either lowercase_vowel or uppercase_vowel variable is 1 (true), the entered
character is a vowel. However, if
both lowercase_vowel and uppercase_vowel variables are 0, the entered character
is a consonant.

Note: This program assumes that the user will enter an alphabet. If the
user enters a non-alphabetic character, it displays the character is a
consonant.

To fix this, we can use the isalpha() function. The islapha() function checks
whether a character is an alphabet or not.
#include <ctype.h>
#include <stdio.h>

int main() {
char c;
int lowercase_vowel, uppercase_vowel;
printf("Enter an alphabet: ");
scanf("%c", &c);

// evaluates to 1 if variable c is a lowercase vowel


lowercase_vowel = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
// evaluates to 1 if variable c is a uppercase vowel
uppercase_vowel = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');

// Show error message if c is not an alphabet


if (!isalpha(c))
printf("Error! Non-alphabetic character.");
else if (lowercase_vowel || uppercase_vowel)
printf("%c is a vowel.", c);
else
printf("%c is a consonant.", c);

return 0;
}
Run Code

Now, if the user enters a non-alphabetic character, you will see:

Enter an alphabet: 3
Error! Non-alphabetic character.

Program to Check Alphabet


#include <stdio.h>
int main() {
char c;
printf("Enter a character: ");
scanf("%c", &c);

if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
printf("%c is an alphabet.", c);
else
printf("%c is not an alphabet.", c);

return 0;
}
Run Code

Output

Enter a character: *
* is not an alphabet
In the program, 'a' is used instead of 97 and 'z' is used instead of 122 .

Similarly, 'A' is used instead of 65 and 'Z' is used instead of 90 .

Note: It is recommended we use the isalpha() function to check whether a


character is an alphabet or not.

if (isalpha(c))
printf("%c is an alphabet.", c);
else
printf("%c is not an alphabet.", c);

You might also like