6.module 6 1
6.module 6 1
6.module 6 1
C language Tutorial with programming approach for beginners and professionals, helps you to
understand the C language tutorial easily. Our C tutorial explains each topic with programs.
The C Language is developed for creating system applications that directly interact with the
hardware devices such as drivers, kernels, etc.
C programming is considered as the base for other programming languages, that is why it is
known as mother language.
1. Mother language
2. System programming language
3. Procedure-oriented programming language
4. Structured programming language
5. Mid-level programming language
1) C as a mother language
C language is considered as the mother language of all the modern programming languages
because most of the compilers, JVMs, Kernels, etc. are written in C language, and most of
the programming languages follow C syntax, for example, C++, Java, C#, etc.
It provides the core concepts like the array, strings, functions, file handling, etc. that are
being used in many languages like C++, Java, C#, etc.
It can't be used for internet programming like Java, .Net, PHP, etc.
3) C as a procedural language
A procedural language breaks the program into functions, data structures, etc.
In the C language, we break the program into parts using functions. It makes the program
easier to understand and modify.
A High-Level language is not specific to one machine, i.e., machine independent. It is easy
to understand.
C Program
In this tutorial, all C programs are given with C compiler so that you can quickly change the
C program code.
File: main.c
1. #include <stdio.h>
2. int main() {
3. printf("good morning");
4. return 0;
5. }
History of C Language
History of C language is interesting to know. Here we are going to discuss a brief history of the c
language.
C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T
(American Telephone & Telegraph), located in the U.S.A.
It was developed to overcome the problems of previous languages such as B, BCPL, etc.
Initially, C language was developed to be used in UNIX operating system. It inherits many
features of previous languages such as B and BCPL.
Let's see the programming languages that were developed before C language.
C is the widely used language. It provides many features that are given below.
1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10.Extensible
1) Simple
C is a simple language in the sense that it provides a structured approach (to break the problem
into parts), the rich set of library functions, data types, etc.
5) Rich Library
C provides a lot of inbuilt functions that make the development fast.
6) Memory Management
It supports the feature of dynamic memory allocation. In C language, we can free the allocated
memory at any time by calling the free() function.
7) Speed
The compilation and execution time of C language is fast since there are lesser inbuilt functions
and hence the lesser overhead.
8) Pointer
C provides the feature of pointers. We can directly interact with the memory by using the
pointers. We can use pointers for memory, structures, functions, array, etc.
9) Recursion
In C, we can call the function within the function. It provides code reusability for every function.
Recursion enables us to use the approach of backtracking.
10) Extensible
C language is extensible because it can easily adopt new features.
C Language Introduction
printf("%d", a);
.
.
5. Return Statement: The last part in any C program is the return statement. The
return statement refers to the returning of the values from a function. This return
statement and return value depend upon the return type of the function. For
example, if the return type is void, then there will be no return statement. In any
other case, there will be a return statement and the return value will be of the type
of the specified return type.
Example:
int main()
{
int a;
printf("%d", a);
return 0;
}
2. Writing first program:
Following is first program in C
#include <stdio.h>
int main(void)
{
printf("hello");
return 0;
}
Let us analyze the program line by line.
Line 1: [ #include <stdio.h> ] In a C program, all lines that start with # are processed
by preprocessor which is a program invoked by the compiler. In a very basic
term, preprocessor takes a C program and produces another C program. The produced
program has no lines starting with #, all such lines are processed by the preprocessor. In the
above example, preprocessor copies the preprocessed code of stdio.h to our file. The .h files
are called header files in C. These header files generally contain declaration of functions. We
need stdio.h for the function printf() used in the program.
Line 2 [ int main(void) ] There must to be starting point from where execution of compiled C
program begins. In C, the execution typically begins with first line of main(). The void written
in brackets indicates that the main doesn’t take any parameter (See this for more details).
main() can be written to take parameters also. We will be covering that in future posts.
The int written before main indicates return type of main(). The value returned by main
indicates status of program termination. See this post for more details on return type.
Line 3 and 6: [ { and } ] In C language, a pair of curly brackets define a scope and mainly used
in functions and control statements like if, else, loops. All functions must start and end with
curly brackets.
Line 5 [ return 0; ] The return statement returns the value from main(). The returned value
may be used by operating system to know termination status of your program. The value 0
typically means successful termination.
Linux: For Linux, gcc comes bundled with the linux, Code Blocks can also be used with Linux.
Flow of C Program
File: simple.c
1. #include <stdio.h>
2. int main(){
3. printf("Hello C Language");
4. return 0;
5. }
Execution Flow
Let's try to understand the flow of above program by the figure given below.
2) Expanded source code is sent to compiler which compiles the code and converts it into
assembly code.
3) The assembly code is sent to assembler which assembles the code and converts it into
object code. Now a simple.obj file is generated.
4) The object code is sent to linker which links it to the library such as header files. Then it
is converted into executable code. A simple.exe file is generated.
5) The executable code is sent to loader which loads it into memory and then it is executed.
After execution, output is sent to console.
Constants in C
A constant is a value or variable that can't be changed in the program, for example: 10, 20,
'a', 3.4, "c programming" etc.
List of Constants in C
Constant Example
1. const keyword
2. #define preprocessor
1) C const keyword
1. #include<stdio.h>
2. int main(){
3. const float PI=3.14;
4. printf("The value of PI is: %f",PI);
5. return 0;
6. }
Output:
The value of PI is: 3.140000
If you try to change the the value of PI, it will render compile time error.
1. #include<stdio.h>
2. int main(){
3. const float PI=3.14;
4. PI=4.5;
5. printf("The value of PI is: %f",PI);
6. return 0;
7. }
2) C #define preprocessor
Constants are like a variable, except that their value never changes during execution once
defined.
C Constants
C Constants is the most fundamental and essential part of the C programming language.
Constants in C are the fixed values that are used in a program, and its value remains the same
during the entire execution of the program.
2. Constant Types in C
3. Integer Constant
4. Real constant
6. String Constants
Example:
#include<stdio.h>
main()
int area;
area = SIDE*SIDE;
, SIDE, area);
Program Output:
or
Primary Constants
1. Numeric Constants
o Integer Constants
o Real Constants
2. Character Constants
o Single Character Constants
o String Constants
o Backslash Character Constants
Integer Constant
1. Decimal Integer
2. Octal Integer
3. Hexadecimal Integer
Example:
15, -265, 0, 99818, +25, 045, 0X6
Real constant
The numbers containing fractional parts like 99.25 are called real or floating points constant.
It simply contains a single character enclosed within ' and ' (a pair of single quote). It is to be
noted that the character '8' is not the same as 8. Character constants have a specific set of
integer values known as ASCII values (American Standard Code for Information Interchange).
Example:
These are a sequence of characters enclosed in double quotes, and they may include letters,
digits, special characters, and blank spaces. It is again to be noted that "G" and 'G' are
different - because "G" represents a string as it is enclosed within a pair of double quotes
whereas 'G' represents a single character.
Example:
C supports some character constants having a backslash in front of it. The lists of backslash
characters have a specific meaning which is known to the compiler. They are also termed as
"Escape Sequence".
For Example:
Constants Meaning
\a beep sound
\b backspace
\f form feed
\n new line
\r carriage return
\t horizontal tab
\v vertical tab
\\ backslash
\0 null
Secondary Constant
Array
Pointer
Structure
Union
Enum
C - Constants and Literals
Constants refer to fixed values that the program may not alter during its execution. These
fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant,
a character constant, or a string literal. There are enumeration constants as well.
Constants are treated just like regular variables except that their values cannot be modified
after their definition.
Integer Literals
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base
or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and
long, respectively. The suffix can be uppercase or lowercase and can be in any order.
Here are some examples of integer literals −
212 /* Legal */
215u /* Legal */
0xFeeL /* Legal */
078 /* Illegal: 8 is not an octal digit */
032UU /* Illegal: cannot repeat a suffix */
Following are other examples of various types of integer literals −
85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */
Floating-point Literals
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent
part. You can represent floating point literals either in decimal form or exponential form.
While representing decimal form, you must include the decimal point, the exponent, or both;
and while representing exponential form, you must include the integer part, the fractional
part, or both. The signed exponent is introduced by e or E.
Here are some examples of floating-point literals −
3.14159 /* Legal */
314159E-5L /* Legal */
510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent */
.e55 /* Illegal: missing integer or fraction */
Character Constants
Character literals are enclosed in single quotes, e.g., 'x' can be stored in a simple variable
of char type.
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a
universal character (e.g., '\u02C0').
There are certain characters in C that represent special meaning when preceded by a
backslash for example, newline (\n) or tab (\t).
Following is the example to show a few escape sequence characters −
#include <stdio.h>
int main() {
printf("Hello\tWorld\n\n");
return 0;
}
When the above code is compiled and executed, it produces the following result −
Hello World
String Literals
String literals or constants are enclosed in double quotes "". A string contains characters that
are similar to character literals: plain characters, escape sequences, and universal characters.
You can break a long line into multiple lines using string literals and separating them using
white spaces.
Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"
"hello, \
dear"
Defining Constants
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main() {
int area;
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of area : 50
You can use const prefix to declare constants with a specific type as follows −
const type variable = value;
The following example explains it in detail −
#include <stdio.h>
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of area : 50
Note that it is a good programming practice to define constants in CAPITALS.
Variables in C
Table of Contents
1. Variable Definition in C
3. Variable Assignment
Variable Definition in C
Syntax:
type variable_name;
or
char letter='A';
double d;
age = 26.5;
Variable Assignment
Variable assignment is a process of assigning a value to a variable.
Example:
A variable name can consist of Capital letters A-Z, lowercase letters a-z, digits 0-9, and the
underscore character.
The first character must be a letter or underscore.
Blank spaces cannot be used in variable names.
Special characters like #, $ are not allowed.
C keywords cannot be used as variable names.
Variable names are case sensitive.
Values of the variables can be numeric or alphabetic.
Variable type can be char, int, float, double or void.
#include<stdio.h>
void main()
Program Output:
I am 5 years old.
Data Types in C
A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.
The basic data types are integer-based and floating-point based. C language supports both
signed and unsigned literals.
The memory size of the basic data types may change according to 32 or 64-bit operating
system.
Let's see the basic data types. Its size is given according to 32-bit architecture.
Data Types Memory Size Range
double 8 byte
Basic types
Here's a table containing commonly used types in C programming for quick access.
char 1 %c
float 4 %f
double 8 %lf
signed char 1 %c
unsigned char 1 %c
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;
The size of int is usually 4 bytes (32 bits). And, it can take 232 distinct states from -
2147483648 to 2147483647.
float and double
float salary;
double price;
char
Keyword char is used for declaring character type variables. For example,
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;
You can always check the size of a variable using the sizeof() operator.
#include <stdio.h>
int main() {
short a;
long b;
long long c;
long double d;
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.
bool Type
Enumerated type
Complex types
Data types that are derived from fundamental data types are derived types. For example:
arrays, pointers, function types, structures, etc.
C Identifiers
Identifiers are names given to different names given to entities such as constants, variables,
structures, functions etc.
Example:
int amount;
double totalbalance;
In the above example, amount and totalbalance are identifiers and int, and double are
keywords.
An identifier can only have alphanumeric characters (a-z , A-Z , 0-9) (i.e. letters & digits) and
underscore( _ ) symbol.
Identifier names must be unique
The first character must be an alphabet or underscore.
You cannot use a keyword as identifiers.
Only first thirty-one (31) characters are significant.
Must not contain white spaces.
Identifiers are case-sensitive.
C Operators
An operator is simply a symbol that is used to perform operations. There can be many types
of operations like arithmetic, logical, bitwise, etc.
There are following types of operators to perform different types of operations in C language.
o Arithmetic Operators
o Relational Operators
o Shift Operators 0110
o Logical Operators
o Bitwise Operators
o Ternary or Conditional Operators
o Assignment Operator
o Misc Operator
Precedence of Operators in C
The precedence of operator species that which operator will be evaluated first and next. The
associativity specifies the operator direction to be evaluated; it may be left to right or right to
left.
The value variable will contain 210 because * (multiplicative operator) is evaluated before +
(additive operator).
Additive +- Left to
right
Equality == != Left to
right
Bitwise OR | Left to
right
Logical AND && Left to
right
Logical OR || Left to
right
Conditional ?: Right to
left
Comma , Left to
right
Arithmetic Operators
Arithmetic Operators are used to performing mathematical calculations like addition (+),
subtraction (-), multiplication (*), division (/) and modulus (%).
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
C Program to Add Two Numbers
Example:
#include <stdio.h>
void main()
Program Output:
i--
Operator Description
++ Increment
−− Decrement
Example: To Demonstrate prefix and postfix modes.
void main()
printf("\n%d %d",a--,--b);
printf("\n%d %d",a--,--b);
printf("\n%d %d",a--,--b);
printf("\n%d %d",a--,--b);
printf("\n%d %d",a--,--b);
Program Output:
54
43
32
21
10
Relational Operators
Relational operators are used to comparing two quantities or values.
Operato Description
r
== Is equal to
!= Is not equal to
Logical Operators
C provides three logical operators when we test more than one condition to make decisions.
These are: && (meaning logical AND), || (meaning logical OR) and ! (meaning logical NOT).
Operator Description
&& And operator. It performs logical conjunction of two expressions. (if both
expressions evaluate to True, result is True. If either expression evaluates to
False, the result is False)
Operator Description
| Binary OR Operator
Assignment Operators
Assignment operators applied to assign the result of an expression to a variable. C has a
collection of shorthand assignment operators.
Operato Description
r
= Assign
Conditional Operator
C offers a ternary operator which is the conditional operator (?: in combination) to construct
conditional expressions.
Operato Description
r
?: Conditional Expression
Special Operators
C supports some special operators
Operato Description
r
* Pointer to a variable.
#include <stdio.h>
void main()
int i=10; /* Variables Defining and Assign values */ printf("integer: %d\n", sizeof(i));
Program Output:
The compiler converts all operands into the data type of the largest operand. A+B
The sequence of rules that are applied while evaluating expressions are given below:
1. If either of the operand is of type long double, then others will be converted to long double
and result will be long double.
2. Else, if either of the operand is double, then others are converted to double.
3. Else, if either of the operand is float, then others are converted to float.
4. Else, if either of the operand is unsigned long int, then others will be converted to unsigned
long int.
5. Else, if one of the operand is long int, and the other is unsigned int, then
1. if a long int can represent all values of an unsigned int, the unsigned int is converted to
long int.
2. otherwise, both operands are converted to unsigned long int.
6. Else, if either operand is long int then other will be converted to long int.
7. Else, if either operand is unsigned int then others will be converted to unsigned int.
It should be noted that the final result of expression is converted to type of variable on left
side of assignment operator before assigning value to it.
Also, conversion of float to int causes truncation of fractional part, conversion of double to
float causes rounding of digits and the conversion of long int to int causes dropping of excess
higher order bits. 0 1
The type conversion performed by the programmer by posing the data type of the expression
of specific type is known as explicit type conversion.
(data_type)expression;
where, data_type is any valid c data type, and expression may be constant, variable or
expression.
For example,
x=(int)a+b*d;
The following rules have to be followed while converting the expression from one type to
another to avoid the loss of information:
1. All integer types to be converted to float.
2. All float types to be converted to double.
3. All character types to be converted to integer.
int main()
{
double x = 1.2;
return 0;
Output:
sum = 2
Type Casting
Type Casting in C is used to convert a variable from one data type to another data type, and
after type casting compiler treats the variable as of the new data type.
Syntax:
(type_name) expression
#include <stdio.h>
main ()
int a;
a = 15/6;
printf("%d",a);
Program Output:
main ()
float a;
a = (float) 15/6;
printf("%f",a);
Program Output:
After type cast is done before division to retain float value 2.500000.
Stdio.h
Step 1: enter two nos a and b
Step4: end
Set sum=a+b
Print sum
end
start
Sum=a+b
Print sum
end
READ number
remainder=number%2
IF remainder==0
WRITE "Even Number"
ELSE
WRITE "Odd Number"
ENDIF
algorithm
Step 1: Start
Else
Print : N is an Odd Number.
Step 4: Exit
1. #include <stdio.h>
2. int main()
3. {
4. int number;
5.
6. printf("Enter an integer: ");
7. scanf("%d", &number);
8.
9. // True if the number is perfectly divisible by 2
10. if(number % 2 == 0)
11. printf("%d is even.", number);
12. else
13. printf("%d is odd.", number);
14.
15. return 0;
16. }
Output
1. Enter an integer: -7
2. -7 is odd.
Step 1 : Input a number N
Step 2 : if (N%2==0)
Step 4 : else
Step 6: Exit
5.1K views
View 3 upvotes
Shubham Thakur
number is even
else
number is odd
end
4.2K views
View 2 upvotes
Add Comment
Sahil Gupta
I am not a coder so i can not tell you the syntax but i can tell you the logic.
E=2*K
O=2*K+1 OR 2*K-1
FOR ANY INTEGER VALUE OF “K” YOU WILL GET EVEN OR ODD RESPECTIVELY USING
ABOVE EQUATIONS.
15.8K views
View 3 upvotes
3
Add Comment
Vladimir Udod
, Master Computer Science, Moscow Institute of Telecommunications and Computer Science (1999)
It is very simple and uses property of even (odd) numbers to be or not to be divisible by 2. There are several
ways to check, if a number can divided by 2 without a reminder.
View 1 upvote
· Answer requested by
Victor Gutierrez-Diaz
1
Add Comment
Related Questions
How do you write an algorithm and flowchart to print odd numbers up to 100?
How can I write an algorithm to check whether an entered number is odd or even?
What is the algorithm to find out if the given number is odd or even?
What is the algorithm to find how many odd and even numbers there are from 1 to 100?
Ask question