Unit 2 Computing Fundamentals and C Programming
Unit 2 Computing Fundamentals and C Programming
Overview of C
1. Documentation section
2. Preprocessor section
3. Definition section
4. Global declaration
5. Main function
6. User defined functions
Documentation section
It includes the statement specified at the beginning of a program, such as a
program's name, date, description, and title. It is represented as:
1. //name of a program
Or
1. /*
2. Overview of the code
3. .
4. */
Preprocessor section
The preprocessor section contains all the header files used in a program. It informs
the system to link the header files to the system libraries. It is given by:
1. #include<stdio.h>
2. #include<conio.h>
The #include statement includes the specific file as a part of a function at the time of
the compilation. Thus, the contents of the included file are compiled along with the
function being compiled. The #include<stdio.h> consists of the contents of the
standard input output files, which contains the definition of stdin, stdout, and stderr.
Whenever the definitions stdin, stdout, and stderr are used in a function, the
statement #include<stdio.h> need to be used.
There are various header files available for different purposes. For example, # include
<math.h>. It is used for mathematic functions in a program.
Define section
The define section comprises of different constants declared using the define
keyword. It is given by:
1. #define a = 2
Global declaration
The global section comprises of all the global declarations in the program. It is given
by:
char = 1 byte
float = 4 bytes
int = 4 bytes
We can also declare user defined functions in the global variable section.
Main function
main() is the first function to be executed by the computer. It is necessary for a code
to include the main(). It is like any other function available in the C library.
Parenthesis () are used for passing parameters (if any) to a function.
1. main()
We can also use int or main with the main (). The void main() specifies that the
program will not return any value. The int main() specifies that the program can
return integer type data.
1. int main()
Or
1. void main()
Local declarations
The variable that is declared inside a given function or block refers to as local
declarations.
1. main()
2. {
3. int i = 2;
4. i++;
5. }
Statements
The statements refers to if, else, while, do, for, etc. used in a program within the
main function.
Expressions
An expression is a type of formula where operands are linked with each other by the
use of operators. It is given by:
1. a - b;
2. a +b;
The program (basic or advance) follows the same sections as listed above.
Return function is generally the last section of a code. But, it is not necessary to
include. It is used when we want to return a value. The return function returns a value
when the return type other than the void is specified with the function.
Return type ends the execution of the function. It further returns control to the
specified calling function. It is given by:
1. return;
Or
1. return expression ;
For example,
return 0;
Examples
Let's begin with a simple program in C language.
It is given by:
Output
The detailed explanation of each part of a code is as follows:
/* Sum of the two It is the comment section. Any statement described in it is not
numbers */ considered as a code. It is a part of the description section in a
code.
The comment line is optional. It can be in a separate line or part of
an executable line.
printf() The printf() prints text on the screen. It is a function for displaying
constant or variables data. Here, 'Enter two numbers to be added' is
the parameter passed to it.
scanf() It reads data from the standard input stream and writes the result
into the specified arguments.
sum = a + b The addition of the specified two numbers will be passed to the
sum parameter in the output.
return 0 A program can also run without a return 0 function. It simply states
that a program is free from error and can be successfully exited.
Character set of C
character:- It denotes any alphabet, digit or special symbol used to represent information.
Use:- These characters can be combined to form variables. C uses constants, variables, operators, keywords
and expressions as building blocks to form a basic C program.
Character set:- The character set is the fundamental raw material of any language and they are used to
represent information. Like natural languages, computer language will also have well defined character set,
which is useful to build the programs..
ALPHABETS
Uppercase letters A-Z
Lowercase letters a-z
DIGITS 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
SPECIAL CHARACTERS
WHITESPACE CHARACTERS
Certain ASCII characters are unprintable, which means they are not displayed on the screen or printer. Those
characters perform other functions aside from displaying text. Examples are backspacing, moving to a newline,
or ringing a bell.
They are used in output statements. Escape sequence usually consists of a backslash and a letter or a
combination of digits. An escape sequence is considered as a single character but a valid character constant.
These are employed at the time of execution of the program. Execution characters set are always represented by
a backslash (\) followed by a character. Note that each one of character constants represents one character,
although they consist of two characters. These characters combinations are called as escape sequence.
Hexadecimal number \x
C Tokens
Every smallest individual unit of a c program is called token. Every instruction in a c program is a
collection of tokens. Tokens are used to construct c programs and they are said to the basic
building blocks of a c program.
1. Keywords
2. Identifiers
3. Operators
4. Special Symbols
5. Constants
6. Strings
7. Data values
C Keywords
As every language has words to construct statements, C programming also has words with a
specific meaning which are used to construct c program instructions. In the C programming
language, keywords are special words with predefined meaning. Keywords are also known as
In the C programming language, there are 32 keywords. All the 32 keywords have their meaning
Properties of Keywords
All the keywords in C programming language are defined as lowercase letters so they
must be used only in lowercase letters
Every keyword has a specific meaning, users can not change that meaning.
Keywords can not be used as user-defined names like variable, functions, arrays,
pointers, etc...
Every keyword in C programming language represents something or specifies some kind
of action to be performed by the compiler.
The following table specifies all the 32 keywords with their meaning...
switch break
case
default
C Identifiers
In C programming language, programmers can specify their name to a variable, array, pointer,
function, etc... An identifier is a collection of characters which acts as the name of variable,
function, array, pointer, structure, etc... In other words, an identifier can be defined as the user-
defined name to identify an entity uniquely in the c programming language that name may be of
the variable name, function name, array name, pointer name, structure name or a label.
Example
int marks;
char studentName[30];
C Operators
An operator is a symbol used to perform arithmetic and logical operations in a program. That
means an operator is a special symbol that tells the compiler to perform mathematical or logical
operations. C programming language supports a rich set of operators that are classified as
follows.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
5. Assignment Operators
6. Bitwise Operators
7. Conditional Operator
8. Special Operators
Arithmetic Operators (+, -, *, /, %)
The arithmetic operators are the symbols that are used to perform basic mathematical operations
like addition, subtraction, multiplication, division and percentage modulo. The following table
+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
⇒ The addition operator can be used with numerical data types and character data type. When it
is used with numerical values, it performs mathematical addition and when it is used with
⇒ The remainder of the division operator is used with integer data type only.
The relational operators are the symbols that are used to compare two values. That means the
relational operators are used to check the relationship between two values. Every relational
operator has two results TRUE or FALSE. In simple words, the relational operators are used to
define conditions in a program. The following table provides information about relational
operators.
Operato
r Meaning Example
< Returns TRUE if the first value is smaller than second value 10 < 5 is
otherwise returns FALSE FALSE
> Returns TRUE if the first value is larger than second value otherwise 10 > 5 is
returns FALSE TRUE
<= Returns TRUE if the first value is smaller than or equal to second 10 <= 5 is
value otherwise returns FALSE FALSE
>= Returns TRUE if the first value is larger than or equal to second 10 >= 5 is
value otherwise returns FALSE TRUE
!= Returns TRUE if both values are not equal otherwise returns FALSE 10 != 5 is
TRUE
The logical operators are the symbols that are used to combine multiple conditions into one
Operato
r Meaning Example
&& Logical AND - Returns TRUE if all conditions are TRUE 10 < 5 && 12 > 10 is
otherwise returns FALSE FALSE
! Logical NOT - Returns TRUE if condition is FLASE and !(10 < 5 && 12 > 10) is
returns FALSE if it is TRUE TRUE
⇒ Logical AND - Returns TRUE only if all conditions are TRUE, if any of the conditions is
⇒ Logical OR - Returns FALSE only if all conditions are FALSE, if any of the conditions is TRUE
The increment and decrement operators are called unary operators because both need only one
operand. The increment operators adds one to the existing value of the operand and the
decrement operator subtracts one from the existing value of the operand. The following table
The increment and decrement operators are used infront of the operand (++a) or after the
Pre-Increment or Pre-Decrement
In the case of pre-increment, the value of the variable is increased by one before the expression
evaluation. In the case of pre-decrement, the value of the variable is decreased by one before
the expression evaluation. That means, when we use pre-increment or pre-decrement, first the
value of the variable is incremented or decremented by one, then the modified value is used in
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i = 5,j;
j = ++i; // Pre-Increment
Output:
Post-Increment or Post-Decrement
In the case of post-increment, the value of the variable is increased by one after the expression
evaluation. In the case of post-decrement, the value of the variable is decreased by one after the
expression evaluation. That means, when we use post-increment or post-decrement, first the
expression is evaluated with existing value, then the value of the variable is incremented or
decremented by one.
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i = 5,j;
j = i++; // Post-Increment
Output:
Assignment Operators (=, +=, -=, *=, /=, %=)
The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand side
variable (Lvalue). The assignment operator is used in different variants along with arithmetic
operators. The following table describes all the assignment operators in the C programming
language.
+= Add both left and right-hand side values and store the result into left-hand side A += 10
variable ⇒A=
A+10
-= Subtract right-hand side value from left-hand side variable value and store the A -= B
result ⇒ A = A-B
into left-hand side variable
*= Multiply right-hand side value with left-hand side variable value and store the A *= B
result ⇒ A = A*B
into left-hand side variable
/= Divide left-hand side variable value with right-hand side variable value and store A /= B
the result ⇒ A = A/B
into the left-hand side variable
%= Divide left-hand side variable value with right-hand side variable value and store A %= B
the remainder ⇒A=A
into the left-hand side variable
Operator Meaning Example
%B
The bitwise operators are used to perform bit-level operations in the c programming language.
When we use the bitwise operators, the operations are performed based on the binary values.
The following table describes all the bitwise operators in the C programming language.
& the result of Bitwise AND is 1 if all the bits are 1 otherwise it is 0 A&B
⇒ 16 (10000)
^ the result of Bitwise XOR is 0 if all the bits are same otherwise it is 1 A^B
⇒ 13 (01101)
<< the Bitwise left shift operator shifts all the bits to the left by the A << 2
specified number of positions ⇒ 100
(1100100)
>> the Bitwise right shift operator shifts all the bits to the right by the A >> 2
specified number of positions ⇒ 6 (00110)
This operator is used for decision making. In this operator, first we verify a condition, then we
perform one operation out of the two operations based on the condition result. If the condition is
TRUE the first option is performed, if the condition is FALSE the second option is performed. The
Example
A = (10<15)?100:200; ⇒ A value is 100
sizeof operator
This operator is used to find the size of the memory (in bytes) allocated for a variable. This
sizeof(variableName);
Example
sizeof(A); ⇒ the result is 2 if A is an integer
This operator is used to separate variables while they are declaring, separate the expressions in
value during the program execution. That means, once a value is assigned to the constant, that
value can't be changed during the program execution. Once the value is assigned to the
A constant is a named memory location which holds only one value throughout the
program execution.
In C programming language, a constant can be of any data type like integer, floating-point,
Integer constants
An integer constant can be a decimal integer or octal integer or hexadecimal integer. A decimal
integer value is specified as direct integer value whereas octal integer value is prefixed with 'o'
An integer constant can also be unsigned type of integer constant or long type of integer
constant. Unsigned integer constant value is suffixed with 'u' and long integer constant value is
suffixed with 'l' whereas unsigned long integer constant value is suffixed with 'ul'.
Example
A floating-point constant must contain both integer and decimal parts. Some times it may also
contain the exponent part. When a floating-point constant is represented in exponent form, the
Character Constants
Example
'A'
'2'
'+'
In the C programming language, there are some predefined character constants called escape
sequences. Every escape sequence has its own special functionality and every escape
sequence is prefixed with '\' symbol. These escape sequences are used in output function called
'printf()'.
String Constants
A string constant is a collection of characters, digits, special symbols and escape sequences that
"This is btechsmartclass"
" This\
is\
btechsmartclass "
We can also define string constant by separating it with white space as follows...
Creating constants in C
We create a constant of any datatype using 'const' keyword. To create a constant, we prefix the
The general syntax for creating constant using 'const' keyword is as follows...
OR
Example
const int x = 10 ;
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i = 9 ;
const int x = 10 ;
i = 15 ;
x = 100 ; // creates an error
printf("i = %d\nx = %d", i, x ) ;
}
The above program gives an error because we are trying to change the constant variable value
(x = 100).
We can also create constants using '#define' preprocessor directive. When we create constant
using this preprocessor directive it must be defined at the beginning of the program (because all
We use the following syntax to create constant using '#define' preprocessor directive...
Example
#define PI 3.14
Example Program
#include<stdio.h>
#include<conio.h>
#defien PI 3.14
void main(){
int r, area ;
printf("Please enter the radius of circle : ") ;
scanf("%d", &r) ;
area = PI * (r * r) ;
printf("Area of the circle = %d", area) ;
}
C Variables
Variables in a c programming language are the named memory locations where the user can
store different values of the same datatype during the program execution. That means a variable
is a name given to a memory location in which we can store different values of the same data
type. In other words, a variable can be defined as a storage container to hold values of the same
datatype during the program execution. The formal definition of a data type is as follows...
Variable is a name given to a memory location where we can store different values of the
Every variable in c programming language must be declared in the declaration section before it is
used. Every variable must have a datatype that determines the range and type of values be
3. A variable name should not contain any special symbols except underscore(_).
4. A variable name can be of any length but compiler considers only the first 31 characters
Declaration of Variable
Declaration of a variable tells the compiler to allocate the required amount of memory with the
specified variable name and allows only specified datatype values into that memory location. In C
programming language, the declaration can be performed either before the function as global
variables or inside any block or function. But it must be at the beginning of block or function.
Declaration Syntax:
Example
int number;
The above declaration tells to the compiler that allocates 2 bytes of memory with the
name number and allows only integer values into that memory location.
eg:
C Expression Evaluation
and associativity. When there are multiple operators in an expression, they are evaluated
according to their precedence and associativity. The operator with higher precedence is
evaluated first and the operator with the least precedence is evaluated last.
expression...
10 + 4 * 3 / 2
In the above expression, there are three operators +, * and /. Among these three operators,
both multiplication and division have the same higher precedence and addition has lower
precedence. So, according to the operator precedence both multiplication and division are
evaluated first and then the addition is evaluated. As multiplication and division have the
same precedence they are evaluated based on the associativity. Here, the associativity of
multiplication and division is left to right. So, multiplication is performed first, then division
and finally addition. So, the above expression is evaluated in the order of * / and +. It is
evaluated as follows...
4 * 3 ====> 12
12 / 2 ===> 6
10 + 6 ===> 16
1) Associativity is only used when there are two or more operators of same
precedence.
The point to note is associativity doesn’t define the order in which operands of a
single operator are evaluated. For example, consider the following program,
associativity of the + operator is left to right, but it doesn’t mean f1() is always called
before f2(). The output of the following program is in-fact compiler dependent.
// Associativity is not used in the below
program.
// Output is compiler dependent.
#include <stdio.h>
int x = 0;
int f1()
{
x = 5;
return x;
}
int f2()
{
x = 10;
return x;
}
int main()
{
int p = f1() + f2();
printf("%d ", x);
return 0;
}
#include <stdio.h>
int main()
{
int a;
a = 1, 2, 3; // Evaluated as (a = 1),
2, 3
printf("%d", a);
return 0;
}
Please see the following precedence and associativity table for reference.
Operator Description
Associativity
() Parentheses (function call) (see Note 1) left-to-right
[] Brackets (array subscript)
. Member selection via object name
-> Member selection via pointer
++ — Postfix increment/decrement (see Note 2)
Prefix increment/decrement right-to-left
++ —
+– Unary plus/minus
!~ Logical negation/bitwise complement
(type) Cast (convert value to temporary value of type)
* Dereference
&
Address (of operand)
sizeof
Determine size in bytes on this implementation
* / % Multiplication/division/modulus left-to-right
+ – Addition/subtraction left-to-right
<< >> Bitwise shift left, Bitwise shift right left-to-right
< <= Relational less than/less than or equal to left-to-right
> >= Relational greater than/greater than or equal to
== != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
= Assignment right-to-left
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment
, Comma (separate expressions) left-to-right
It is good to know precedence and associativity rules, but the best thing is to use
brackets, especially for less commonly used operators (operators other than +, -, *..
etc). Brackets increase the readability of the code as the reader doesn’t have to see the
table to find out the order.
C Math
C Programming allows us to perform mathematical operations through the functions defined
in <math.h> header file. The <math.h> header file contains various methods for performing
mathematical operations such as sqrt(), pow(), ceil(), floor() etc.
C Math Functions
There are various methods in math.h header file. The commonly used functions of math.h
header file are given below.
No. Function Description
rounds down the given number. It returns the integer value which
2) floor(number)
is less than or equal to given number.
pow(base,
4) returns the power of given number.
exponent)
Let's see a simple example of math functions found in math.h header file.
1. #include<stdio.h>
2. #include <math.h>
3. int main(){
4. printf("\n%f",ceil(3.6));
5. printf("\n%f",ceil(3.3));
6. printf("\n%f",floor(3.6));
7. printf("\n%f",floor(3.2));
8. printf("\n%f",sqrt(16));
9. printf("\n%f",sqrt(7));
10. printf("\n%f",pow(2,4));
11. printf("\n%f",pow(3,3));
12. printf("\n%d",abs(-12));
13. return 0;
14. }
Output:
4.000000
4.000000
3.000000
3.000000
4.000000
2.645751
16.000000
27.000000
12
Also
acos(x)
asin(x)
A getchar() reads a single character from standard input, while a getc() reads a single
Syntax
var_name = getchar();
putchar(varname);
#include <stdio.h>
1.#include <conio.h>
2.#include <ctype.h>
3.int main()
4.{
5. char ch;
6. printf (" Enter a character ( If we want to exit press #) \n");
7. while (ch != '#') /* accept the number till the user does not enter the # to exit from the loo
p. */
8. {
9. ch = getchar();
10. printf (" \n We have entered the character : ");
11. putchar (ch); // print a single character
12. printf ("\n");
13. }
14. return 0;
15.}
C language provide us console input/output functions. As the name says, the console input/output
functions allow us to -
Read the input from the keyboard by the user accessing the console.
Display the output to the user at the console.
Note : These input and output values could be of any primitive data type.
Formatted input/output functions
Formatted console input/output functions are used to take one or more inputs from the user at
console and it also allows us to display one or multiple values in the output to the user at the
console.
scanf() This function is used to read one or multiple inputs from the
user at the console.
Some of the most commonly used format specifiers used in console formatted input/output
functions are displayed in the table below -
Format Specifiers Description
%d
Format specifier used to read or display a signed int integer value.