C Programming Notes
C Programming Notes
Identifiers
In this tutorial, you will learn about keywords. Keywords are
the reserved words in programming and are part of the
syntax. Also, you will learn about identifiers and proper way to
name an identifier.
Character set
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
Special Characters in C Programming
, < > . _
( ) ; $ :
% [ ] # ?
' & { } "
^ ! * / |
- \ ~ +
blank space, new line, horizontal tab, carriage return and form
feed
Keywords
Keywords are predefined, reserved words used in
programming that have special meaning. Keywords are part of
the syntax and they cannot be used as an identifier. For
example:
int money;
Keywords in C Language
do if static while
All these keywords, their syntax and application will be discussed in their
respective topics. However, if you want a brief information on these
keywords without going further, visit list of all keywords in C programming.
Identifiers
Identifiers are the names you can give to entities such as variables, functions,
structures etc.
Identifier names must be unique. They are created to give unique name to a C
entity to identify it during the execution of a program. For example:
int money;
double accountBalance;
Here, money and accountBalance are identifiers.
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:
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:
For example:
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
Note: E-5 = 10 -5
Character constants
A character constant is a constant which uses single quotation around
characters. For example: 'a', 'l', 'm', 'F'
Escape Sequences
Sometimes, it is necessary to use characters which cannot be typed or has
special meaning in C programming. For example: newline(enter), tab,
question mark etc. In order to use these characters, escape sequence is used.
For example: \n is used for newline. The backslash ( \ ) causes "escape" from
the normal way the characters are interpreted by the compiler.
Escape Sequences
\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\? Question mark
\0 Null character
String constants
String constants are the constants which are enclosed in a pair of double-
quote marks. For example:
"good" //string constant
Enumeration constants
Keyword enum is used to define enumeration types. For example:
Here, color is a variable and yellow, green, black and white are the
enumeration constants having value 0, 1, 2 and 3 respectively. For more
information, visit page: C Enumeration.
Data types in C
1. Fundamental Data Types
o Integer types
o Floating type
o Character type
2. Derived Data Types
o Arrays
o Pointers
o Structures
o Enumeration
This tutorial will focus on fundamental data types. To learn about derived
data types, visit the corresponding tutorial.
int id;
The size of int is either 2 bytes(In older PC's) or 4 bytes. If you consider an
integer having size of 4 byte( equal to 32 bits), it can take 2 32 distinct states
as: -2 31 ,-2 31 +1, ...,-2, -1, 0, 1, 2, ..., 2 31 -2, 2 31 -1
Similarly, int of 2 bytes, it can take 2 16 distinct states from -2 15 to 2 15 -1. If you
try to store larger number than 2 31 -1, i.e,+2147483647 and smaller number
than -2 31 , i.e, -2147483648, program will not run correctly.
Floating types
Floating type variables can hold real numbers such as: 2.34, -9.382, 5.0 etc.
You can declare a floating point variable in C by using
either float or double keyword. For example:
float accountBalance;
double bookPrice;
Character types
Keyword char is used for declaring character type variables. For example:
C Qualifiers
Qualifiers alters the meaning of base data types to yield a new data type.
Size qualifiers
Size qualifiers alters the size of a basic type. There are two size
qualifiers, longand short. For example:
long double i;
The size of float is 8 bytes. However, when long keyword is used, that
variable becomes 10 bytes.
Sign qualifiers
Integers and floating point variables can hold both negative and positive
values. However, if a variable needs to hold positive value
only, unsigned data types are used. For example:
There is another qualifier signed which can hold both negative and positive
only. However, it is not necessary to define variable signed since a variable is
signed by default.
An integer variable of 4 bytes can hold data from -2 31 to 2 31 -1. However, if the
variable is defined as unsigned, it can hold data from 0 to 2 32 -1.
It is important to note that, sign qualifiers can be applied to int and char types
only.
Constant qualifiers
An identifier can be declared as a constant. To do so const keyword is used.
Two commonly used functions for I/O (Input/Output) are printf() and scanf().
The scanf() function reads formatted input from standard input (keyboard)
whereas the printf() function sends formatted output to the standard output
(screen).
int main()
Output
C Programming
All valid C program must contain the main() function. The code
execution begins from the start of main() function.
The printf() is a library function to send formatted output to the screen.
Theprintf() function is declared in "stdio.h" header file.
Here, stdio.h is a header file (standard input output header file)
and #includeis a preprocessor directive to paste the code from the
header file when necessary. When the compiler
encounters printf() function and doesn't findstdio.h header file,
compiler shows error.
The return 0; statement is the "Exit status" of the program. In simple
terms, program ends.
int main()
int testInteger = 5;
Output
Number = 5
Inside the quotation of printf() function, there is a format string "%d" (for
integer). If the format string matches the argument (testInteger in this case),
it is displayed on the screen.
int main()
int testInteger;
scanf("%d",&testInteger);
printf("Number = %d",testInteger);
return 0;
Output
Enter an integer: 4
Number = 4
The scanf() function reads formatted input from the keyboard. When user
enters an integer, it is stored in variable testInteger. Note the '&' sign
before testInteger;&testInteger gets the address of testInteger and the value is
stored in that address.
int main()
float f;
scanf("%f",&f);
return 0;
Output
Value = 23.450000
The format string "%f" is used to read and display formatted in case of floats.
int main()
char var1;
scanf("%c",&var1);
return 0;
Output
Enter a character: g
You entered g.
int main()
char var1;
scanf("%c",&var1);
return 0;
Output
Enter a character: g
You entered g.
ASCII value of g is 103.
You can display a character if you know ASCII code of that character. This is
shown by following example.
int main()
return 0;
Output
int main()
return 0;
Output
C Programming Operators
C programming has various operators to perform tasks including arithmetic,
conditional and bitwise operations. You will learn about various C operators
and how to use them in this tutorial.
An operator is a symbol which operates on a value or a variable. For
example: +is an operator to perform addition.
Operators in C programming
Arithmetic Operators
Assignment Operators
Relational Operators
Logical Operators
Conditional Operators
Bitwise Operators
Special Operators
C Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition,
subtraction and multiplication on numerical values (constants and variables).
Operator Meaning of Operator
* multiplication
/ division
#include <stdio.h>
int main()
int a = 9,b = 4, 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("a/b = %d \n",c);
c=a%b;
return 0;
Output
a+b = 13
a-b = 5
a*b = 36
a/b = 2
#include <stdio.h>
int main()
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--. Visit this page to learn more on
howincrement 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
Operator Example Same as
%= a %= b a = a%b
#include <stdio.h>
int main()
int a = 5, c;
c = a;
c += a; // c = c+a
c -= a; // c = c-a
c *= a; // c = c*a
c %= a; // c = c%a
return 0;
Output
c = 5
c = 10
c = 5
c = 25
c = 5
c = 0
C 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.
== Equal to 5 == 3 returns 0
#include <stdio.h>
int main()
int a = 5, b = 5, c = 10;
printf("%d == %d = %d \n", a, b, a == b); // true
Output
5 == 5 = 1
5 == 10 = 0
5 > 5 = 0
5 > 10 = 0
5 < 5 = 0
5 < 10 = 1
5 != 5 = 0
5 != 10 = 1
5 >= 5 = 1
5 >= 10 = 0
5 <= 5 = 1
5 <= 10 = 1
C 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 indecision making in C programming.
#include <stdio.h>
int main()
return 0;
Output
(a = b) && (c > b) equals to 1
(a = b) || (c < b) equals to 1
(a != b) || (c < b) equals to 0
!(a != b) equals to 1
!(a == b) equals to 0
Bitwise Operators
In processor, mathematical operations like: addition, subtraction, addition
and division are done in bit-level which makes processing faster and saves
power.
Bitwise operators are used in C programming to perform bit-level operations.
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
Other Operators
Comma Operator
Comma operators are used to link related expressions together. For example:
int a, c = 5, d;
int main()
int a, e[10];
float b;
double c;
char d;
return 0;
Output
#include <stdio.h>
int main(){
char February;
int days;
scanf("%c",&February);
// If test condition (February == 'l') is true, days
equal to 29.
return 0;
Output
C Programming Introduction
Examples
You will learn to write simple programs such as displaying a line, adding two
numbers, and finding ASCII value of an character in this chapter.
This page provides examples on basics of C programming language like:
input/output, arithmetic operations etc. To understand these example, you
should have basic knowledge on following topics:
C Introduction Examples
C Programming Introduction Examples
C Program to Find Size of int, float, double and char of Your System
C if statement
if (testExpression)
// statements
#include <stdio.h>
int main()
int number;
scanf("%d", &number);
if (number < 0)
return 0;
Output 1
Enter an integer: -2
When user enters -2, the test expression (number < 0) becomes true.
Hence, You entered -2 is displayed on the screen.
Output 2
Enter an integer: 5
When user enters 5, the test expression (number < 0) becomes false and the
statement inside the body of if is skipped.
C if...else statement
The if...else statement executes some code if the test expression is true
(nonzero) and some other code if the test expression is false (0).
Syntax of if...else
if (testExpression) {
else {
// codes inside the body of else
If test expression is true, code inside the body of if statement is executed; and
code inside the body of else statement is skipped.
If test expression is false, code inside the body of else statement is executed;
and code inside the body of if statement is skipped.
#include <stdio.h>
int main()
int number;
scanf("%d",&number);
// True if remainder is 0
if( number%2 == 0 )
else
return 0;
Output
Enter an integer: 7
7 is an odd integer.
The nested if...else statement allows you to check for multiple test
expressions and execute different codes for more than two conditions.
if (testExpression1)
else if(testExpression2)
{
// statements to be executed if testExpression1 is
false and testExpression2 is true
else if (testExpression 3)
else
}
Example #3: C nested if...else statement
// Program to relate two integers using =, > or <
#include <stdio.h>
int main()
if(number1 == number2)
printf("Result: %d = %d",number1,number2);
}
// if both test expression is false
else
return 0;
Output
23
Result: 12 < 23
You can also use switch statement to make decision between multiple
possibilites.
Loops are used in programming to repeat a specific block until some end
condition is met. There are three loops in C programming:
1. for loop
2. while loop
3. do...while loop
for Loop
The syntax of a for loop is:
// codes
Then, the test expression is evaluated. If the test expression is false (0), for
loop is terminated. But if the test expression is true (nonzero), codes inside
the body of for loop is executed and update expression is updated. This
process repeats until the test expression is false.
The for loop is commonly used when the number of iterations is known.
int main()
scanf("%d", &n);
sum += count;
return 0;
Output
The value entered by the user is stored in variable n. Suppose the user entered
10.
The count is initialized to 1 and the test expression is evaluated. Since, the
test expression count <= n (1 less than or equal to 10) is true, the body of for
loop is executed and the value of sum will be equal to 1.
Then, the update statement ++count is executed and count will be equal to 2.
Again, the test expression is evaluated. The test expression is evaluated to
true and the body of for loop is executed and the sum will be equal to 3. And,
this process goes on.
Eventually, the count is increased to 11. When the count is 11, the test
expression is evaluated to 0 (false) and the loop terminates.
Loops are used in programming to repeat a specific block until some end
condition is met. There are three loops in C programming:
1. for loop
2. while loop
3. do...while loop
while loop
The syntax of a while loop is:
while (testExpression)
//codes
If the test expression is true (nonzero), codes inside the body of while loop is
evaluated. Then, again the test expression is evaluated. The process goes on
until the test expression is false.
#include <stdio.h>
int main()
int number;
long long factorial;
scanf("%d",&number);
factorial = 1;
--number;
return 0;
Output
Enter an integer: 5
Factorial = 120
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 once, before checking the test
expression. Hence, the do...while loop is executed at least once.
do
// codes
while (testExpression);
How do...while loop works?
The code block (loop body) inside the braces is executed once.
Then, the test expression is evaluated. If the test expression is true, the loop
body is executed again. This process goes on until the test expression is
evaluated to 0 (false).
When the test expression is false (nonzero), the do...while loop is terminated.
int main()
do
scanf("%lf", &number);
sum += number;
while(number != 0.0);
printf("Sum = %.2lf",sum);
return 0;
Output
Enter a number: 0
Sum = 4.70
break Statement
The break statement terminates the loop immediately when it is encountered.
The break statement is used with decision making statement such as if...else.
Syntax of break statement
break;
# include <stdio.h>
int main()
{
int i;
scanf("%lf",&number);
break;
printf("Sum = %.2lf",sum);
return 0;
}
Output
Enter a n4: -3
Sum = 10.30
continue Statement
The continue statement skips some statements inside the loop. The continue
statement is used with decision making statement such as if...else.
continue;
Flowchart of continue Statement
How continue statement works?
# include <stdio.h>
int main()
int i;
scanf("%lf",&number);
continue;
}
printf("Sum = %.2lf",sum);
return 0;
Output
Sum = 59.70
In the program, when the user enters positive number, the sum is calculated
using sum += number; statement.
When the user enters negative number, the continue statement is executed and
skips the negative number from calculation.
The nested if...else statement allows you to execute a block code among
many alternatives. If you are checking on the value of a single variable
in nested if...else statement, it is better to use switch statement.
The switch statement is often faster than nested if...else (not always). Also,
the syntax of switch statement is cleaner and easy to understand.
Syntax of switch...case
switch (n)
case constant1:
break;
case constant2:
break;
default:
When a case constant is found that matches the switch expression, control of
the program passes to the block of code associated with that case.
In the above pseudo code, suppose the value of n is equal to constant2. The
compiler will execute the block of code associate with the case statement
until the end of switch block, or until the break statement is encountered.
The break statement is used to prevent the code running into the next case.
switch Statement Flowchart
Example: switch Statement
// Program to create a simple calculator
# include <stdio.h>
int main() {
char operator;
double firstNumber,secondNumber;
scanf("%c", &operator);
switch(operator)
case '+':
printf("%.1lf + %.1lf = %.1lf",firstNumber,
secondNumber, firstNumber+secondNumber);
break;
case '-':
break;
case '*':
break;
case '/':
break;
default:
return 0;
Output
12.4
The - operator entered by the user is stored in operator variable. And, the two
operands, 32.5 and 12.4 are stored in
variable firstNumber and secondNumberrespectively.
goto label;
... .. ...
... .. ...
... .. ...
label:
statement;
# include <stdio.h>
int main()
int i;
goto jump;
jump:
average=sum/(i-1);
return 0;
Output
1. Enter a number: 3
Sum = 16.60
one:
test += i;
goto two;
two:
if (test > 5) {
goto three;
... .. ...
Also, goto statement allows you to do bad stuff such as jump out of scope.
That being said, goto statement can be useful sometimes. For example: to
break from nested loops.
C Programming Functions
In programming, a function is a segment that groups code to perform a
specific task.
A C program has at least one function main(). Without main() function, there
is technically no C program.
Types of C functions
There are two types of functions in C programming:
Library function
User defined function
Library function
Library functions are the in-built function in C programming system. For
example:
main()
printf()
scanf()
#include <stdio.h>
void function_name(){
................
................
int main(){
...........
...........
function_name();
...........
...........
As mentioned earlier, every C program begins from main() and program starts
executing the codes inside main() function. When the control of program
reaches to function_name() inside main() function. The control of program
jumps to void function_name() and executes the codes inside it. When all the
codes inside that user-defined function are executed, control of the program
jumps to the statement just after function_name() from where it is called.
Analyze the figure below for understanding the concept of function in C
programming. Visit this page to learn in detail about user-defined functions.
1. User defined functions helps to decompose the large program into small
segments which makes programmer easy to understand, maintain and
debug.
2. If repeated code occurs in a program. Function can be used to include
those codes and execute when needed by calling that function.
3. Programmer working on large project can divide the workload by
making different functions.
C Programming User-defined
functions
This chapter is the continuation to the function Introduction chapter.
Example of user-defined function
Write a C program to add two integers. Make a function add to add integers
and display sum in main() function.
#include <stdio.h>
int main(){
int num1,num2,sum;
scanf("%d %d",&num1,&num2);
printf("sum=%d",sum);
return 0;
int add;
add=a+b;
return add; //return statement of
function
Function prototype(declaration):
Every function in C programming should be declared before they are used.
These type of declaration are also called function prototype. Function
prototype gives compiler information about function name, type of arguments
to be passed and return type.
function_name(argument(1),....argument(n));
Function definition
Function definition contains programming codes to perform specific task.
//body of function
Syntax of function declaration and declarator are almost same except, there is
no semicolon at the end of declarator and function declarator is followed by
function body.
2. Function body
Function declarator is followed by body of function inside braces.
In above example two variable, num1 and num2 are passed to function during
function call and these arguments are accepted by arguments a and b in
function definition.
Arguments that are passed in function call and arguments that are accepted in
function definition should have same data type. For example:
If argument num1 was of int type and num2 was of float type then, argument
variable a should be of type int and b should be of type float,i.e., type of
argument during function call and function definition should be same.
Return Statement
Return statement is used for returning a value from function definition to
calling function.
return (expression);
For example:
return a;
return (a+b);
In above example, value of variable add in add() function is returned and that
value is stored in variable sum in main() function. The data type of
expression in return statement should also match the return type of function.
C Programming String
In C programming, array of character are called strings. A string is
terminated by null character /0. For example:
char s[5];
char *p
Initialization of strings
In C, string can be initialized in different number of ways.
char c[]="abcd";
OR,
char c[5]="abcd";
OR,
char c[]={'a','b','c','d','\0'};
OR;
char c[5]={'a','b','c','d','\0'};
char *c="abcd";
char c[20];
scanf("%s",c);
String variable c can only take a word. It is beacause when white space is
encountered, the scanf() function terminates.
#include <stdio.h>
int main(){
char name[20];
printf("Enter name: ");
scanf("%s",name);
return 0;
Output
Here, program will ignore Ritchie because, scanf() function takes only string
before the white space.
#include <stdio.h>
int main(){
char name[30],ch;
int i=0;
{
ch=getchar();
name[i]=ch;
i++;
printf("Name: %s",name);
return 0;
int main(){
char name[30];
printf("Name: ");
return 0;
Output
Enter name: Tom Hanks
#include <stdio.h>
int main(){
char c[50];
gets(c);
return 0;
puts(ch);