Professional Documents
Culture Documents
C Periodical Notes
C Periodical Notes
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 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 –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.
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.
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.
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:
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:
For processing(input) or
recording of the process
information(output).
type of operations.
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.
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."
1. Documentation section
2. Linking section
3. Definition section
Declaration section
Executable section
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.
3. DEFINITION SECTION : It is used to declare some constants and assign them some value.
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)
5. MAIN FUNCTION SECTION : It tells the compiler where to start the execution from
main()
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
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.
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).
Eg: name,ptr,sum
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;
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.
#include<stdio.h>
main()
int a;
float b;
b=190.5;
scanf("%d",&a);
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:
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’
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.
\a Alert
\b Backspace
\f Form feed
\n New Line
\r Carriage return
\t Horizontal Tab
\v Vertical Tab
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.
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
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
All arithmetic operations such as Addition , subtraction etc are possible on basic data
types.
Char c;
The following table shows the Storage size and Range of basic data types:
Derived datatypes are used in ‘C’ to store a set of data values. Arrays and Structures are
examples for derived data types.
Char name[20];
C Provides a facility called typedef for creating new data type names defined by the
user. For Example ,the declaration ,
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.
varname=getchar();
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.
arg1, arg2... argn specifies address of location or variable where data is stored.
eg scanf("%d%d",&a,&b);
%f floats
%l long
%c character
#include<stdio.h>
main()
int a,b;
float c;
a=getchar();
putchar(a);
scanf("%d%d%f",&a,&b,&c);
printf("%d%d%f",a,b,c);
OPERATORS :
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
6. Conditional operator
Problem Solving and
Algorithmic Thinking
(PSAT)
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
Any algorithm that correctly solves a given problem must solve the problem in a reasonable amount of time,
What Is an Algorithm?
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
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
#include <stdio.h>
// main function -
int main()
printf("Hello World");
return 0;
Output
Hello World
Line 1:
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.
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
Digits
0 1 2 3 4 5 6 7 8 9
Special Characters
, < > . _
( ) ; $ :
% [ ] # ?
^ ! * / |
- \ ~ +
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
do if static while
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.
int money;
double accountBalance;
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:
char ch = 'a';
// some code
ch = 'l';
C is a strongly typed language. This means that the variable type cannot be
changed once it is declared. For example:
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:
• octal (base 8)
For example:
2. Floating-point Literals
-2.0
0.0000234
-0.22E-5
4. Escape Sequences
Escape Sequences
\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\? 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
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,
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.
char 1 %c
Type Size (bytes) Format Specifier
float 4 %f
double 8 %lf
signed char 1 %c
unsigned char 1 %c
int
Integers are whole numbers that can have both zero, positive and negative
values but no decimal values. For example, 0 , -5 , 10
int id;
float salary;
double price;
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,
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 .
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;
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
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 -
• bool type
• Enumerated type
• Complex types
Example 1: C Output
#include <stdio.h>
int main()
{
// Displays the string inside quotations
printf("C Programming");
return 0;
}
Run Code
Output
C Programming
• 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.
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 .
Output
number1 = 13.500000
number2 = 12.400000
Output
character = a
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.
Output
Enter an integer: 4
Number = 4
Output
We use %f and %lf format specifier for float and double respectively.
Output
Enter a character: g
You entered g
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);
Output
Enter a character: g
You entered g.
ASCII value is 103.
#include <stdio.h>
int main()
{
int a;
float b;
Output
• %d for int
• %f for float
• %c for char
Here's a list of commonly used C data types and their format specifiers.
int %d
char %c
float %f
double %lf
unsigned int %u
Data Type Format Specifier
signed char %c
unsigned char %c
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() {
Output
Hello World
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() {
return 0;
}
Run Code
Output
Age: 25
In the above example, // create integer variable and // print the age
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.
#include <stdio.h>
int main() {
int age;
return 0;
}
Run Code
Output
• 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.
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.
#include <stdio.h>
int main() {
int age;
// double height;
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).
* multiplication
/ division
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
a/b = 2.5
a/d = 2.5
c/b = 2.5
c/d = 2
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 =
= 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
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
== Equal to 5 == 3 is evaluated to 0
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
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.
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, 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
b) is 0 (false).
C Bitwise Operators
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
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.
// displays output
printf("You entered: %d", number);
return 0;
}
Run Code
Output
Enter an integer: 25
You entered: 25
int number;
Then, the user is asked to enter an integer number. This number is stored
in the number variable.
Finally, the value stored in number is displayed on the screen using printf() .
Output
In this program, the user is asked to enter two integers. These two integers
are stored in variables number1 and number2 respectively.
Then, these two numbers are added using the + operator, and the result is
stored in the sum variable.
// Calculating product
product = a * b;
return 0;
}
Run Code
Output
In this program, the user is asked to enter two numbers which are stored in
variables a and b respectively.
Then, the product of a and b is evaluated and the result is stored in product .
product = a * b;
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.
return 0;
}
Run Code
Output
if (test expression)
{
// code
}
Example 1: if statement
// Program to display a number if it is negative
#include <stdio.h>
int main() {
int number;
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?
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &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.
if (test expression1) {
// statement(s)
}
else if(test expression2) {
// statement(s)
}
else if (test expression3) {
// statement(s)
}
.
.
else {
// statement(s)
}
#include <stdio.h>
int main() {
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
return 0;
}
Run Code
Output
Nested if...else
It is possible to include an if...else statement inside the body of
another if...else statement.
return 0;
}
Run Code
If the body of an if...else statement has only one statement, you do not
need to use brackets {} .
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.
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:
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
int main() {
int i;
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.
#include <stdio.h>
int main()
{
int num, count, sum = 0;
Output
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.
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
}
#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
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);
#include <stdio.h>
int main() {
double number, sum = 0;
printf("Sum = %.2lf",sum);
return 0;
}
Run Code
Output
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);
break;
The break statement is almost always used with if...else statement inside
the loop.
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;
return 0;
}
Run Code
Output
continue;
The continue statement is almost always used with the if...else statement.
Working of
Continue in C
#include <stdio.h>
int main() {
int i;
double number, sum = 0.0;
return 0;
}
Run Code
Output
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
}
switch Statement
Flowchart
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;
return 0;
}
Run Code
Output
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
C goto Statement
The goto statement allows us to transfer control of the program to the
specified label .
goto label;
... .. ...
... .. ...
label:
statement;
#include <stdio.h>
int main() {
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.
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 .
Output
Enter an alphabet: G
G 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);
return 0;
}
Run Code
Enter an alphabet: 3
Error! Non-alphabetic character.
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 .
if (isalpha(c))
printf("%c is an alphabet.", c);
else
printf("%c is not an alphabet.", c);