0% found this document useful (0 votes)
34 views27 pages

Unit1 C Sreedhar

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

Unit1 C Sreedhar

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

Unit-I

Introduction:
What is Problem Solving in Programming?

Computers are used to solve various problems in day-to-day life. Problem Solving is an essential
skill that helps to solve problems in programming. There are specific steps to be carried out to solve
problems in computer programming, and the success depends on how correctly and precisely we
define a problem.
This involves designing, identifying and implementing problems using certain steps to develop a
computer.

Problem Solving Through Programming in C


 A computer is a very powerful and versatile machine capable of performing a multitude of
different tasks, yet it has no intelligence or thinking power.
 The Computer performs many tasks exactly in the same manner as it is told to do.
 The computer cannot solve the problem on its own, one has to provide step by step solutions of
the problem to the computer. In fact, the task of problem-solving is not that of the computer.
 It is the programmer who has to write down the solution to the problem in terms of simple
operations which the computer can understand and execute.
 Problem-solving is a sequential process of analyzing information related to a given situation and
generating appropriate response options.
In order to solve a problem with the computer, one has to pass through certain stages or steps. They are
as follows:
Step 1: Understanding the Problem:
Here we try to understand the problem to be solved in totally. Before with the next stage or step, we
should be absolutely sure about the objectives of the given problem.
Step 2: Analyzing the Problem:
After understanding thoroughly the problem to be solved, we look at different ways of solving the
problem and evaluate each of these methods.
The idea here is to search for an appropriate solution to the problem under consideration. The end result
of this stage is a broad overview of the sequence of operations that are to be carried out to solve the
given problem.
Step 3: Developing the solution:
Here, the overview of the sequence of operations that was the result of the analysis stage is expanded to
form a detailed step by step solution to the problem under consideration.

Prepared By: Sreedhar Aakula, RGUKT


Step 4: Coding and Implementation:
The last stage of problem-solving is the conversion of the detailed sequence of operations into a
language that the computer can understand. Here, each step is converted to its equivalent instruction or
instructions in the computer language that has been chosen for the implantation.
Computer Programming
A computer is a programmable machine. Program means set of instructions. A computer program is a
collection of instructions that performs a specific task when executed by a computer.
Programmers translate the solutions or tasks into a language the computer can understand.
As we write programs, we must keep in mind that the computer will only do what we instruct it to do.
Because of this, we must be very careful and thorough with our instructions.
Programming Languages
 Computer programming is almost always done by means of Programming Language.
 There exist more than 2500 programming languages in the world.
 Some of them are known by only their developers!
 Programming languages Examples: 1955-FORTRAN,1958-ALGOL 58, 1959-COBOL,1964-
BASIC,1972-C,1978-SQL

Types of Languages:

Machine Language, high-level & Low-level Languages


Machine language is a collection of binary digits(0,1) or bits that the computer reads and interprets.
Machine language is the only language a computer is capable of understanding.
machine language is a set of instructions executed directly by a computer's central processing unit (CPU).
Low-level languages are difficult to learn. Because these are far from human languages. Deep
knowledge of hardware is required to write programs. so it is very difficult to modify the language. low-
level languages are fast in execution. These languages are normally used to write hardware programs

High-level languages are easy to learn. Because these are similar to human languages so we can easily
modify the language. But the disadvantage of this high-level language is it takes more time for
execution.Because High-level languages are translated into machine language by a compiler and then
execution will start. These languages are normally used to write application programs.

Prepared By: Sreedhar Aakula, RGUKT


Compiler:
Compiler itself is a computer program. It Scans the entire program and translates it as a whole into
machine code. It takes large amount of time to analyze the source code but the overall execution time is
comparatively faster. Generates intermediate object code which further requires linking, hence requires
more memory. It generates the error message only after scanning the whole program. Hence debugging
is comparatively hard.

Algorithm is a computer procedure that is a lot like a recipe (called a procedure) and tells your computer
precisely what steps to take to solve a problem or reach a goal. The ingredients are called inputs, while
the results are called the outputs.
Flowchart
 A flowchart is a type of diagram that represents an algorithm, workflow or process, showing the
steps as boxes of various kinds, and their order by connecting them with arrows.
 This diagrammatic representation illustrates a solution model to a given problem.
 Flowcharts are used in analyzing, designing, documenting or managing a process or program in
various fields.
Flowchart Symbols

Prepared By: Sreedhar Aakula, RGUKT


Rules of Drawing Flowcharts for Algorithms
1. All boxes of flowcharts are connected with arrows to show the logical connection between them,
2. Flowcharts will flow from top to bottom,
3. All flowcharts start with a Start Box and end with a Terminal(End) Box,
Example 1: Calculate the Interest of a Bank Deposit
Algorithm:
 Step 1: Read amount,
 Step 2: Read years,
 Step 3: Read rate,
 Step 4: Calculate the interest with formula "Interest=Amount*Years*Rate/100
 Step 5: Print interest,
Flowchart:

Example 2: Determine and Output Whether Number N is Even or Odd


Algorithm:
 Step 1: Read number N,
 Step 2: Set remainder as N modulo 2,
 Step 3: If remainder is equal to 0 then number N is even, else number N is odd,
 Step 4: Print output.
Flowchart:

Prepared By: Sreedhar Aakula, RGUKT


Example 3: Determine Whether A Student Passed the Exam or Not:
Algorithm:
 Step 1: Input grades of 4 courses M1, M2, M3 and M4,
 Step 2: Calculate the average grade with formula "Grade=(M1+M2+M3+M4)/4"
 Step 3: If the average grade is less than 60, print "FAIL", else print "PASS".
Flowchart:

Prepared By: Sreedhar Aakula, RGUKT


Exercise
1. Write an algorithm and flowchart to find given number is prime or not.
2. Write an algorithm and flowchart to find the gcd of two numbers.
3. write an algorithm and flowchart to swap two numbers.
4. Write an algorithm and flowchart to find the largest number of 3 numbers.
5. Write an algorithm and flowchart to compute the factorial of a given number.
6. Write an algorithm and flowchart to compute given number is perfect or not.

History of C
Introduction to C: -
 C is a high level language. It is both a general purpose(to develop applications programs) and a
specific purpose(to develop System programs ) programming language.
 It was developed at the Bell Telephone Laboratory, USA (Now AT & T), in 1972. It was developed
by Dennis Ritchie .
 C is derived from two early programming languages such as BCPL (Basic Combined Programming
Language) and B language.
 He selected the name C for his new language because C comes after B in alphabetical order which
indicates advancement to B.

Prepared By: Sreedhar Aakula, RGUKT


Characteristics of C:-

C is a General Purpose Programming Language This means C can be used to write a variety of
applications. It is often referred to as a “system programming language.”
1. C is renowned for its simplicity and is easy to use because of its structured approach.
2. C is portable, which means a C program runs in different environments.
3. C compilers are available for all operating systems and hardware platforms.
4. C is modular, which means C programs can be divided into small modules, which are much easier
to understand.
5. C is easy to debug. The C compiler detects syntax errors quickly and easily and displays the errors
along with the line numbers of the code and the error message.

Applications of C:-
Because of its portability and efficiency, C is used to develop the system as well as application software.
Some of the system and application software listed below are:
1. Operating Systems(System software)
2. Interpreters and Compilers(System software)
3. Editors(System software)
4. DBMS(Application software)
5. Spread sheets(Application software)
6. Graphics packages(Application software)
7. Word Processors(Application software)
C Tokens:-
A token in C can be defined as the smallest individual element of the C programming language that is
meaningful to the compiler.
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Operators

Keywords and Identifiers:-


Every word in a C program is either a keyword or identifier. All keywords are basically the sequences of
characters that have one or more fixed meanings and these meanings in any circumstances can’t be
changed. All C keywords must be written in lower letters.
Keywords supported by ANSI(American National Standards institute) C are:

Prepared By: Sreedhar Aakula, RGUKT


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

Identifiers:-
Identifiers are the names given to the program elements such as variables, arrays and functions.
Basically, identifiers are the sequences of alphabets and digits. The rules that govern the formation of
identifier names are:
1. The first character must be an alphabet or an underscore.
2. All succeeding characters must be either letters or digits
3. Uppercase and lowercase identifiers are different
4. No special character or punctuation symbols are allowed except the underscore.
5. No two successive underscores are allowed.
6. Keywords should not be used as identifiers.
Constants:
The quantity which does not change during the execution of a program is known as constant.
Constants are created by using a keyword called “const”.
Ex: const int a=10;
Note: after this statement if we are trying to modify the a value it gives an error as it is a constant.
Variables:-
1. The quantity that changes during the execution of a program is called a variable.
2. The variables are the name given to identify the specific program elements.
3. Variables are nothing but reserved memory locations to store values. This means when you create a
variable, you reserve some space in memory.
Rules for forming variable names:-
1. The first character must be an alphabet or an underscore.
2. All succeeding characters must be either letters or digits
3. Uppercase and lowercase variables are different
4. No special character or punctuation symbols are allowed except the underscore.
5. No two successive underscores are allowed.
6. Keywords should not be used as variables.

Prepared By: Sreedhar Aakula, RGUKT


Declaration of Variables:-
All variables must be declared before they are used in C program. The purpose of declaring variables is to
reserve the amount of memory required for these variables.
Syntax for declaration:-
Data_type variable_name;
Example: int length;
Assigning values to variables:
When the data is stored that the variables represent some memory location. Each variable is associated
with one or more values. The process of giving values to variables is called the assignment of the values.
The assignment operator ‘=’ is used to assign a value to a variable.
Syntax:
Variable_name = value;
Example: int x = 1;
Multiple Assignment Statement
The process of giving initial values to variable is known as initialization. We can initialize more than one
variable in a a single statement. This is called multiple assignment statement.
Example: int x=y=z=10;
Data types:-
Data types indicates the type of data that a variable can hold. The data may be numeric or non-numeric.
Those are categorized into:
1. Predefined data types-
a. Integers: short, int, long int, long long int,
b. Float: float, double, long double
c. Character: char
2. User defined data types-pointers, arrays, strings, structures and union

Predefined Data types:- They are basic data types and designate a single value. There are four
fundamental built in data types in C language. They are:
1. Integer
2. character
3. Floating point
4. Double
In C, there is one and only one non-specific data type called void. It does not specify anything.
Prepared By: Sreedhar Aakula, RGUKT
Int:-
Int is a keyword used to indicated integer number. Any integer number is a sequence of digits
without decimal point.
Float:-
Float is a keyword used to indicate a floating point number. The floating point numbers are the
same as real numbers.
Char:-
Char is a keyword used to indicate the character type data. The data may be a character constant
or a string constant. A character constant can be defined as any single character enclosed in a pair of
single quotes.
Double:-
Double is a keyword used to indicate a double precision floating point number. The precision
associated with the accuracy of the data. A double is normal float value, but the number of significant
digits that are stored after the decimal point is double that of the float.
Prepared By: Sreedhar Aakula, RGUKT
The float usually stores a maximum of 6 digits after the decimal point but double stores 16 significant
digits after the decimal point.
Modifiers in C language:
 The amount of memory space to be allocated for a variable is derived by modifiers.
 Modifiers are prefixed with basic data types to modify (either increase or decrease) the amount
of storage space allocated to a variable.
 There are 4 modifiers available in C language. They are,
1. short
2. long
3. signed
4. unsigned
Short
In general int data type occupies different memory spaces for a different operating system; to allocate
fixed memory space short keyword can be used. short int occupies 2 bytes of memory space in every
operating system.
Long
This can be used to increased size of the current data type to 2 more bytes, which can be applied on int
or double data types. For example int occupy 2 byte of memory if we use long with integer variable then
it occupy 4 byte of memory.
Signed
This keyword accepts both negative or positive value and this is default properties or data type modifiers
for every data type. in real time no need to write signed keyword explicitly for any data type.
Example
int a=10; // right
int a=-10; // right
signed int a=10; // right
signed int a=-10; // right
Unsigned
This keyword can be used to make the accepting values of a data type is positive data type.
Example
unsigned int a =100; // right
unsigned int a=-100; // wrong

Prepared By: Sreedhar Aakula, RGUKT


Type conversion:
It is used to modify a variable from one date type to another data type. New data type should be
mentioned before the variable name or value in brackets which to be typecast.
Example
#include<stdio.h>
int main()
{
double x = 1.2;
// Explicit conversion from double to int
int sum = (int)x + 1;
printf("sum = %d", sum);
}
Format Specifiers:
In C programming we need lots of format specifier to work with various data types. Format specifiers
defines the type of data to be printed on standard output. Whether to print formatted output or to take
formatted input we need format specifiers. Format specifiers are also called as format string.

List of format specifiers

%c char single character


%d int integer
%f float or double
%p pointer address stored in pointer
%s array of char sequence of characters
%u unsigned int

%% to print %

Input and Output


Functions:-The scanf()
function
When we want to take input from the user, we use the scanf() function and store the input value into a
variable.
Syntax:
Scanf(“%d”, &number); // & is called address operator, %d- to read integer
Prepared By: Sreedhar Aakula, RGUKT
The printf() function
The printf() function is the most used function in the C language. This function is defined in the stdio.h
header file and is used to show output on the console (standard output).
Syntax:
printf(“%d”, number); //%d to print integers

Preprocessor statements:-
These statements begin with # symbol and also called as preprocessor directives. These
statements direct the C preprocessor to include header files and also symbolic constants into a C
program.
Examples:-
#include<stdio.h> -For the standard input / output functions
The main() function:-
As the name itself indicates, this is the main function of every C program. Execution of C program
starts with main(). No C program is executed without the main() function. The function main() should be
written in lowercase letters and should not be terminated by a semicolon. There must be one and only
one main() function in every C program.
Braces:-
Every C program uses a pair of curly braces ({, }). The left brace indicates the beginning of the
main() function. The right brace indicates the end of the main() function. The braces can also be used to
indicate the beginning and end of use-defined functions.
Declarations:-
The declaration is a part of the C program where all the variables, arrays, functions etc.. used in
the C program are declared and may be initialized with their basic data types.
Statements:-
These are instructions to the computer to perform some specific operations. They may be I/O
statements, arithmetic statements, control statements and other statements. They also include
comments. The comments are explanatory notes on some instructions. The comment statements are not
compiled and executed.
User defined functions:-
These are subprograms. A subprogram is a function. The user-defined functions contain a set of
statements to perform a specific task. These are written by the user. They may be written before or after
the main() function.
Prepared By: Sreedhar Aakula, RGUKT
Example:
write a c program to display “hello computer” on the screen
#include<stdio.h>
void main()
{
printf("hello computer\n");
}
Compiling and Executing a C program:-
Compiling a C program means translating it into machine language. C compilers are used for this
purpose. The C program to be compiled must be typed in using an editor. An editor is a program which
allows the programmer to write the program and edit it. C compilers are available with and without
editors.
There are basically five steps in the successful execution of a program.
1. Creating a source file(program file)
2. Saving the program(with .c as extension)
3. Compilation
4. Linking system library functions

Prepared By: Sreedhar Aakula, RGUKT


5. Running(executing) the program

Operators and Expressions


 The symbols which are used to perform logical and mathematical operations in a program are
called operators.
 These operators join individual constants and variables to form expressions.
 Operators, functions, constants and variables are combined together to form expressions.
Consider the expression A + B * 5. where, +, * are operators, A, B are variables, 5 is constant and
A + B * 5 is an expression.
Associativity
It represents which operator should be evaluated first if an expression is containing more than one
operator with same priority.
Operator Priority Associativity
{}, (), [] 1 Left to right
++, --, ! 2 Right to left
*, /, % 3 Left to right
+, - 4 Left to right
<, <=, >, >=, ==, != 5 Left to right
&& 6 Left to right
|| 7 Left to right
?: 8 Right to left
=, +=, -=, *=, /=, %= 9 Right to left

Example1:
#include <stdio.h>
Prepared By: Sreedhar Aakula, RGUKT
int main() {
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
printf("Value of (a + b) * c / d is : %d\n", e );
e = ((a + b) * c) / d; // (30 * 15 ) / 5
printf("Value of ((a + b) * c) / d is : %d\n" , e );
e = (a + b) * (c / d); // (30) * (15/5)
printf("Value of (a + b) * (c / d) is : %d\n", e );
e = a + (b * c) / d; // 20 + (150/5)
printf("Value of a + (b * c) / d is : %d\n" , e );
return 0;
}
Output
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50

Operators in C Language
Operators are that symbols which work on operands. Operator in C language is used to perform specific
mathematical or logical computations on the operands and it reduces a single value.
Operators in C language, are classified into several categories.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Shift Operators
6. Ternary or Conditional Operators

Prepared By: Sreedhar Aakula, RGUKT


7. Assignment Operators
8. Sizeof Operators
9. Increment / Decrement operators

Arithmetic Operators
An arithmetic operator is used to perform arithmetic/mathematical operations on operands. Some of
the arithmetic operators are (+, -, *, /, %, ++, --)
Operator Name of Operator What it does How it is used
+ Plus Add two Operands a+b
- Minus Subtracts the second operand from the first. a-b
* Multiplication Multiplies both operands. a*b
/ Division Divides numerator by de-numerator. a/b
% Modulus return remainder, after an integer division. a%b
++ Increment Operator increases the integer value by one. a++
-- Decrement Operator decreases the integer value by one. a- -

Relational Operators
Relational operators help in making a relationship or comparison between two operands with which they
are used. Hence, relational operators help us make decisions in the program and their end result is either
true or false. Some of the relation operators are (==, !=, <, >, <=, >=)
Example: a==b
The expression given above, we used an equality operator that means it checks the value of a and b if
both values are the same then it will return true otherwise it will return false.

Prepared By: Sreedhar Aakula, RGUKT


Operator Name of Operator What it does Return value
== Equality Operator checks if a == b Boolean (True / False)
!= Not equal to checks if a != b Boolean (True / False)
< Less than checks if a < b Boolean (True / False)
> Greater than checks if a > b Boolean (True / False)
<= Less than or equal to checks if a<=b Boolean (True / False)
>= Greater than or equal to checks if a>=b Boolean (True / False)

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 of Operator Example

Logical AND If c=5 and d=2 then,


&& True only if all operands are true (c==5) && (d>5) equals to 0.

Logical OR If c=5 and d=2 then,


|| True only if either one operand is true (c==5) || (d>5) equals to 1.

Logical NOT If c = 5 then, expression ! (c == 5)


! True only if the operand is 0 equals to 0.

Example : Logical Operators


// C Program to demonstrate the 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) equals to %d \n", result);
result = (a = b) && (c < b);
Prepared By: Sreedhar Aakula, RGUKT
printf("(a = b) && (c < b) equals to %d \n", result);
result = (a = b) || (c < b);
printf("(a = b) || (c < b) equals to %d \n", result);
result = (a != b) || (c < b);
printf("(a != b) || (c < b) equals to %d \n", result);
result = !(a != b);
printf("!(a == b) equals to %d \n", result);
result = !(a == b);
printf("!(a == b) equals to %d \n", result);
return 0;
}
Bitwise Operators
An Bitwise operator is used for the manipulation of data at the bit level. These operators are not applied
for the float and double datatype. Bitwise operator first converts the integer into its binary
representation then performs its operation. Bitwise operators subsist of two digits, either 0 or 1. Some
of the bitwise operators are (&, | , ^, ~)
We use the following truth table for the Bitwise Operators:
A B A & B (Bitwise AND) A | B (Bitwise OR) A ^ B (Bitwise XoR)
1 1 1 1 0
0 1 0 1 1
1 0 0 1 1
0 0 0 0 0
Example:
a = 5, b = 6
a & b = 4 (In Decimal) a | b = 7 (In Decimal) a ^ b = 3 (In Decimal)
In the above example, We have two variables a and b.
a = 5 (In Decimal);
b = 6 (In Decimal);
So, a's binary representation is 0101(5) and b's binary representation is 0110(6)

Prepared By: Sreedhar Aakula, RGUKT


AND Operation OR Operation XOR Operation
0101 0101 0101
& 0110 | 0110 ^ 0110

0100 = 4 0111 = 7 0011 = 3


Operator Name of What it does How it
Operator is used
& bitwise AND bitwise AND operator do AND of every corresponding a&b
bits of both operands and output 1 (true) if both
operands have 1 at that position otherwise 0(false).
| bitwise OR bitwise OR operator do OR operation of every a|b
corresponding bits of both operands and output 0 (false)
if both operands have 0 at that position otherwise
1(true).
~ bitwise performs complement operation on an operand and ~a
complement bitwise complement changes 1 to 0 and 0 to 1
^ bitwise returns 1 if the corresponding bits of two operands are a^b
exclusive OR opposite else 0
<< shift left shifts the number of bits to the left side a << 1
>> shift right shifts the number of bits to the right side a >> 1

Shift Operators:
Right Shift Operator
Right shift operator shifts all bits towards right by certain number of specified bits. It is denoted by >>.
212 = 11010100 (In binary)
212>>2 = 00110101 (In binary) [Right shift by two bits]
212>>7 = 00000001 (In binary)
212>>8 = 00000000
212>>0 = 11010100 (No Shift)
Left Shift Operator
Left shift operator shifts all bits towards left by certain number of specified bits. It is denoted by <<.
212 = 11010100 (In binary)
212<<1 = 110101000 (In binary) [Left shift by one bit]
Prepared By: Sreedhar Aakula, RGUKT
212<<0 =11010100 (Shift by 0)
212<<4 = 110101000000 (In binary) =3392(In decimal)
C Ternary Operator (?:)
A conditional operator is a ternary operator, that is, it works on 3 operands.
Conditional Operator Syntax:
(condition) ? True part : False part
Example #6: C conditional Operator
#include<stdio.h>
int main()
{
int num;
printf("Enter the Number : ");
scanf("%d",&num);
(num%2==0)?printf("Even\n"):printf("Odd\n");
}
Output
Enter the Number : 4
Even
Assignment Operators
An assignment operator is used to assign values to the operands. Some of the assignment operators
are (=, +=, -=, *=, /=, %=)
Eample: a = b
In the above example, we are assigning b's value to variable a.
Operator Name of What it does How it is used
Operator
= assignment assign value of variable b to variable a a=b
+= plus assign a = a+b (adds values of a to b and assign this value to a += b
a)
-= minus assign a = a-b (subtracts values of b from a and assign this a -= b
value to a)
*= times assign a = a*b (Multiplies a with b and assign the value to a) a *= b
/= div assign a = a/b (divides a by b and assigns the value to a) a /= b

Prepared By: Sreedhar Aakula, RGUKT


%= Mod assign a = a%b (divides a by b and assigns the value of the a %= b
remainder to a)

Prepared By: Sreedhar Aakula, RGUKT


The sizeof operator
The sizeof is an unary operator which returns the size of data (constant, variables, array, structure etc).
Example #6: sizeof Operator implementation in C
#include <stdio.h>
int main()
{
int a, e[10];
float b;
double c;
char d;
printf("Size of int=%d bytes\n",sizeof(a));
printf("Size of float=%d bytes\n",sizeof(b));
printf("Size of double=%d bytes\n",sizeof(c));
printf("Size of char=%d byte\n",sizeof(d));
printf("Size of integer type array having 10 elements = %d bytes\n", sizeof(e));
return 0;
}
Output
Size of int = 4 bytes
Size of float = 4 bytes
Size of double = 8 bytes
Size of char = 1 byte
Size of integer type array having 10 elements = 40 bytes
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
// C Program to demonstrate the working of increment and decrement operators
#include <stdio.h>

Prepared By: Sreedhar Aakula, RGUKT


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;
}
Output
++a = 11
--b = 99
++c = 11.500000
--d = 99.500000
Here, the operators ++ and -- are used as prefix. These two operators can also be used as postfix like a++
and a--.
++ and -- operator as prefix and postfix:-
Suppose you use ++ operator as prefix like:++var. The value of var is incremented by 1 then, it returns
the value.
Suppose you use ++ operator as postfix like: var++. The original value of var is returned first then, var is
incremented by 1.
Example:-C program to demonstrate post increment and pre increment.
#include <stdio.h>
int main()
{
int var=5; // 5 is displayed then, var is increased to 6.
printf("%d\n",var++); // Initially, var = 6. It is increased to 7 then, it is displayed.
printf("%d",++var);
return 0;
}
Output

Prepared By: Sreedhar Aakula, RGUKT


5
7

Comments:
A comment is an explanation or description of the source code of the program. It helps a developer
explain logic of the code and improves program readability. At run-time, a comment is ignored by the
compiler.
There are 2 types of comments in the C language.
1. Single Line Comments
2. Multi-Line Comments

Single Line Comments:


Single line comments are represented by double slash \\. Let's see an example of a single line comment
in C.
Example:
#include<stdio.h>
int main(){
//printing information
printf("Hello C");
return 0;
}

MultiLine Comments
Multi-Line comments are represented by slash asterisk \* ... *\. It can occupy many lines of code, but it
can't be nested.
Syntax:
/*
code
to be commented
*/

Errors:
Errors are the problems or the faults that occur in the program (or)
Error is a abnormal condition whenever it occurs execution of the program is stopped.
There are commonly five types of errors exist in C programming:
1. Syntax error
2. Run-time error
3. Linker error
4. Logical error
5. Semantic error

Prepared By: Sreedhar Aakula, RGUKT


Synatx error:
Syntax errors are also known as the compilation errors as they occurred at the compilation time. These
errors are mainly occurred due to the mistakes while typing when programmer does not follow the
grammar rule of the programming language. These errors can be easily corrected.

Run-time error / Execution Error:


The errors exist during the execution-time even after the successful compilation known as run-time
errors. When the program is running, and it is not able to perform the operation is the main cause of
the run-time error. The division by zero is the common example of the run-time error.

Logical error:
The logical error is an error that leads to an undesired output. These errors produce the incorrect
output, but they are error-free, known as logical errors. The occurrence of these errors mainly depends
upon the logical thinking of the developer.

Semantic Error:
Errors that occur because the compiler is unable to understand the written code are called Semantic
Errors. A semantic error will be generated if the code makes no sense to the compiler, even though it is
syntactically correct. It is like using the wrong word in the wrong place in the English language.

Linker Error:
Linker errors are mainly generated when the executable file of the program is not created. This can be
happened either due to the wrong function prototyping or usage of the wrong header file.

Prepared By: Sreedhar Aakula, RGUKT


Practice Questions:

1. C Program to reading and displaying the data of all data types.


2. C program to print the address of given variable.
3. C program to find Sum and Average of two numbers
4. C Program to check whether number is EVEN or ODD using conditional operator.
5. C Program to find largest number among three numbers using conditional operator.
6. C Program to accept ten numbers and display sum of even and product of odd numbers
7. C Program to find out the sum of first n numbers. (Hint: Sum= n*(n+1)/2)
8. C Program to find the roots of a quadratic equation
9. C Program To calculate area and circumference of the circle
10. C program to print size of variables using sizeof () operators
11. C program to print ASCII value of entered character.

Prepared By: Sreedhar Aakula, RGUKT

You might also like