C is a powerful general-purpose programming language.
It can be used to develop
software like operating systems, databases, compilers, and so on. C programming is an
excellent language to learn to program for beginners.
First Program - "Hello, World!" Program
#include <stdio.h>
int main() {
// printf() displays the string inside quotation
printf("Hello, World!");
return 0;
}
How "Hello, World!" program works?
The #include is a preprocessor command that tells the compiler to include the
contents of stdio.h (standard input and output) file in the program.
The stdio.h file contains functions such as scanf() and printf() to take input and
display output respectively.
If you use the printf() function without writing #include <stdio.h>, the program
will not compile.
The execution of a C program starts from the main() function.
printf() is a library function to send formatted output to the screen. In this
program, printf() displays Hello, World! text on the screen.
The return 0; statement is the "Exit status" of the program. In simple terms, the
program ends with this statement.
Comments
Comments are like helping text in your C program and they are ignored by the compiler.
They start with /* and terminate with the characters */ as shown below −
/* my first program in C */
C Keywords
Keywords are predefined, reserved words used in programming that have special
meanings to the compiler. Keywords are part of the syntax and they cannot be used as
an identifier. For example:
1|Page
int money;
Here, int is a keyword that indicates money is a variable of type int (integer).
As C is a case sensitive language, all keywords must be written in lowercase. Here is a
list of all keywords allowed in ANSI C.
C Keywords
auto double int struct
break else long switch
case enum register typedef
char extern return union
continue for signed void
do if static while
default goto sizeof volatile
const float short unsigned
C Identifiers
Identifier refers to name given to entities such as variables, functions, structures etc.
Identifiers must be unique. They are created to give a unique name to an entity to
identify it during the execution of the program. For example:
int money;
double accountBalance;
Here, money and accountBalance are identifiers.
Also remember, identifier names must be different from keywords. You cannot
use int as an identifier because int is a keyword.
Rules for naming identifiers
1. A valid identifier can have letters (both uppercase and lowercase letters), digits
and underscores.
2. The first letter of an identifier should be either a letter or an underscore.
3. You cannot use keywords as identifiers.
4. There is no rule on how long an identifier can be. However, you may run into
problems in some compilers if the identifier is longer than 31 characters.
2|Page
You can choose any name as an identifier if you follow the above rule, however, give
meaningful names to identifiers that make sense.
Variables
In programming, a variable is a container (storage area) to hold data.
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:
int playerScore = 95;
Here, playerScore is a variable of int type. Here, the variable is assigned an integer
value 95.
The value of a variable can be changed, hence the name variable.
char ch = 'a';
// some code
ch = 'l';
Rules for naming a variable
1. A variable name can only have letters (both uppercase and lowercase letters),
digits and underscore.
2. The first letter of a variable should be either a letter or an underscore.
3. There is no rule on how long a variable name (identifier) can be. However, you
may run into problems in some compilers if the variable name is longer than 31
characters.
Constants
If you want to define a variable whose value cannot be changed, you can use
the const keyword. This will create a constant. For example,
const double PI = 3.14;
Notice, we have added keyword const.
Here, PI is a symbolic constant; its value cannot be changed.
const double PI = 3.14;
PI = 2.9; //Error
3|Page
Data Types
In C programming, data types are declarations for variables. This determines the type
and size of data associated with variables. For example,
int myVar;
Here, myVar is a variable of int (integer) type.
Type Storage size Value range
char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long 8 bytes -9223372036854775808 to 9223372036854775807
unsigned long 8 bytes 0 to 18446744073709551615
int
Integers are whole numbers that can have both zero, positive and negative values but
no decimal values. For example, 0, -5, 10
We can use int for declaring an integer variable.
int id;
Here, id is a variable of type integer. You can declare multiple variables at once in C
programming. For example,
int id, age;
4|Page
float and double
float and double are used to hold real numbers.
float salary;
double price;
char
Keyword char is used for declaring character type variables. For example,
char test = 'h';
void
void is an incomplete type. It means "nothing" or "no type". You can think of void
as absent. For example, if a function is not returning anything, its return type should
be void.
Note that, you cannot create variables of void type.
short and long
If you need to use a large number, you can use a type specifier long. Here's how:
long a;
long long b;
long double c;
Here variables a and b can store integer values. And, c can store a floating-point
number.
If you are sure, only a small integer ([−32,767, +32,767] range) will be used, you can
use short.
short d;
5|Page
signed and unsigned
In C, signed and unsigned are type modifiers. You can alter the data storage of a data
type by using them. For example,
unsigned int x;
int y;
Here, the variable x can hold only zero and positive values because we have used
the unsigned modifier.
Considering the size of int is 4 bytes, variable y can hold values from -231 to 231-1,
whereas variable x can hold values from 0 to 232-1.
#include <stdio.h>
int main () {
/* variable definition: */
int a, b;
int c;
float f;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf("value of c : %d \n", c);
f = 70.0/3.0;
printf("value of f : %f \n", f);
return 0;
}
Strings
String is a sequence of characters terminated with a null character \0.
stng c[] = "c string";
Here's how you can declare strings:
char s[5];
6|Page
You can initialize strings in a number of ways.
char c[] = "abcd";
char c[50] = "abcd";
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
Integer Output
#include <stdio.h>
int main()
{
int testInteger = 5;
printf("Number = %d", testInteger);
return 0;
}
We use %d format specifier to print int types. Here, the %d inside the quotations will be
replaced by the value of testInteger.
float and double Output
int main()
{
float number1 = 13.5;
double number2 = 12.4;
printf("number1 = %f\n", number1);
printf("number2 = %lf", number2);
7|Page
return 0;
}
To print float, we use %f format specifier. Similarly, we use %lf to print double values.
Print Characters
int main()
{
char chr = 'a';
printf("character = %c", chr);
return 0;
}
To print char, we use %c format specifier.
Input
In C programming, scanf() is one of the commonly used function to take input from the
user. The scanf() function reads formatted input from the standard input such as
keyboards.
Integer Input/Output
int main()
{
int testInteger;
printf("Enter an integer: ");
scanf("%d", &testInteger);
printf("Number = %d",testInteger);
return 0;
}
Float and Double Input/Output
int main()
8|Page
{
float num1;
double num2;
printf("Enter a number: ");
scanf("%f", &num1);
printf("Enter another number: ");
scanf("%lf", &num2);
printf("num1 = %f\n", num1);
printf("num2 = %lf", num2);
return 0;
}
We use %f and %lf format specifier for float and double respectively.
Character I/O
int main()
{
char chr;
printf("Enter a character: ");
scanf("%c",&chr);
printf("You entered %c.", chr);
return 0;
}
Data Type Format Specifier
int %d
char %c
float %f
double %lf
short int %hd
unsigned int %u
long int %li
long long int %lli
unsigned long int %lu
unsigned long long int %llu
9|Page
signed char %c
unsigned char %c
long double %Lf
Operators
An operator is a symbol that operates on a value or a variable. For example: + is an
operator to perform addition.
C has a wide range of operators to perform various operations.
Operator Meaning of Operator
+ addition or unary plus
- subtraction or unary minus
* multiplication
/ division
% remainder after division (modulo division)
// Working of arithmetic operators
#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;
printf("Remainder when a divided by b = %d \n",c);
return 0;
}
Increment and Decrement Operators
C programming has two operators increment ++ and decrement -- to change the value of
an operand (constant or variable) by 1.
10 | P a g e
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.
// Working of increment and decrement operators
#include <stdio.h>
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;
}
Assignment Operators
An assignment operator is used for assigning a value to a variable.
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
// Working of assignment operators
#include <stdio.h>
int main()
{
int a = 5, c;
c = a; // c is 5
printf("c = %d\n", c);
c += a; // c is 10
printf("c = %d\n", c);
c -= a; // c is 5
printf("c = %d\n", c);
11 | P a g e
c *= a; // c is 25
printf("c = %d\n", c);
c /= a; // c is 5
printf("c = %d\n", c);
c %= a; // c = 0
printf("c = %d\n", c);
return 0;
}
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 is evaluated to 0
> Greater than 5 > 3 is evaluated to 1
< Less than 5 < 3 is evaluated to 0
!= Not equal to 5 != 3 is evaluated to 1
>= Greater than or equal to 5 >= 3 is evaluated to 1
<= Less than or equal to 5 <= 3 is evaluated to 0
// Working of relational operators
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10;
printf("%d == %d is %d \n", a, b, a == b);
printf("%d == %d is %d \n", a, c, a == c);
printf("%d > %d is %d \n", a, b, a > b);
printf("%d > %d is %d \n", a, c, a > c);
printf("%d < %d is %d \n", a, b, a < b);
printf("%d < %d is %d \n", a, c, a < c);
printf("%d != %d is %d \n", a, b, a != b);
printf("%d != %d is %d \n", a, c, a != c);
printf("%d >= %d is %d \n", a, b, a >= b);
printf("%d >= %d is %d \n", a, c, a >= c);
printf("%d <= %d is %d \n", a, b, a <= b);
printf("%d <= %d is %d \n", a, c, a <= c);
12 | P a g e
return 0;
}
Program to Add Two Integers
#include <stdio.h>
int main() {
int number1, number2, sum;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
// calculating sum
sum = number1 + number2;
printf("%d + %d = %d", number1, number2, sum);
return 0;
}
if Statement
The syntax of the if statement in C programming is:
if (test expression)
{
// statements to be executed if the test expression is true
}
How if statement works?
The if statement evaluates the test expression inside the parenthesis ().
If the test expression is evaluated to true, statements inside the body of if are
executed.
If the test expression is evaluated to false, statements inside the body of if are not
executed.
13 | P a g e
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
// true if number is less than 0
if (number < 0) {
printf("You entered %d.\n", number);
}
printf("The if statement is easy.");
return 0;
}
if...else Statement
The if statement may have an optional else block. The syntax of the if..else statement is:
if (test expression) {
// statements to be executed if the test expression is true
}
else {
// statements to be executed if the test expression is false
}
How if...else statement works?
If the test expression is evaluated to true,
statements inside the body of if are executed.
14 | P a g e
statements inside the body of else are skipped from execution.
If the test expression is evaluated to false,
statements inside the body of else are executed
statements inside the body of if are skipped from execution.
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
// True if the remainder is 0
if (number%2 == 0) {
printf("%d is an even integer.",number);
}
else {
printf("%d is an odd integer.",number);
}
return 0;
}
if...else Ladder
The if...else statement executes two different codes depending upon whether the test
expression is true or false. Sometimes, a choice has to be made from more than 2
possibilities.
15 | P a g e
The if...else ladder allows you to check between multiple test expressions and execute
different statements.
#include <stdio.h>
int 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);
}
return 0;
}
Nested if...else
It is possible to include an if...else statement inside the body of
another if...else statement.
This program given below relates two integers using either <, > and = similar to
the if...else ladder's example. However, we will use a nested if...else statement to solve
this problem.
16 | P a g e
#include <stdio.h>
int main() {
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
if (number1 >= number2) {
if (number1 == number2) {
printf("Result: %d = %d",number1,number2);
}
else {
printf("Result: %d > %d", number1, number2);
}
}
else {
printf("Result: %d < %d",number1, number2);
}
return 0;
}
Loop
C programming has three types of loops:
1. for loop
2. while loop
3. do...while loop
for loop
How for loop works?
The initialization statement is executed only once.
Then, the test expression is evaluated. If the test expression is evaluated to false,
the for loop is terminated.
However, if the test expression is evaluated to true, statements inside the body
of for loop are executed, and the update expression is updated.
17 | P a g e
Again the test expression is evaluated.
This process goes on until the test expression is false. When the test expression is false,
the loop terminates.
#include <stdio.h>
int main() {
int i;
for (i = 1; i < 11; ++i)
{
printf("%d ", i);
}
return 0;
}
#include <stdio.h>
int main()
{
int num, count, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &num);
for(count = 1; count <= num; ++count)
{
sum += count;
}
printf("Sum = %d", sum);
return 0;
}
while loop
How while loop works?
The while loop evaluates the test expression inside the parenthesis ().
If the test expression is true, statements inside the body of while loop are
executed. Then, the test expression is evaluated again.
18 | P a g e
The process goes on until the test expression is evaluated to false.
If the test expression is false, the loop terminates (ends).
#include <stdio.h>
int main()
{
int i = 1;
while (i <= 5)
{
printf("%d\n", i);
++i;
}
return 0;
}
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 at least once. Only then, the test expression is evaluated.
How do...while loop works?
The body of do...while loop is executed once. Only then, the test expression is
evaluated.
If the test expression is true, the body of the loop is executed again and the test
expression is evaluated.
This process goes on until the test expression becomes false.
If the test expression is false, the loop ends.
#include <stdio.h>
int main()
{
double number, sum = 0;
// the body of the loop is executed at least once
do
19 | P a g e
{
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
}
while(number != 0.0);
printf("Sum = %.2lf",sum);
return 0;
}
C break
The break statement ends the loop immediately when it is encountered. Its syntax is:
break;
The break statement is almost always used with if...else statement inside the loop.
# include <stdio.h>
int main()
{
int i;
double number, sum = 0.0;
20 | P a g e
for(i=1; i <= 10; ++i)
{
printf("Enter a n%d: ",i);
scanf("%lf",&number);
// If the user enters a negative number, the loop ends
if(number < 0.0)
{
break;
}
sum += number; // sum = sum + number;
}
printf("Sum = %.2lf",sum);
return 0;
}
C continue
The continue statement skips the current iteration of the loop and continues with the
next iteration. Its syntax is:
continue;
The continue statement is almost always used with the if...else statement.
# include <stdio.h>
int main()
{
int i;
21 | P a g e
double number, sum = 0.0;
for(i=1; i <= 10; ++i)
{
printf("Enter a n%d: ",i);
scanf("%lf",&number);
if(number < 0.0)
{
continue;
}
sum += number; // sum = sum + number;
}
printf("Sum = %.2lf",sum);
return 0;
}
switch Statement
The switch statement allows us to execute one code block among many alternatives.
You can do the same thing with the if...else..if ladder. However, the syntax of
the switch statement is much easier to read and write.
How does the switch statement work?
The expression is evaluated once and compared with the values of each case label.
If there is a match, the corresponding statements after the matching label are
executed. For example, if the value of the expression is equal to constant2,
statements after case constant2: are executed until break is encountered.
If there is no match, the default statements are executed.
If we do not use break, all statements after the matching label are executed.
By the way, the default clause inside the switch statement is optional.
#include <stdio.h>
int main() {
char operator;
22 | P a g e
double n1, n2;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operator);
printf("Enter two operands: ");
scanf("%lf %lf",&n1, &n2);
switch(operator)
{
case '+':
printf("%.1lf + %.1lf = %.1lf",n1, n2, n1+n2);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2);
break;
// operator doesn't match any case constant +, -, *, /
default:
printf("Error! operator is not correct");
}
return 0;
}
goto Statement
The goto statement allows us to transfer control of the program to the specified label.
The label is an identifier. When the goto statement is encountered, the control of the
program jumps to label: and starts executing the code.
#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);
23 | P a g e
scanf("%lf", &number);
// go to jump if the user enters a negative number
if (number < 0.0) {
goto jump;
}
sum += number;
}
jump:
average = sum / (i - 1);
printf("Sum = %.2f\n", sum);
printf("Average = %.2f", average);
return 0;
}
Arrays
An array is a variable that can store multiple values. For example, if you want to store
100 integers, you can create an array for it.
int data[100];
How to declare an array?
dataType arrayName[arraySize];
For example,
float mark[5];
Here, we declared an array, mark, of floating-point type. And its size is 5. Meaning, it can
hold 5 floating-point values.
It's important to note that the size and type of an array cannot be changed once it is
declared.
Access Array Elements
You can access elements of an array by indices.
Suppose you declared an array mark as above. The first element is mark[0], the second
element is mark[1] and so on.
24 | P a g e
Arrays have 0 as the first index, not 1. In this example, mark[0] is the first
element.
If the size of an array is n, to access the last element, the n-1 index is used. In this
example, mark[4]
How to initialize an array?
It is possible to initialize an array during declaration. For example,
int mark[5] = {19, 10, 8, 17, 9};
You can also initialize an array like this.
int mark[] = {19, 10, 8, 17, 9};
Here, we haven't specified the size. However, the compiler knows its size is 5 as we are
initializing it with 5 elements.
Change Value of Array elements
int mark[5] = {19, 10, 8, 17, 9}
// make the value of the third element to -1
mark[2] = -1;
// make the value of the fifth element to 0
mark[4] = 0;
Input and Output Array Elements
Here's how you can take input from the user and store it in an array element.
// take input and store it in the 3rd element
scanf("%d", &mark[2]);
// take input and store it in the ith element
25 | P a g e
scanf("%d", &mark[i-1]);
Here's how you can print an individual element of an array.
// print the first element of the array
printf("%d", mark[0]);
// print the third element of the array
printf("%d", mark[2]);
// print ith element of the array
printf("%d", mark[i-1]);
// Program to take 5 values from the user and store them in an array
// Print the elements stored in the array
#include <stdio.h>
int main() {
int values[5];
printf("Enter 5 integers: ");
// taking input and storing it in an array
for(int i = 0; i < 5; ++i) {
scanf("%d", &values[i]);
}
printf("Displaying integers: ");
// printing elements of an array
for(int i = 0; i < 5; ++i) {
printf("%d\n", values[i]);
}
return 0;
}
26 | P a g e