0% found this document useful (0 votes)
314 views96 pages

C Programming Notes

C programming has several data types including integers, floats, characters, and enums. Integers (int) can be used to store whole numbers, floats (float, double) can store real numbers, characters (char) store single characters, and enums allow defining sets of named values. Variables must be declared before use and given a unique name according to the naming rules.

Uploaded by

Ngatia Mukere
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
314 views96 pages

C Programming Notes

C programming has several data types including integers, floats, characters, and enums. Integers (int) can be used to store whole numbers, floats (float, double) can store real numbers, characters (char) store single characters, and enums allow defining sets of named values. Variables must be declared before use and given a unique name according to the naming rules.

Uploaded by

Ngatia Mukere
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 96

C Programming Keywords and

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

, < > . _

( ) ; $ :

% [ ] # ?
' & { } "

^ ! * / |

- \ ~ +

White space Characters

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;

Here, int is a keyword that indicates 'money' is a variable of


type 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.

Keywords in C Language

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

Along with these keywords, C supports other numerous keywords depending


upon the compiler.

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.

Also remember, identifier names must be different from keywords. You


cannot useint as an identifier because int is a keyword.

Rules for writing an identifier

1. A valid identifier can have letters (both uppercase and lowercase


letters), digits and underscore only.
2. The first letter of an identifier should be either a letter or an
underscore. However, it is discouraged to start an identifier name with
an underscore. It is because identifier that starts with an underscore can
conflict with system names.
In such cases, compiler will complain about it. Some system names that
start with underscore are _fileno, _iob, _wfopen etc.
3. There is no rule on the length of an identifier. However, the first 31
characters of identifiers are discriminated by the compiler. So, the first
31 letters of two identifiers in a program should be different.

Good Programming Practice


You can choose any name for an identifier. However, if the programmer
choose meaningful name for an identifier, it will be easy to understand and
work on.

C Programming Variables and


Constants
In this tutorial, you will learn about variables, rules for naming a variable,
constants and different type of constants in C programming.
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 integer type. The variable is holding


integer 95 in above program.

The value of an variable can be changed, hence the name 'variable'.

Rules for writing variable name in C

1. A variable name can have letters (both uppercase and lowercase


letters), digits and underscore only.
2. The first letter of a variable should be either a letter or an underscore.
However, it is discouraged to start variable name with an underscore. It
is because variable name that starts with an underscore can conflict
with a system name and may cause errot.
3. There is no rule on how long a variable can be. However, the first 31
characters of a variable are discriminated by the compiler. So, the first
31 letters of two variables in a program should be different.

In C programming, you have to declare a variable before you can use. It is a


common practice in C programming to declare all the variables at the
beginning of the program.
Constants/Literals
A constant is a value or an identifier whose value cannot be altered in a
program. For example: 1, 2.5, "C programming is easy" etc.

As mentioned, an identifier also can be defined as a constant.

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)

For example:

Decimal constants: 0, -9, 22 etc

Octal constants: 021, 077, 033 etc

Hexadecimal constants: 0x7f, 0x2a, 0x521 etc


In C programming, octal constant starts with a 0 and hexadecimal constant
starts with a 0x.

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

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

String constants
String constants are the constants which are enclosed in a pair of double-
quote marks. For example:
"good" //string constant

"" //null string constant

" " //string constant of six white


space

"x" //string constant having single


character.

"Earth is round\n" //prints string with newline

Enumeration constants
Keyword enum is used to define enumeration types. For example:

enum color {yellow, green, black, white};

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.

C Programming Data Types


In this tutorial, you will learn about data types and how to declare a variable
in C programming.

In C programming, variables or memory locations should be declared before


it can be used. Similarly, a function also needs to be declared before use.
Data types simply refers to the type and size of data associated with variables
and functions.

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.

Integer data types


Integers are whole numbers that can have both positive and neg ative values,
but no decimal values. Example: 0, -5, 10

In C programming, keyword int is used for declaring integer variable. For


example:

int id;

Here, id is a variable of type integer.

You can declare multiple variable at once in C programming. For example:


int id, age;

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;

Here, both accountBalance and bookPrice are floating type variables.

In C, floating values can be represented in exponential form as well. For


example:

float normalizationFactor = 22.442e2;


Difference between float and double
The size of float (single precision float data type) is 4 bytes. And the size
ofdouble (double precision float data type) is 8 bytes. Floating point variables
has a precision of 6 digits whereas the the precision of double is 14 digits.

Character types
Keyword char is used for declaring character type variables. For example:

char test = 'h'

Here, test is a character variable. The value of test is 'h'.

The size of character variable is 1 byte.

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.

Learn more about long keyword in C programming.


If you know that the value of a variable will not be large, short can be used.

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:

// unsigned variables cannot hold negative value

unsigned int positiveInteger;

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.

const int cost = 20;

The value of cost cannot be changed in the program.


Volatile qualifiers
A variable should be declared volatile whenever its value can be changed by
some external sources outside the program. Keyword volatile is used for
creating volatile variables.

C Programming Input Output (I/O):


printf() and scanf()
This tutorial focuses on two in-build functions printf() and scanf() to perform
I/O task in C programming. Also, you will learn how you write a valid
program in C.

C programming has several in-build library functions to perform input and


output tasks.

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).

Example #1: C Output

#include <stdio.h> //This is needed to run printf()


function.

int main()

printf("C Programming"); //displays the content


inside quotation
return 0;

Output

C Programming

How this program works?

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.

Example #2: C Integer Output


#include <stdio.h>

int main()

int testInteger = 5;

printf("Number = %d", testInteger);


return 0;

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.

Example #3: C Integer Input/Output


#include <stdio.h>

int main()

int testInteger;

printf("Enter an integer: ");

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.

Example #3: C Floats Input/Output


#include <stdio.h>

int main()

float f;

printf("Enter a number: ");

// %f format string is used in case of floats

scanf("%f",&f);

printf("Value = %f", f);

return 0;

Output

Enter a number: 23.45

Value = 23.450000
The format string "%f" is used to read and display formatted in case of floats.

Example #4: C Character I/O


#include <stdio.h>

int main()

char var1;

printf("Enter a character: ");

scanf("%c",&var1);

printf("You entered %c.",var1);

return 0;

Output

Enter a character: g

You entered g.

Format string %c is used in case of character types.

Little bit on ASCII code


When a character is entered in the above program, the character itself is not
stored. Instead a numeric value(ASCII value) is stored. And when we
displayed that value using "%c" text format, the entered character is
displayed.
Example #5: C ASCII Code
#include <stdio.h>

int main()

char var1;

printf("Enter a character: ");

scanf("%c",&var1);

// When %c text format is used, character is displayed


in case of character types

printf("You entered %c.\n",var1);

// When %d text format is used, integer is displayed


in case of character types

printf("ASCII value of %c is %d.", var1, var1);

return 0;

Output

Enter a character: g

You entered g.
ASCII value of g is 103.

The ASCII value of character 'g' is 103. When, 'g' is


entered, 103 is stored in variable var1 instead of g.

You can display a character if you know ASCII code of that character. This is
shown by following example.

Example #6: C ASCII Code


#include <stdio.h>

int main()

int var1 = 69;

printf("Character having ASCII value 69 is %c.",var1);

return 0;

Output

Character having ASCII value 69 is E.

Click here to learn more about the complete ASCII reference.

More on Input/Output of floats and Integers


Integer and floats can be displayed in different formats in C programming.
Example #7: I/O of Floats and Integers
#include <stdio.h>

int main()

int integer = 9876;

float decimal = 987.6543;

// Prints the number right justified within 6 columns

printf("4 digit integer right justified to 6 column:


%6d\n", integer);

// Tries to print number right justified to 3 digits


but the number is not right adjusted because there are
only 4 numbers

printf("4 digit integer right justified to 3 column:


%3d\n", integer);

// Rounds to two digit places

printf("Floating point number rounded to 2 digits:


%.2f\n",decimal);

// Rounds to 0 digit places


printf("Floating point number rounded to 0 digits:
%.f\n",987.6543);

// Prints the number in exponential


notation(scientific notation)

printf("Floating point number in exponential form:


%e\n",987.6543);

return 0;

Output

4 digit integer right justified to 6 column: 9876

4 digit integer right justified to 3 column: 9876

Floating point number rounded to 2 digits: 987.65

Floating point number rounded to 0 digits: 988

Floating point number in exponential form: 9.876543e+02

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.

C programming has wide range of operators to perform various operations.


For better understanding of operators, these operators can be classified as:

Operators in C programming

Arithmetic Operators

Increment and Decrement 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

+ addition or unary plus

- subtraction or unary minus

* multiplication

/ division

% remainder after division( modulo division)

Example #1: Arithmetic Operators


// C Program to demonstrate the 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;

Output

a+b = 13

a-b = 5

a*b = 36

a/b = 2

Remainder when a divided by b=1


The operators +, - and * computes addition, subtraction and multiplication
respectively as you might have expected.

In normal calculation, 9/4 = 2.25. However, the output is 2 in the program. It


is because both variables a and b are integers. Hence, the output is also an
integer. The compiler neglects the term after decimal point and shows answer
2 instead of 2.25.

The modulo operator % computes the remainder. When a = 9 is divided by b


= 4, the remainder is 1. The % operator can only be used with integers.

Suppose a = 5.0, b = 2.0, c = 5 and d = 2. Then in C


programming,

a/b = 2.5 // Because both operands are floating-point


variables

a/d = 2.5 // Because one operand is floating-point


variable

c/b = 2.5 // Because one operand is floating-point


variable

c/d = 2 // Because both operands are integers

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 #2: Increment and Decrement Operators

// C Program to demonstrate the 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;

}
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 =

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
Operator Example Same as

%= a %= b a = a%b

Example #3: Assignment Operators


// C Program to demonstrate the working of assignment
operators

#include <stdio.h>

int main()

int a = 5, c;

c = a;

printf("c = %d \n", c);

c += a; // c = c+a

printf("c = %d \n", c);

c -= a; // c = c-a

printf("c = %d \n", c);

c *= a; // c = c*a

printf("c = %d \n", c);


c /= a; // c = c/a

printf("c = %d \n", c);

c %= a; // c = c%a

printf("c = %d \n", c);

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.

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

Example #4: Relational Operators


// C Program to demonstrate the working of arithmetic
operators

#include <stdio.h>

int main()

int a = 5, b = 5, c = 10;
printf("%d == %d = %d \n", a, b, a == b); // true

printf("%d == %d = %d \n", a, c, a == c); // false

printf("%d > %d = %d \n", a, b, a > b); //false

printf("%d > %d = %d \n", a, c, a > c); //false

printf("%d < %d = %d \n", a, b, a < b); //false

printf("%d < %d = %d \n", a, c, a < c); //true

printf("%d != %d = %d \n", a, b, a != b); //false

printf("%d != %d = %d \n", a, c, a != c); //true

printf("%d >= %d = %d \n", a, b, a >= b); //true

printf("%d >= %d = %d \n", a, c, a >= c); //false

printf("%d <= %d = %d \n", a, b, a <= b); //true

printf("%d <= %d = %d \n", a, c, a <= c); //true


return 0;

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.

Operator Meaning of Operator Example

Logial AND. True only if If c = 5 and d = 2 then, expression ((c


&&
all operands are true == 5) && (d > 5)) equals to 0.

Logical OR. True only if If c = 5 and d = 2 then, expression ((c


||
either one operand is true == 5) || (d > 5)) equals to 1.

Logical NOT. True only if If c = 5 then, expression ! (c ==


!
the operand is 0 5) equals to 0.

Example #5: Logical Operators


// C Program to demonstrate the working of logical
operators

#include <stdio.h>

int main()

int a = 5, b = 5, c = 10, result;


result = (a = b) && (c > b);

printf("(a = b) && (c > b) equals to %d \n", result);

result = (a = b) && (c < b);

printf("(a = b) && (c < b) equals to %d \n", result);

result = (a = b) || (c < b);

printf("(a = b) || (c < b) equals to %d \n", result);

result = (a != b) || (c < b);

printf("(a != b) || (c < b) equals to %d \n", result);

result = !(a != b);

printf("!(a == b) equals to %d \n", result);

result = !(a == b);

printf("!(a == b) equals to %d \n", result);

return 0;

Output
(a = b) && (c > b) equals to 1

(a = b) && (c < b) equals to 0

(a = b) || (c < b) equals to 1

(a != b) || (c < b) equals to 0

!(a != b) equals to 1

!(a == b) equals to 0

Explanation of logical operator program

(a = b) && (c > 5) evaluates to 1 because both operands (a = b) and (c


> b)is 1 (true).
(a = b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false).
(a = b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
(a != b) || (c < b) evaluates to 0 because both operand (a != b) and (c <
b)are 0 (false).
!(a != b) evaluates to 1 because operand (a != b) is 0 (false). Hence, !(a
!= b) is 1 (true).
!(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a == b) is
0 (false).

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.

Operators Meaning of operators

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

~ Bitwise complement

<< Shift left

>> Shift right

Visit bitwise operator in C to learn more.

Other Operators
Comma Operator
Comma operators are used to link related expressions together. For example:

int a, c = 5, d;

The sizeof operator


The sizeof is an unary operator which returns the size of data (constant,
variables, array, structure etc).
Example #6: sizeof Operator
#include <stdio.h>

int main()

int a, e[10];

float b;

double c;

char d;

printf("Size of int=%lu bytes\n",sizeof(a));

printf("Size of float=%lu bytes\n",sizeof(b));

printf("Size of double=%lu bytes\n",sizeof(c));

printf("Size of char=%lu byte\n",sizeof(d));

printf("Size of integer type array having 10 elements


= %lu bytes\n", sizeof(e));

return 0;

Output

Size of int = 4 bytes

Size of float = 4 bytes

Size of double = 8 bytes


Size of char = 1 byte

Size of integer type array having 10 elements = 40 bytes

C Ternary Operator (?:)


A conditional operator is a ternary operator, that is, it works on 3 operands.

Conditional Operator Syntax

conditionalExpression ? expression1 : expression2

The conditional operator works as follows:

The first expression conditionalExpression is evaluated at first. This


expression evaluates to 1 if it's and evaluates to 0 if it's false.
If conditionalExpression is true, expression1 is evaluated.
If conditionalExpression is false, expression2 is evaluated.

Example #6: C conditional Operator

#include <stdio.h>

int main(){

char February;

int days;

printf("If this year is leap year, enter 1. If not


enter any integer: ");

scanf("%c",&February);
// If test condition (February == 'l') is true, days
equal to 29.

// If test condition (February =='l') is false, days


equal to 28.

days = (February == '1') ? 29 : 28;

printf("Number of days in February = %d",days);

return 0;

Output

If this year is leap year, enter 1. If not enter any


integer: 1

Number of days in February = 29

Other operators such as & (reference operator), * (dereference operator) and -


> (member selection) operator will be discussed in C pointers.

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:

1. Variables and Constants


2. Data Types
3. Input and Output in C programming
4. Operators

C Introduction Examples
C Programming Introduction Examples

C Program to Print a Sentence

C Program to Print a Integer Entered by a User

C Program to Add Two Integers Entered by User

C Program to Multiply two Floating Point Numbers

C Program to Find ASCII Value of Character Entered by User

C Program to Find Quotient and Remainder of Two Integers Entered by User

C Program to Find Size of int, float, double and char of Your System

C Program to Demonstrate the Working of Keyword long

C Program to Swap Two numbers Entered by User


C Programming if, if...else and
Nested if...else Statement
Decision making is used to specify the order in which statements are
executed. In this tutorial, you will learn to put decision making in a C
program using if, if..else and nested if...else statement.

C if statement
if (testExpression)

// statements

The if statement evaluates the test expression inside parenthesis.

If test expression is evaluated to true (nonzero), statements inside the body


of ifis executed.

If test expression is evaluated to false (0), statements inside the body of if is


skipped.

To learn more on test expression (when test expression is evaluated to


nonzero (true) and 0 (false)), check out relational and logical operators.
Flowchart of if statement

Example #1: C if statement


// Program to display a number if user enters negative
number

// If user enters positive number, that number won't be


displayed

#include <stdio.h>
int main()

int number;

printf("Enter an integer: ");

scanf("%d", &number);

// Test expression is true if number is less than 0

if (number < 0)

printf("You entered %d.\n", number);

printf("The if statement is easy.");

return 0;

Output 1

Enter an integer: -2

You entered -2.


The if statement is easy.

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

The if statement in C programming is easy.

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) {

// codes inside the body of if

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.

Flowchart of if...else statement


Example #2: C if...else statement
// Program to check whether an integer entered by the user
is odd or even

#include <stdio.h>

int main()

int number;

printf("Enter an integer: ");

scanf("%d",&number);

// True if remainder is 0

if( number%2 == 0 )

printf("%d is an even integer.",number);

else

printf("%d is an odd integer.",number);

return 0;

Output

Enter an integer: 7
7 is an odd integer.

When user enters 7, the test expression ( number%2 == 0 ) is evaluated to


false. Hence, the statement inside the body of else statement printf("%d is an
odd integer"); is executed and the statement inside the body of if is skipped.

Nested if...else statement (if...elseif....else


Statement)
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.

The nested if...else statement allows you to check for multiple test
expressions and execute different codes for more than two conditions.

Syntax of nested if...else statement.

if (testExpression1)

// statements to be executed if testExpression1 is true

else if(testExpression2)

{
// statements to be executed if testExpression1 is
false and testExpression2 is true

else if (testExpression 3)

// statements to be executed if testExpression1 and


testExpression2 is false and testExpression3 is true

else

// statements to be executed if all test expressions


are false

}
Example #3: C nested if...else statement
// Program to relate two integers using =, > or <

#include <stdio.h>

int main()

int number1, number2;

printf("Enter two integers: ");

scanf("%d %d", &number1, &number2);

//checks if 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);

}
// if both test expression is false

else

printf("Result: %d < %d",number1, number2);

return 0;

Output

Enter two integers: 12

23

Result: 12 < 23

You can also use switch statement to make decision between multiple
possibilites.

C Programming for Loop


Loops are used in programming to repeat a specific block of code. After
reading this tutorial, you will learn how to create a for loop in C
programming.

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:

for (initializationStatement; testExpression;


updateStatement)

// codes

How for loop works?


The initialization statement is executed only once.

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.

To learn more on test expression (when test expression is evaluated to


nonzero (true) and 0 (false)), check out relational and logical operators.
for loop Flowchart

Example: for loop


// Program to calculate the sum of first n natural numbers

// Positive integers 1,2,3...n are known as natural


numbers
#include <stdio.h>

int main()

int n, count, sum = 0;

printf("Enter a positive integer: ");

scanf("%d", &n);

// for loop terminates when n is less than count

for(count = 1; count <= n; ++count)

sum += count;

printf("Sum = %d", sum);

return 0;

Output

Enter a positive integer: 10


Sum = 55

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.

C programming while and do...while


Loop
Loops are used in programming to repeat a specific block of code. After
reading this tutorial, you will learn how to create a while and do...while loop
in C programming.

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

How while loop works?


The while loop evaluates the test expression.

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.

When the test expression is false, the while loop is terminated.


Flowchart of while loop

Example #1: while loop


// Program to find factorial of a number

// For a positive integer n, factorial = 1*2*3...n

#include <stdio.h>

int main()

int number;
long long factorial;

printf("Enter an integer: ");

scanf("%d",&number);

factorial = 1;

// loop terminates when number is less than or equal


to 0

while (number > 0)

factorial *= number; // factorial =


factorial*number;

--number;

printf("Factorial= %lld", factorial);

return 0;

Output
Enter an integer: 5

Factorial = 120

To learn more on test expression (when test expression is evaluated to


nonzero (true) and 0 (false)), check out relational and logical operators.

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...while loop Syntax

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.

Example #2: do...while loop


// Program to add numbers until user enters zero
#include <stdio.h>

int main()

double number, sum = 0;

// loop body is executed at least once

do

printf("Enter a number: ");

scanf("%lf", &number);

sum += number;

while(number != 0.0);

printf("Sum = %.2lf",sum);

return 0;

Output

Enter a number: 1.5


Enter a number: 2.4

Enter a number: -3.4

Enter a number: 4.2

Enter a number: 0

Sum = 4.70

To learn more on test expression (when test expression is evaluated to


nonzero (true) and 0 (false)), check out relational and logical operators.

C Programming break and continue


Statement
In this tutorial, you will learn how to use break and continue statements to
alter the program flow in loops.

It is sometimes desirable to skip some statements inside the loop or terminate


the loop immediately without checking the test expression. In such
cases, breakand continue statements are used.

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;

Flowchart of break statement


How break statement works?

Example #1: break statement


// Program to calculate the sum of maximum of 10 numbers

// Calculates sum until user enters positive number

# include <stdio.h>

int main()
{

int i;

double number, sum = 0.0;

for(i=1; i <= 10; ++i)

printf("Enter a n%d: ",i);

scanf("%lf",&number);

// If user enters negative number, loop is


terminated

if(number < 0.0)

break;

sum += number; // sum = sum + number;

printf("Sum = %.2lf",sum);

return 0;
}

Output

Enter a n1: 2.4

Enter a n2: 4.5

Enter a n3: 3.4

Enter a n4: -3

Sum = 10.30

This program calculates the sum of maximum of 10 numbers. It's because,


when the user enters negative number, the break statement is executed and
loop is terminated.

In C programming, break statement is also used with switch...case statement.

continue Statement
The continue statement skips some statements inside the loop. The continue
statement is used with decision making statement such as if...else.

Syntax of continue Statement

continue;
Flowchart of continue Statement
How continue statement works?

Example #2: continue statement


// Program to calculate sum of maximum of 10 numbers
// Negative numbers are skipped from calculation

# include <stdio.h>

int main()

int i;

double number, sum = 0.0;

for(i=1; i <= 10; ++i)

printf("Enter a n%d: ",i);

scanf("%lf",&number);

// If user enters negative number, loop is


terminated

if(number < 0.0)

continue;

sum += number; // sum = sum + number;

}
printf("Sum = %.2lf",sum);

return 0;

Output

Enter a n1: 1.1

Enter a n2: 2.2

Enter a n3: 5.5

Enter a n4: 4.4

Enter a n5: -3.4

Enter a n6: -45.5

Enter a n7: 34.5

Enter a n8: -4.2

Enter a n9: -1000


Enter a n10: 12

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:

// code to be executed if n is equal to constant1;

break;
case constant2:

// code to be executed if n is equal to constant2;

break;

default:

// code to be executed if n doesn't match any


constant

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

// Performs addition, subtraction, multiplication or


division depending the input from user

# include <stdio.h>

int main() {

char operator;

double firstNumber,secondNumber;

printf("Enter an operator (+, -, *,): ");

scanf("%c", &operator);

printf("Enter two operands: ");

scanf("%lf %lf",&firstNumber, &secondNumber);

switch(operator)

case '+':
printf("%.1lf + %.1lf = %.1lf",firstNumber,
secondNumber, firstNumber+secondNumber);

break;

case '-':

printf("%.1lf - %.1lf = %.1lf",firstNumber,


secondNumber, firstNumber-secondNumber);

break;

case '*':

printf("%.1lf * %.1lf = %.1lf",firstNumber,


secondNumber, firstNumber*secondNumber);

break;

case '/':

printf("%.1lf / %.1lf = %.1lf",firstNumber,


secondNumber, firstNumber/firstNumber);

break;

// operator is doesn't match any case constant (+,


-, *, /)

default:

printf("Error! operator is not correct");


}

return 0;

Output

Enter an operator (+, -, *,): -

Enter two operands: 32.5

12.4

32.5 - 12.4 = 20.1

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.

Then, control of the program jumps to

printf("%.1lf / %.1lf = %.1lf",firstNumber, secondNumber,


firstNumber/firstNumber);

Finally, the break; statement ends the switch statement.

C Programming goto Statement


In this tutorial, you will learn how to create a goto statement in C
programming. Also, you will learn when to use a goto statement and when
not to use it.

The goto statement is used to alter the normal sequence of a C program.

Syntax of goto statement

goto label;

... .. ...

... .. ...

... .. ...

label:

statement;

The label is an identifier. When goto statement is encountered, control of the


program jumps to label: and starts executing the code.
Example: goto Statement

// Program to calculate the sum and average of maximum of


5 numbers

// If user enters negative number, the sum and average of


previously entered positive number is displayed

# include <stdio.h>

int main()

const int maxInput = 5;

int i;

double number, average, sum=0.0;

for(i=1; i<=maxInput; ++i)

printf("%d. Enter a number: ", i);


scanf("%lf",&number);

// If user enters negative number, flow of program


moves to label jump

if(number < 0.0)

goto jump;

sum += number; // sum = sum+number;

jump:

average=sum/(i-1);

printf("Sum = %.2f\n", sum);

printf("Average = %.2f", average);

return 0;

Output

1. Enter a number: 3

2. Enter a number: 4.3


3. Enter a number: 9.3

4. Enter a number: -2.9

Sum = 16.60

Reasons to avoid goto statement


The use of goto statement may lead to code that is buggy and hard to follow.
For example:

one:

for (i = 0; i < number; ++i)

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.

Should I or shouldn't I use goto statement?


If you think the use of goto statement simplifies your program. By all means
use it. The goal here is to create code that your fellow programmer can
understand easily.

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()

- The execution of every C program starts from this main() function.

printf()

- prinf() is used for displaying output in C.

scanf()

- scanf() is used for taking input in C.

Visit this page to learn more about library functions in C programming


language.

User defined function


C allows programmer to define their own function according to their
requirement. These types of functions are known as user-defined functions.
Suppose, a programmer wants to find factorial of a number and check
whether it is prime or not in same program. Then, he/she can create two
separate user-defined functions in that program: one for finding factorial and
other for checking whether it is prime or not.
How user-defined function works in C Programming?

#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.

Remember, the function name is an identifier and should be unique.

Advantages of 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.

/*Program to demonstrate the working of user defined


function*/

#include <stdio.h>

int add(int a, int b); //function


prototype(declaration)

int main(){

int num1,num2,sum;

printf("Enters two number to add\n");

scanf("%d %d",&num1,&num2);

sum=add(num1,num2); //function call

printf("sum=%d",sum);

return 0;

int add(int a,int b) //function declarator

/* Start of function definition. */

int add;

add=a+b;
return add; //return statement of
function

/* End of function definition. */

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.

Syntax of function prototype

return_type function_name(type(1) argument(1),....,type(n)


argument(n));

In the above example,int add(int a, int b); is a function prototype which


provides following information to the compiler:

1. name of the function is add()


2. return type of the function is int.
3. two arguments of type int are passed to function.

Function prototype are not needed if user-definition function is written


beforemain() function.
Function call
Control of the program cannot be transferred to user-defined function unless
it is called invoked.

Syntax of function call

function_name(argument(1),....argument(n));

In the above example, function call is made using


statement add(num1,num2);from main(). This make the control of program
jump from that statement to function definition and executes the codes inside
that function.

Function definition
Function definition contains programming codes to perform specific task.

Syntax of function definition

return_type function_name(type(1) argument(1),..,type(n)


argument(n))

//body of function

Function definition has two major components:


1. Function declarator
Function declarator is the first line of function definition. When a function is
called, control of the program is transferred to function declarator.

Syntax of function declarator

return_type function_name(type(1) argument(1),....,type(n)


argument(n))

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.

In above example, int add(int a,int b) in line 12 is a function declarator.

2. Function body
Function declarator is followed by body of function inside braces.

Passing arguments to functions


In programming, argument(parameter) refers to data this is passed to
function(function definition) while calling function.

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.

A function can be called with or without an argument.

Return Statement
Return statement is used for returning a value from function definition to
calling function.

Syntax of return statement

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:

"c string tutorial"

Here, "c string tutorial" is a string. When, compiler encounters strings, it


appends null character at the end of string.
Declaration of strings
Strings are declared in C in similar manner as arrays. Only difference is that,
strings are of char type.

char s[5];

Strings can also be declared using pointer.

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'};

String can also be initialized using pointers

char *c="abcd";

Reading Strings from user.


Reading words from user.

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.

Write a C program to illustrate how to read string from terminal.

#include <stdio.h>

int main(){

char name[20];
printf("Enter name: ");

scanf("%s",name);

printf("Your name is %s.",name);

return 0;

Output

Enter name: Dennis Ritchie

Your name is Dennis.

Here, program will ignore Ritchie because, scanf() function takes only string
before the white space.

Reading a line of text


C program to read line of text manually.

#include <stdio.h>

int main(){

char name[30],ch;

int i=0;

printf("Enter name: ");

while(ch!='\n') // terminates if user hit enter

{
ch=getchar();

name[i]=ch;

i++;

name[i]='\0'; // inserting null character at end

printf("Name: %s",name);

return 0;

This process to take string is tedious. There are predefined


functions gets() andputs in C language to read and display string respectively.

int main(){

char name[30];

printf("Enter name: ");

gets(name); //Function to read string from user.

printf("Name: ");

puts(name); //Function to display string.

return 0;

Both, the above program has same output below:

Output
Enter name: Tom Hanks

Name: Tom Hanks

Passing Strings to Functions


String can be passed to function in similar manner as arrays as, string is also
an array. Learn more about passing array to a function.

#include <stdio.h>

void Display(char ch[]);

int main(){

char c[50];

printf("Enter string: ");

gets(c);

Display(c); // Passing string c to function.

return 0;

void Display(char ch[]){

printf("String Output: ");

puts(ch);

Here, string c is passed from main() function to user-defined


function Display(). In function declaration, ch[] is the formal argument.
String handling functions
You can perform different type of string operations manually like: finding
length of string, concatenating(joining) two strings etc. But, for programmers
ease, many library function are defined under header file <string.h> to handle
these commonly used talk in C programming. You will learn more about
string hadling function in next chapter.

You might also like