Unit-1
Programming Concepts
Dr. Amit Kukker
Assistant Professor,
E&TC Department,
SIT, Pune
Contents
o History of C
o Middle level language
o Compiler and Interpreter
o Algorithms & Pseudocode
o Identifiers
o Keywords
o Variables and Datatypes
o Constants
o Operator
o Pre-processor and Macros
o Decision making
o Branching
o Looping statements
History of C
C was originally developed in the 1970s, by Dennis Ritchie at Bell Telephone
Laboratories, Inc.
C is a High level , general –purpose structured programming language.
Instructions of C consists of terms that are very closely same to algebraic
expressions, consisting of certain English keywords such as if, else, for ,do
and while
C contains certain additional features that allows it to be used at a lower
level, acting as bridge between machine language and the high level
languages.
This allows C to be used for system programming as well as for applications
programming
Assembly Language (Middle Level Language)
Middle-level language is a computer language in which the instructions are created using
symbols such as letters, digits and special characters.
Assembly language is an example of middle-level language.
In assembly language, we use predefined words called mnemonics. Binary code instructions
in low-level language are replaced with mnemonics and operands in middle-level language.
But the computer cannot understand mnemonics, so we use a translator called Assembler to
translate mnemonics into machine language.
Assembler is a translator which takes assembly code as input and produces machine code as
output.
That means, the computer cannot understand middle-level language, so it needs to be
translated into a low-level language to make it understandable by the computer.
Assembler is used to translate middle-level language into low-level language.
Compiler and Interpreter
Compiler and interpreter are used to convert the high level language into machine level
language.
The program written in high level language is known as source program and the
corresponding machine level language program is called as object program.
Both compiler and interpreter perform the same task but there working is different.
Compiler read the program at-a-time and searches the error and lists them. If the
program is error free then it is converted into object program. When program size is
large then compiler is preferred.
Whereas interpreter read only one line of the source code and convert it to object code.
If it check error, statement by statement and hence of take more time.
Programming languages like JavaScript, Python, Ruby use interpreters. Programming
languages like C, C++, Java use compilers.
Algorithm & Pseudocode
An algorithm is a procedure or set of instructions which are followed for solving a
mathematical problem or accomplishing a task.
An algorithm may or may not be written in a programming language.
While a pseudocode is an informal representation of an algorithm which is free from
the programming language.
Algorithm for finding the factorial of a positive
number
START
Step 1) Input the required integer variable, say n
Step 2) Assign value to n
Step 3) Multiply each from n-1 upto 1 with variable n
Step 4) Store the value of n and display it.
STOP
Pseudocode for finding the factorial of a positive number
Steps to find factorial (variable or ‘n’ )
For value 1 to n
Factorial = factorial * value
End for display factorial value
End steps
Program : Finding factorial of a positive number in C
Identifiers
A 'C' program consist of two types of elements , user defined and system
defined. Identifiers is nothing but a name given to these elements.
An identifier is a word used by a programmer to name a variable , function,
or label.
Identifiers consist of letters and digits, in any order, except that the first
character or label.
Identifiers consist of letters and digits if any order, except that the first
character must be letter.
Both Upper and lowercase letters can be used
Keywords
Keywords are nothing but system defined auto double int struct
identifiers.
break else long switch
Keywords are reserved words of the
case enum register typedef
language.
char extern return union
They have specific meaning in the
language and cannot be used by the const float short unsigned
programmer as variable or constant names
continue for signed void
C is case sensitive, it means these must be
default goto sizeof volatile
used as it is
do if static while
32 Keywords in C Programming
Variables & Data Types
A variable is nothing but a name given to a storage area that our programs can
manipulate. Each variable in C has a specific data type, which determines the size and
layout of the variable's memory; the range of values that can be stored within that
memory; and the set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and lowercase letters
are distinct because C is case-sensitive. There are following basic variable data types:
Type Description
• char Typically a single octet(one byte). This is an integer type.
• int The most natural size of integer for the machine.
• float A single-precision floating point value.
• double A double-precision floating point value.
• void Represents the absence of type.
Constants
A constant is a value or an identifier whose value cannot be altered in a program. For
example: 1, 2.5
As mentioned, an identifier also can be defined as a constant. eg. const double PI = 3.14
Here, PI is a constant. Basically what it means is that, PI and 3.14 is same for this
program.
Integer constants
A integer constant is a numeric constant (associated with number) without any fractional
or exponential part. There are three types of integer constants in C programming:
• decimal constant(base 10)
• octal constant(base 8)
• hexadecimal constant(base 16)
Constants
Floating-point constants
A floating point constant is a numeric constant that has either a fractional form or
an exponent form. For example: 2.0,0.0000234,-0.22E-5
Character constants
A character constant is a constant which uses single quotation around
characters. For example: 'a', 'l', 'm', 'F'
String constants
String constants are the constants which are enclosed in a pair of double-quote
marks. For example: "good" ,"x",“ Earth is round \n"
Escape Sequences
Sometimes, it is necessary to use characters which cannot be typed or has special meaning in C
programming. Example: newline(enter), tab, question mark etc. In order to use these characters,
escape sequence is used. Example: \n is used for newline. The backslash ( \ ) causes "escape"
from the normal way the characters are interpreted by the compiler.
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
\? Question mark
\0 Null character
Operators in C
An operator is a symbol which operates on a value or a variable.
For example: + is an operator to perform addition.
C programming has wide range of operators to perform various operations.
For better understanding of operators, these operators can be classified as:
Arithmetic Operators
Increment and Decrement Operators
Assignment Operators
Relational Operators
Logical Operators
Conditional Operators
Bitwise Operators
Special Operators
Arithmetic Operator
Operator Meaning of Operator
+ addition or unary plus
- subtraction or unary minus
* multiplication
/ division
% remainder after division ( modulus)
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:
int a=10, b=100
++a = 11
--b = 99
Assignment Operators
An assignment operator is used for assigning a value to a variable.
The most common assignment operator are:
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
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 returns 0
> Greater than 5 > 3 returns 1
< Less than 5 < 3 returns 0
!= Not equal to 5 != 3 returns 1
>= Greater than or equal to 5 >= 3 returns 1
<= Less than or equal to 5 <= 3 return 0
Input / output operations
stdin, stdout, stderr
When your C program begins to execute, three input/output devices are opened
automatically.
stdin
• The “standard input” device, usually your keyboard
stdout
• The “standard output” device, usually your monitor
stderr
• The “standard error” device, usually your monitor
Some C library I/O functions automatically use these devices
printf( ) conversions
Conversions specifications begin with % and end with a conversion character.
Between the % and the conversion character maybe, in order
A minus sign specifying left-justification
The minimum field width
A period separating the field width and precision
The precision that specifies
• Maximum characters for a string
• Number of digits after the decimal for a floating point
• Minimum number of digits for an integer
An h for “short” or an l (letter ell) for long
7/28/09
Common printf( ) Conversions
%d -- the int argument is printed as a decimal number
%u -- the int argument is printed as an unsigned number
%s -- prints characters from the string until ‘\0’ is seen or the number of
characters in the (optional) precision have been printed (more on this later)
%f -- the double argument is printed as a floating point number
%x, %X -- the int argument is printed as a hexadecimal number (without the
usual leading “0x”)
%c - the int argument is printed as a single character
%p - the pointer argument is printed (implementation dependent)
Keyboard Input
In C, keyboard input is accomplished using the scanf( ) function. scanf reads user input from stdin.
Calling scanf( ) is similar to calling printf( )
scanf( format, arg1, arg2, ... )
The format string has a similar structure to the format string in printf( ). The arguments are the
addresses of the variables into which the input is store.
scanf( ) format string
The scanf( ) format string usually contains conversion specifications that tell
scanf( ) how to interpret the next “input field”. An input field is a string of non-
whitespace characters.
The format string usually contains
Blanks or tabs which are ignored
Ordinary characters which are expected to match the next (non-
whitespace) character input by the user
Conversion specifications usually consisting
• % character indicating the beginning of the conversion
• An optional h, l (ell) or L
• A conversion character which indicates how the input field is to be
interpreted.
Common scanf( ) conversions
• %d -- a decimal (integer) number
• %u - an unsigned decimal (integer) number
• %x -- a hexadecimal number
• The matching argument is the address of an int
• May be preceded by h to indicate that the argument is the address of a short or by l (ell) to
indicate that the argument is the address of a long rather than an int
• %f, %e -- a floating point number with optional sign, optional decimal point, and optional exponent
• The matching argument is the address of a float
• May be preceded by l (ell) to indicate the argument is of the address of a double rather than a
float
• %s -- a word (a string delimited by white space, not an entire line)
• The matching argument is the address of a char or the name of a char array
• The caller must insure the array is large enough to for the input string and the terminating \0
character
• More on this later
• %c - a single character
• The matching arguments is the address of a char
• Does not skip over white-space
• More on this later
scanf( ) examples
int age;
double gpa;
printf(“Input your age: “);
scanf( “%d”, &age ); /* note & */
printf(“ input your gpa: “);
scanf (“%f”, &gpa );
Preprocessing & Macro’s
Preprocessing
Occurs before program compiled
Inclusion of external files
Definition of symbolic constants
Macros
Conditional compilation
Conditional execution
All directives begin with #
Can only have whitespace before directives
Directives not C++ statements
Do not end with ;
#include directive
• Puts copy of file in place of directive
• Seen many times in example code
• Two forms
• #include <filename>
• For standard library header files
• Searches predesignated directories
• #include "filename"
• Searches in current directory
• Normally used for programmer-
defined files
Usage
Loading header files
#include <iostream>
Programs with multiple source files
Header file
Has common declarations and definitions
Classes, structures, enumerations, function
prototypes
Extract commonality of multiple program files
#define
Symbolic constants
Constants represented as symbols
When program compiled, all occurrences replaced
Format
#define identifier replacement-text
#define PI 3.14159
Everything to right of identifier replaces text
#define PI=3.14159
Replaces PI with "=3.14159"
Probably an error
Cannot redefine symbolic constants
Advantages
Takes no memory
Disadvantages
Name not be seen by debugger (only replacement
text)
Do not have specific data type
const variables preferred
Macro
Operation specified in #define Intended for legacy C programs
Macro without arguments Treated like a symbolic constant
Macro with arguments
Arguments substituted for replacement text
Macro expanded Performs a text substitution
No data type checking
Example
#define CIRCLE_AREA( x ) ( PI * ( x ) * ( x ) )
area = CIRCLE_AREA( 4 );
becomes
area = ( 3.14159 * ( 4 ) * ( 4 ) );
Use parentheses Without them,
#define CIRCLE_AREA( x ) PI * x * x
area = CIRCLE_AREA( c + 2 );
becomes
area = 3.14159 * c + 2 * c + 2;
which evaluates incorrectly
Decision making
Decision making is about deciding the order of execution of statements based on
certain conditions or repeat a group of statements until certain specified conditions
are met. C language handles decision-making by supporting the following
statements,
•if statement
•switch statement
•conditional operator statement (? : operator)
•goto statement
Decision making with if statement
The if statement may be implemented in different forms depending on the complexity of
conditions to be tested. The different forms are,
[Link] if statement
[Link]....else statement
[Link] if....else statement
[Link] else if statement
Simple if statement
#include <stdio.h>
void main( )
{
int a, b, c;
printf("Enter 3 numbers...");
scanf("%d%d%d",&a, &b, &c);
if(a > b)
{
if(a > c)
{
printf("a is the greatest");
}
else
{
printf("c is the greatest");
}
}
else
{
if(b > c)
{
printf("b is the greatest");
}
else
{
printf("c is the greatest");
}
}
}
#include <stdio.h>
void main( )
{
int a;
printf("Enter a number...");
scanf("%d", &a);
if(a%5 == 0 && a%8 == 0)
{
printf("Divisible by both 5 and 8");
}
else if(a%8 == 0)
{
printf("Divisible by 8");
}
else if(a%5 == 0)
{
printf("Divisible by 5");
}
else
{
printf("Divisible by none");
}
}
Switch statement in C
When you want to solve multiple option type
problems, for example: Menu like program,
where one value is associated with each
option and you need to choose only one at a
time, then, switch statement is used.
Switch statement is a control statement that
allows us to choose only one choice among
the many given choices. The expression
in switch evaluates to return an integral
value, which is then compared to the values
present in different cases. It executes that
block of code which matches the case value.
If there is no match, then default block is
executed(if present). The general form
of switch statement is,
#include<stdio.h> switch(choice)
void main( ) {
{ case 1:
int a, b, c, choice; printf("Enter 2 numbers");
while(choice != 3) scanf("%d%d", &a, &b);
{ c = a + b;
/* Printing the available options */ printf("%d", c);
printf("\n 1. Press 1 for addition"); break;
printf("\n 2. Press 2 for subtraction"); case 2:
printf("\n Enter your choice"); printf("Enter 2 numbers");
/* Taking users input */ scanf("%d%d", &a, &b);
scanf("%d", &choice); c = a - b;
…. printf("%d", c);
break;
default:
printf("you have passed a wrong key");
printf("\n press any key to continue");
}
}
}
goto statement
A goto statement in C programming
provides an unconditional jump from the
'goto' to a labeled statement in the same
function.
NOTE − Use of goto statement is highly
discouraged in any programming
language because it makes difficult to
trace the control flow of a program,
making the program hard to understand
and hard to modify. Any program that uses
a goto can be rewritten to avoid them.
#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);
// Program to calculate the sum and
average of positive numbers // go to jump if the user enters a negative number
// If the user enters a negative number, if (number < 0.0) {
goto jump;
the sum and average are displayed.
}
sum += number;
}
jump:
average = sum / (i - 1);
printf("Sum = %.2f\n", sum);
printf("Average = %.2f", average);
return 0;
}
Branching Statements
A branch is an instruction in a computer program that can cause a computer to begin executing
a different instruction sequence and thus deviate from its default behavior of executing
instructions in order. Common branching statements include break, continue, return, and goto.
Loops in C
During programming, sometimes we might need to
execute a certain code statement again and again.
We can write the code statement as many times as
we need it to execute but that would be very
inefficient, because what if you want a code
statement to execute a 100 times? This is why we
use loops.
In any programming language including C language,
loops are used to execute a single statement or a
set of statements, repeatedly, until a particular
condition is satisfied.
Types of Loop in C
There are 3 types of Loop in C language, namely:
[Link] loop
[Link] loop
[Link] while loop
#include <stdio.h>
int main()
{
int n;
printf("Enter the number of times you want to print your name:");
scanf("%d", &n);
char name[30];
printf("Enter your name:");
scanf("%s", &name);
while(n)
{
//here we are checking if n is non-zero
printf("%s\n", name);
n--; //decrementing n
}
return 0;
}
Program to print first 10 natural numbers using while loop
#include<stdio.h>
void main( )
{
int x;
x = 1;
while(x <= 10)
{
printf("%d \t", x);
/* below statement means, do x = x+1, increment x by 1 */
x++;
}
}