Professional Documents
Culture Documents
Faculty of Science
Department of Computer Science
CA3CO01
Problem Solving and Programming
Unit-II
Basics of Language
Books to be Referred
• Text Books
1. R.G. Dromey, How to Solve it by Computer, Pearson Education
2. B.W. Kernighan and D. M. Ritchie, The C Programming Language, Pearson Education.
3. B. Gottfried, Programming with C , 2nd Edition, (Indian Adapted Edition), TMH .
• References Books
1. H. Schildt C, The Complete Reference, Tata McGraw Hill.
2. E. Balaguruswamy, Programming in C, Tata McGraw Hill.
3. Y. Kanetkar, Let us C, BPB Publications.
4. Practical C Programming, 3rd Edition, A Nutshell Handbook O’Relly.
5. A. N Kamthaneet. al, Computer Programming and IT, Pearson Education, 2011.
Character Set
Every language contains a set of characters used to construct words, statements, etc., C language also has a
set of characters which include alphabets, digits, and special symbols. C language supports a total of 256
characters.
Every C program contains statements. These statements are constructed using words and these words are
constructed using characters from C character set. C language character set contains the following set of
characters...
1. Alphabets
2.Digits
3.Special Symbols
Alphabets
• C language supports all the alphabets from the English language. Lower and upper case
letters together support 52 alphabets.
• lower case letters - a to z
• UPPER CASE LETTERS - A to Z
Character Set
Digits
• C language supports 10 digits which are used to construct numerical values in C language.
• Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Symbols
• C language supports a rich set of special symbols that include symbols to perform mathematical
operations, to check conditions, white spaces, backspaces, and other special symbols.
• Special Symbols - ~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . > , < \ | tab newline space NULL
bell backspace vertical tab etc.,
Identifier
• In C programming language, programmers specify names to a variable, array, pointer or function. An identifier is a collection
of characters which acts as the name of variable, function, array, pointer, structure, etc. That is, an identifier can be defined
as the user-defined name to identify an entity uniquely in the C Programming Language.
The identifier is a user-defined name of an entity to identify it uniquely during the program execution
5.There is no limit for the length of an identifier. However, the compiler considers the first 31 characters only.
6.An identifier must be unique in its scope.
Rules for Choosing a Variable
• A variable name can consist of Capital letters A-Z, lowercase letters a-z, digits
0-9, and the underscore character.
• The first character must be a letter or underscore.
• Blank spaces cannot be used in variable names.
• Special characters like #, $ are not allowed.
• C keywords cannot be used as variable names.
• Variable names are case sensitive.
• Values of the variables can be numeric or alphabetic.
• Variable type can be char, int, float, double, or void.
Keywords
• A keyword is a reserved word. It has a predefined meaning and it is known to the compiler well in advance along with
its meaning.
• Keywords are specific reserved words in C each of which has a specific feature associated with it.
• Almost all of the words which help us use the functionality of the C language are included in the list of keywords.
Constants
1. const keyword
2.#define preprocessor
1) C const keyword
The const keyword is used to define constant in C programming.
Example - const float PI=3.14;
#include<stdio.h>
int main(){
const float PI=3.14;
printf("The value of PI is: %f",PI);
return 0;
}
• The definition of Basic Data Types / Primary Data Types / System-Defined Data Type is known to the compiler in
advance.
• The basic data types are char, integer-based and floating-point based. C language supports both signed and
unsigned literals.
• The memory size of the basic data types may change according to 32 or 64-bit operating system.
Basic Data Types / Primary Data Types / System-Defined Data Type
Format Specifiers of Basic Data Types / Primary Data Types /
System-Defined Data Type
Variables and Declaration
Syntax 1 :
type variable_name;
Or
Syntax 2 :
When the number of variables are more –
type variable_name, variable_name, variable_name;
EXAMPLES
1. int age ;
2. float percent ;
3. float radius, area;
Variable Declaration And Initialization
Syntax 1 :
type variable_name = Value ; (For Numeric Data Types)
Syntax 2 :
type variable_name = ‘Value’ ; (For Character Data Types)
EXAMPLE
double d;
/* actual initialization */
#include<stdio.h>
void main()
{
int age = 33;
printf("I am %d years old. \n", age);
}
Program Output
I am 33 years old.
Operators and Expressions
• An operator is a symbol that operates on a value or a variable. For example: + is an operator to perform addition.
• Operators are the foundation of any programming language. Thus the functionality of C/C++ programming language is
incomplete without the use of operators.
During computation, mathematical operations like: addition, subtraction, multiplication, division, etc are converted to bit-
level which makes processing faster and saves power.
The following table lists the bitwise operators. Assume variable 'A' holds 60 and variable 'B' holds 13, then −
3. Bitwise Operators
cont..
3. Bitwise Operators
cont..
Let A = 60 and
B = 13
Then in binary format, they will be as follows −
A = 0011 1100
B = 0000 1101
--------------------------------
A & B = 0000 1100
A | B = 0011 1101
A ^ B = 0011 0001
~A = 1100 0011
A =00111100
B =00001101
-------------------------------------
A&B =00001100
-------------------------------------
4. 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.
Example:
Let A = 1 and
B=0
5. 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.
For example: if A = 10, B= 20, then
5. Other Operators
Apart from above operators there are some other operators in C that are used to perform some specific task.
1. sizeof Operator: sizeof is a much used in the C programming language. It is a compile time unary operator which can be
used to compute the size of its operand. The result of sizeof is of unsigned integral type which is usually denoted by size_t.
Basically, sizeof operator is used to compute the size of the variable.
2. Comma Operator: The comma operator (represented by the token ,) is a binary operator that evaluates its first operand
and discards the result, it then evaluates the second operand and returns this value (and type). The comma operator has the
lowest precedence of any C operator. Comma acts as both operator and separator.
3. & Operator: Returns the address of a variable.
Example: &a; (It returns the actual address of the variable.)
4. * Operator: It is called Pointer to a variable.
Example: *a; (It is used to return the pointer to a variable.)
5. ?: Operator: It is called Conditional Operator and it is used to find Conditional Expressions. It is also called
Ternary Operator.
Broad Classification of Operators
• 1. Unary Operator: It has a Single Operand.
• Example: -
Minus is an Unary Operator
Operator precedence determines the grouping of terms in an expression and decides how an expression is
evaluated.
Certain operators have higher precedence than others; for example, the multiplication operator has a higher
precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence than
+, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at
the bottom. Within an expression, higher precedence operators will be evaluated first.
Operator Precedence and Associativity cont.
Input and Output Functions
• C programming language provides many built-in functions to
(i) read any given input and
(ii) display/write data on screen or in a file.
• To give input by the keyboard -------------------------- scanf( ), getchar( ) and gets( ) are used.
• To give output onto the screen ------------------------ printf( ), putchar( ), and puts( ) functions are used.
• These functions are inbuilt library functions, defined in stdio.h (header file).
1.scanf( ) reads input until it encounters whitespace, newline or End Of File(EOF) whereas gets() reads input until it encounters
newline or End Of File(EOF), gets() does not stop reading input when it encounters whitespace instead it takes whitespace as a string.
2.Scanf( ) can read multiple values of different data types whereas gets() will only get character string data.
Input and Output Functions Contined
• printf() function
The printf() function is used for output. It prints the given statement to the console.
The syntax of printf() function is given below:
printf("format string",argument_list);
The format string can be (%d for int, %c for Character, %f for float data etc.)
Example: printf("enter a number:");
• scanf() function
The scanf() function is used for input. It reads the input data from the console.
The syntax of printf() function is given below:
scanf("format string", &argument_list);
Example: scanf("%d",&number);
Simple Computational Problems involving the above constructs
C Program to print cube of given number
#include<stdio.h>
void main()
{
int number;
printf(“Enter a number:");
scanf("%d",&number);
printf("cube of number is:%d ",number*number*number);
}
Output:
Enter a number: 4
Cube of number is: 64
Control Statements
The statements that are used to control the flow of execution of statements are known as conditional control statements.
(i) if statement
The if statement is used to check some given condition and perform some operations depending upon the correctness of that condition. It is mostly
used in the scenario where we need to perform the different operations for the different conditions.
The syntax of the if statement is given below.
if(expression)
{
//code to be executed
}
Example:
if(a > b)
{ printf(“A is bigger”);
}
Control Statements Continued
•If the test expression is evaluated to false, statements inside the body of if are not executed.
Control Statements Continued
}
Example:
if(a > b)
{ printf(“A is bigger”);
}
else
{ printf(“B is bigger”);
}
Control Statements Continued
}
else if(expression 3)
{
//code to be executed if expression 3 is true
}
else
{
//code to be executed if all the conditions are false
}
// Program to relate two integers using =, > or < symbol
#include <stdio.h>
void main( )
{
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
//checks if the two integers are equal.
if(number1 == number2)
{
printf("Result: %d = %d",number1,number2);
}
//checks if number1 is greater than number2.
else if (number1 > number2)
{
printf("Result: %d > %d", number1, number2);
}
//checks if both test expressions are false
else
{
printf("Result: %d < %d",number1, number2);
}
}
Output:
Enter two integers: 13 24
Result : 13 < 24
Control Statements Continued
• The c switch statement is used to execute the code of multiple conditions. In a switch statement, you can not use operators, you have to
compare with a direct value like int value, float value, etc.
• Switch case statements have multiple cases to execute conditions and a default case that works like as else statement. This statement
allows a variable to be compared for equality against a list of values. Each value is known as a case, and the variable being checked for
each switch case.
• The break statement is optional in the switch statement. If there is no break statement in the switch case, all the switch cases will be
executed after matching the case value. It is called fall through the state of C switch statement.
Control Statements Continued
4) The break statement in switch case is not must. It is optional. If there is no break statement found in the case, all
the cases will be executed present after the matched case. It is known as fall through the state of C switch statement.
Limitations of switch
•Good for equality comparisons but not for range comparisons.
•Works good for int type data only and not good for other types of data.
•Works good with constants but not with variables (as case labels).
Control Statements Continued
switch(expression)
{
case value1: //code to be executed;
break; //optional
case value2: //code to be executed;
break; //optional
......
default: // code to be executed if all cases are not matched;
}
Control Statements Continued
The looping can be defined as repeating the same process multiple times until a specific condition satisfies. There are
three types of loops used in the C language. that is,(i) do..while (ii) while (iii) for
Advantage of loops in C
1) It provides code reusability.
2) Using loops, we do not need to write the same code again and again.
3) Using loops, we can traverse over the elements of data structures (array or linked lists).
Control Statements Continued
Jump Statements
(i) Conditional Jump
(i) Break
(ii) Continue
The break is a keyword in C which is used to bring the program control out of the loop. The break statement is used
inside loops or switch statement. The break statement breaks the loop one by one, i.e., in the case of nested loops, it
breaks the inner loop first and then proceeds to outer loops. The break statement in C can be used in the following
two scenarios:
1.With switch case
2.With loop
Syntax:
//loop or switch case
break;
Control Statements Continued
Jump Statements
(i) Conditional Jump
(i) Break
(ii) Continue
The continue statement in C language is used to bring the program control to the beginning of the loop. The continue
statement skips some lines of code inside the loop and continues with the next iteration. It is mainly used for a
condition so that we can skip some code for a particular condition.
Syntax:
//loop statements
continue;
//some lines of the code which is to be skipped
Control Statements Continued
Jump Statements
(ii) Unconditional Jump
(i) goto
The goto statement is known as jump statement in C. As the name suggests, goto is used to transfer the program
control to a predefined label. The goto statment can be used to repeat some part of the code for a particular condition.
It can also be used to break the multiple loops which can't be done by using a single break statement. However, using
goto is avoided these days since it makes the program less readable and complicated.
Syntax:
label:
//some part of the code;
goto label;
Nesting of Control Statements
• C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements inside
another loop. Let's observe an example of nesting loops in C.
• Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of
loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for example,
you can define 'while' loop inside a 'for' loop.
for (initialization; condition; update)
{
for(initialization; condition; update)
{
// inner loop statements.
}
// outer loop statements.
}
while(condition)
{
while(condition)
{
// inner loop statements.
}
// outer loop statements.
}
Nested do..while loop
The nested do..while loop means any type of loop which is defined inside the ‘do..while' loop.
do
{
do
{
// inner loop statements.
} while(condition);
// outer loop statements.
} while(condition);
C Program to print all the characters of C Character Set
#include<stdio.h>
#include<conio.h>
int main()
{
int i;
clrscr();
printf("ASCII ==> Character\n");
for(i = -128; i <= 127; i++)
printf("%d ==> %c\n", i, i);
getch();
return 0;
}