
The C programming language is one of the foundation or base-language of many programming languages today. Dennis Ritchie developed the C language and it has known as the mother of programming languages. The invention of the C language made the usage of languages like COBOL, PASCAL, and FORTRAN are obsolete.
The C language is still in use today. The C language is very robust and it could be used to implement many programs, software, and applications. Any person who is interested in learning programming should first make sure that he/she has a strong basic background in C programming language. A person who masters the varied aspects of the C programming language can master any other programming language with relative ease.
Prior to the year 1969, the programmers had to use Assembly Programming language which is a hardware-specific language. In the early day's computer code used to write in assembly code. To perform a specific task, you had to write many pages of code.
The drawback of this language was, it was very difficult to code a program, as we need to pass in the address locations, store bits for each program. It means the programmer needs to have a profound knowledge of hardware then only he/she was able to code a program in assembly language.
To overcome this difficulty, Ken Thompson developed the language ‘B’ in 1969-70. Which is easy to use and has the power and efficiency of assembly programming language.
A high-level language like 'B' made it possible to write the same task in just a few lines of code. The developers started making use of ‘B’ programming language for further development of the UNIX system. B language could produce code much faster than in assembly language.
A drawback of the B language was that it did not know data-types. Another functionality that the B language did not provide was the use of structures. Therefore, in 1971-73, Dennis M. Ritchie turned the B language into the C language, keeping most of the language B syntax while adding data-types and many other changes.
The C language had a powerful mix of high-level functionality and the detailed features required to program an operating system.
In the programming world, a programming language can be broadly classified on three different categories namely:
Low level programming language
Middle level programming language
High level programming language
Low level programming language: The languages which can directly interact with hardware or we can consider them as "native language" of the computer.
For example Machine language, Assembly language, etc.
The languages which are closest to the hardware itself is termed as Low-level programming language.
Middle level programming language: C language is often called as a middle-level programming language. This does not mean that C is less powerful, harder to use, or less developed than a high-level language such as BASIC or Pascal, nor does it imply that C has the cumbersome nature of assembly language. As middle – level language, C allows the manipulation of bits, bytes, and addresses.
High level programming language: languages which are near to human language or written in English-like words and makes it easier for programmers to think and understand a program code is considered as a high-level programming language.
For example: Java, C#, Python, etc.
A high-level language also requires a translation to machine language before execution, as the computer only understands Machine level language i.e. "0" and "1" binary digits format.
A compiler translates a high-level language to low-level language because the computer is not capable of understanding a high-level code program that is not covered in a binary format and thus only understands the hardware-specific language like Machine level language in general.
Following areas where C is used for:
Operating systems
Embedded system application
Website CGI
Application software
Operating systems: The reason C is used under the Operating system because being a middle-level programming language, provides high-level constructs while still providing low-level details that are closer to Assembly language, and hence, C programming language is perfect for coding Operating systems. Because of this, using C language is fairly easy in OS development.
Embedded system application: In order to code Embedded system applications and drivers we need to communicate with the hardware, it is very easy to code using C programming language and we can also access the hardware location, hence C is heavily used in Embedded system applications.
Website CGI: We could make use of C for developing website programming using CGI as a "gateway" for information between the Web application, the server, and the browser. Reasons for choosing C language over interpreted languages are its speed, stability, and near-universal availability.
Application software: As the name suggests, Application software is a program or a group of programs designed for end-users or programmers in general. A c programming language is also used to code application software, like a word processor, a media player, simulators, etc.
In C programming language, all 26 letters from the English language, digits in the number system, and special symbols on a standard keyboard are valid. However, in order to code a program in the C programming language, we need to follow some rules and syntax. Let us compare the hierarchy of English language and C programming language first.
If we check with English, we have Alphabets and digits using which we make words and numbers, and using these words and numbers we make sentences and a group of sentences defines a meaningful context in English is a paragraph. Similarly, we can describe C programming also.
If we compare English with C language, we have Alphabets and digits whereas, in C, we also have Alphabets, digits, and Special characters (for e.g: If we want to add, subtract, divide, multiply any operation we can use special characters in C ). In case of words and numbers, we have constants(fixed value not changeable), Variables(created using alphabets, numbers and underscore symbol) and Keywords(specific reserved words in C).
In a similar fashion sentences, statements, and instructions are used to describe a command in C. At last for paragraphs, a program is a collection of instructions that can be executed by a computer to perform specific tasks which include process an input, manipulate data, and provide an output result.
A constant is a non-varying value, i.e. a value completely fixed or fixed in the context of use. The term usually occurs in opposition to the variable, which is a symbol that stands for a value that may vary.
The C constant
In C programming language the constants are categorized into two major categories namely primary and secondary constants. These categories are then further categorized.
Integer Constant
Numeric entity
At least one digit and Decimal point is not allowed
Example: 231,-554, 0
Note: The range of an integer constant varies upon the compiler. For a 16-bit compiler like Turbo C, Turbo C++ the range is -32768 to 32767 whereas range in 32-bit compiler likes Dev C++, VC++ the range of integer constant will be much higher.
Real constant
Real constant also known as a floating-point variable, we could write these in two forms:
1. Fractional or Normal form
2. Exponential or Scientific form
Fractional or Normal form
This is the normal form of representation of a floating-point number, where the number represented by making use of decimal point and it mandatory to make use of decimal point in real constant.
Examples: 3.14, -5.75, 0.0, 87.5, 8.0
Exponential or Scientific form
The Exponential or Scientific representation is done in two parts, the part before ‘e’ is called as a mantissa and the part after ‘e’ is the exponent.
Alphanumeric entity
Must have a decimal point
It can have positive, negative, or zero value
Examples: 3.56e4, -2.6e6, -0.4e7
Character constant
A character constant is a single length entity; this entity could be an alphabet, a digit, or a symbol. A character constant should be with single quotes.
The length should be one.
A single quote point to the left should be used.
Example: ‘a’, ’*’, ’1’
C variables
As we have already seen, that the value of the variable could change. Variable is a name to a memory location where we store the constant, in fact, variables are like a container for a constant. At some time, we can store a constant and we may store a different constant in the same container at some other time.
The same type of constant can be stored on a variable; means in an integer variable we can store an integer constant only.
Types of variables and constants are always the same, as variables are the container for constants so they go hand in hand.
Rules for creating variable names
Can be a combination of alphabets, digits, and underscore
Should start from the alphabet
No comma, space, or any other special symbol except underscore is allowed
The variable names are case sensitive
Keywords cannot be used as a variable name
Example: A, StudyEasy, Study_Easy,studyeasy,a123,a11_a1m
Keywords are words whose meaning is already been explained to the compiler, we can make use of these words in our program according to our need, and we cannot use these keywords as a variable.
Keywords are also known as reserved words and in C programming language there are 32 keywords.
Usage of these keywords:
auto, signed, constant, extern, register, unsigned: used to define a variable.
break: used to terminate the statement immediately.
continue: skips the rest of the statements of current iteration by performing the next iteration of the loop.
goto: used to transfer control of the program to the specified label.
switch, case, and default: used when a block of statements to be executed among many blocks.
int, float, char, double, long: datatypes used in variable declaration.
for, while, do-while: types of loop structures in C.
enum: a set of constants.
char: used to declare a variable as a character type.
sizeof: to know the size of data(a variable or a constant)
return: terminates the function and returns the value.
void: returns nothing or no value.
struct: used to declare a structure.
typedef: used to explicitly associate a type with an identifier.
union: a collection of different types of variables under a single name.
volatile: objects that can be modified in an unspecified way by the hardware.
Let's see a very simple and famous program Hello world.
In this program we have:
comments section: comments are just to add further detailing in our program. It is ignored by the compiler during execution.
header file: If we want to print output for our program it is necessary to include the header files. If we skip the header file in our program we won't be able to use the "printf" statement to print output.
main(): entry point or where the execution of our program begins.
printf: to print output on the console.
This program is the first step to code in C language.
Whenever a programmer starts coding a program, the code is for the machine but even the programmers should be able to understand the code easily. So in order to make the code easy to understand for programmers and others there are some best practices.
Best practices while coding a program
Comments are important
Comments involve placing Human-readable descriptions inside of computer programs, detailing what the code is doing. Proper use of commenting can make code maintenance much easier, as well as helps in finding bugs faster. Further, commenting is very important when writing functions that other people will use. Remember, a well-documented code is as important as correctly working code.
Note: Always try to finish your comment in a few words as possible; one-liner comment is best until its explaining.
Comment in C programming language
In the C Programming Language, you can place comments in our code, Comments are ignored be by the compiler and do not get executed as part of the program. A comment can be anywhere in your program. Comments can span several lines within your C program.
Multi-line comment
Syntax: /* comment goes here */
Single-line comment
Syntax: // comment goes here
2.Why?
Always write why you are writing this piece of code because this information is not visible until you write them in the comments and this is critical to identify. Also is good practice to write the date when you started coding the program and the name of the coder.
3.Naming conventions
Naming conventions are a set of ‘standards’ defining what case is used when naming elements of your code. It is practiced to keep your code consistent, making it easier to follow and understand. The two cases used most often, Pascal case and the Camel case.
Pascal case: StudyEasy
Camel case: studyEasy
Recommendation:
Variable name: use camel case
Function name: use pascal case
Note: Make use of a meaningful name for your function name and variable name.
4.Indentation
An indent style is a convention governing the indentation of blocks of code to convey the program's structure
To start with we shall learn the basics of the C program.
Header
A header file is a file with extension ‘.h’. In order to use a header file in a program, we need to include it. The C pre-processing directive #include is used to include the header file. We have seen the inclusion of stdio.h header file, which comes along with your compiler.
Note: we must include specific headers to make use of specific functions and macros.
printf and scanf
printf stands for print formatted and likewise,scanf stands for scan formatted, these are standard function for console input and output respectively. These functions are defined under the header file in C programming, in order to use the functions we must include a header in the program.
Note: In order to receive an input using scanf, we need to use & address of the operator.
Statement terminators
In C programming, we have statements and instructions. In the same way, we have a sentence in English. Now when we see a full stop in English, it means that sentence has ended. Likewise, in order to make the compiler understand that statement has ended, we have statement terminators. In C programming language the statement terminator is semi-colon;
Data types
We have seen that variables are like a container for constants, whereas ‘Data type’ is nothing but the type of data the variable contains. In C programming the type of data that can be stored in the variable needs to be declared when we define the variable in the code of the program.
In a one-liner, whenever we declare a variable name, we must tell the compiler that what will be the data type of the variable.
Types of data type
Basic Types
They are arithmetic types and consists of two types:
Integer
Floating-point
2. Enumerated types
They are arithmetic types and they used to define variables that could only be assigned certain discrete integer values throughout the program.
3. The type void
The type specifies ‘void’ indicates that no value is available.
4. Derived types
They include:
Pointer types
Array types
Structure types
Union types
Function types.
At this point, we will see the details of the basic data type and void data type. We will see the details of enumerated types and derived types in forthcoming chapters.
Basic types:
Integer type: Used to store numbers without a decimal point. It is further categorized as a signed and unsigned type.
Signed and unsigned: ‘Signed` means that the value can be negative, positive or zero, whereas unsigned means that the value will be only positive or zero. It applies that we will not use the sign at the prefix of the number, and as we knew the default is positive, the number will be positive or zero.
2. Floating type: Used to store numbers with a decimal point.
Format specifier
The ‘printf()’ function is a standard output function which is by default present in the standard library for C compiler to use.
Whenever we want to print some output to the console, we need to tell the ‘printf()’ function that which type of data is present on the variable and the format in which we want to print it, in order to do this we need the help of format specifier.
Example: %d -> used for a decimal integer.
%s -> used for a string.
Escape sequence
When we are programming in the C language, sometimes you need to refer to a keypress instead of printing a character on the screen. For example, we need to use a new line character so that the text could be displayed on the next line, all this kind of operation is done by making use of an escape sequence.
Example: \n -> for new line in our program.
\t -> used to provide tab(intendation) in our program.
Program structure in C
We can say that a program is categorized on four different chunks which are essential for making a program structure a meaningful one. In general, a Program structure of C includes:
Preprocessor command: using preprocessor commands we include the header files in our program. This is the first step we do, while we code a program.
Example: #include<stdio.h>, #include<math.h>, etc.
Note: A header file is a file with extension ‘.h’.
A header file is very important because it is used for the declaration of functions, structure, union, any other data type or extern variable. Whichever source file includes a header file, that source file can access all declaration and definition present in that header file.
Functions: A main() function is the entry point where the program logic goes within. When a C program is executed, the execution control is pointed towards directly to the main() function. Every program in C has a main() function.
Variable declaration: In C programming, as we have seen in the general structure of the C program, the variable needs to be declared at the beginning of the function definition. There are few variations in how we can declare a variable in the programming language. We can declare and define the variable at the same time or we can first declare and define the variable later, both ways are valid. We need to choose the way according to the need.
Note: It is not mandated to declare a variable inside a function always, we can also declare a variable before main()function in C.
Statements and expression: This includes the actual logic of the program. In this part, we include the printf() to get an output result on the console, and scanf() function is commonly used to take input from the user. This function is used to read character, string, and numeric data from the keyboard.
Inter-changing of values in the variable
In the world of programming, inter-changing of the value’s in “variable” is a common operation. Now we want to code a program to make the value to X as 5 and the value to Y as 23. How to do this, let’s check that.
Step 1: Copy the value of X to a temp variable
Now the value of X is stored in a temp variable.
Step 2: Over-write X with the value of Y
Copy the value of Y to X variable and X value has become 23, also we have the value of X in temp variable i.e. 5
Step3: Copy the value of temp to Y
Now, the value of both variables is inter-changed i.e. X=23 and Y=5 and we are done!
So this is how we inter-change values of the variable in C.
Decision making in C
Decision making is about deciding the order of execution of code in the program depending upon the condition. In C programming decision-making is done by the following mechanism.
if statement
Conditional operator
Switch statement
Goto statement
if statement: An if statement contains a Boolean expression followed by one or more statements. In C programming, assume any non-zero and non-null values as true and if it is either zero or null then it is assumed as false value.
Syntax:
if(Boolean_expression) //never use semi-colon here.
{
/*Instruction(s) will execute if the Boolean expression is true */
}
Types of decision making using if statement
if statement: An if statement contains a Boolean expression followed by one or more statements.
if...else statement: An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
nested if statements: we can use one if or else if statement inside another if statement or else if statement(s).
2. Conditional operator: A conditional operator is one of the operators which is used in the decision-making process that depends upon the output of the expression. It is also known as a ternary operator.
Syntax: Expression1? Expression2: Expression3;
3. Switch statement: The statements which are used to execute only a specific block of code in a given series of the block of code are called case-control structure. This structure is known as decision making using switch case.
Syntax:
switch (integer expression)
{
case label1:
statements;
break;
case label2:
statements;
break;
default:
statements;
break;
}
Note: The default case is optional.
4. Goto statement: A goto statement provides an unconditional jump to a specified label in our program. In C, a goto statement can be used to jump from anywhere within the function.
Syntax: goto label;
.....
.....
label: statement;
Here label is an identifier and when goto statement is encountered in our program, the control of the program jumps to label and starts the execution of code.
Relational Operator
Relational Operator is one of the types of operators used for decision making in C. It checks the relationship between the two operands. Applying this relational operator the result will be a boolean value i.e. either true means the value will be '1' or false means the value will be '0' because it is represented in bits. Let's assume we have two operands a and b.
Given: a=5 and b=10
Operator (==) -> Checks if the value of two operands is equal or not, if yes then the condition becomes true.
a==b
Example: 5==10 is evaluated to 0, which means the condition is false.
Operator (!=) -> Checks if the value of two operands is equal or not, if values are not equal then the condition becomes true.
a != b
Example: 5 != 10 is evaluated to 1, which means the condition is true.
Operator (<) -> Checks if the value of the left operand is less than the right operand value, if yes then the condition becomes true.
a < b
Example: 5 < 10 is evaluated to 1, which means the condition is true.
Operator (>) -> Checks if the value of the left operand is greater than the right operand value, if yes then the condition becomes true.
a > b
Example: 5 > 10 is evaluated to 0, which means the condition is false.
Operator (>) -> Checks if the value of the left operand is greater than the right operand value, if yes then the condition becomes true.
a > b
Example: 5 > 10 is evaluated to 0, which means the condition is false.
Operator (>=) -> Checks if the value of the left operand is greater than or equal to the right operand value, if yes then the condition becomes true.
a >= b
Example: 5 >= 10 is evaluated to 0, which means the condition is false.
Operator (<=) -> Checks if the value of the left operand is less than or equal to the right operand value, if yes then the condition becomes true.
a <= b
Example: 5 <= 10 is evaluated to 1, which means the condition is true.
Miscellaneous operators
Operator (?:) -> Conditional Expression (also an alternative for if-else condition). It is a ternary operator(means operator operates on three operands)
Example: If Condition is true? Then value X: Otherwise, the value is Y
Operator (sizeof()) -> Returns the size of a variable.
Example: sizeof(a), where a is an integer, will return 4 (means 4 bytes of memory is been allocated for that particular value).
Operator (&) -> Returns the address of a variable.
Example: &a will give the actual address of the variable.
Operator (*) -> Pointer to a variable.
Example: *a will point to a variable.
Logical Operator
Assume variable A holds 10 and variable B holds 4 then.
Operator (&&) ->Called Logical AND operator. If both the operands are non-zero then the condition becomes true.
Example: (A==10) && (B<6)
Here both the conditions are true, therefore the result of the logical expression value is 1.
Operator (||) ->Called Logical OR Operator. If any of the two operands is non-zero then the condition becomes true.
Example: (A==10) || (B>6)
Here one of the conditions is true, A==10 which is true, but B holds value as 4, so condition B>6 which is false.
Operator (!) -> Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then the Logical NOT operator will make false.
Example: !(A==10)
Here A which holds a value as 10 will be changed to some other value other than 10.
In C, operators are used to perform different kinds of operations on variables. In C language, there is a variety of operators used to perform logical or arithmetic operations. Out of which we will be taking a simple program example to demonstrate logical operators in C.
We will first initialize two variables a, b, where a = 5 and b=6 respectively.
e.g: int a=5, b=6;
After that, we will check about the Logical AND(&&) operator using a conditional statement.
e.g: if(a <= 5 && b>2){ //If the both the operands satisfies the condition then it will be true.
printf("true");
If one of the operands does not satisfy the condition it will print false as result.
e.g: esle{
printf("false");
Now, let us take another example of logical operator(!) for the same program.Here the value of a is 5
e.g: if (!a) //means if a is not true i.e. false would be displayed as an output.
Another example to demonstrate operations in logical operators.
First, we will declare a variable percentage
e.g. int percentage; //name of the variable of integer type
Then we will ask the user to provide input with the help of printf() and store the variable in scanf() function.
e.g. printf("Enter the percentage:"); //to feed user's input
scanf("%d",&percentage); ///to store address of variable
Now we will check that variable percentage falls under which category using the conditional statement, if-else
The percentage criteria ranges would be, more than or equal to 60%, between 45 to 59%, between 35 to 44%, below 35%
We will use a conditional statement for each of these scenarios and define the conditionals based on relational and logical operators here.
e.g. if(percentage >= 60) //to describe the percentage is greater than or equal to 60%
if(percentage >= 45 && percentage < 60) //means percentage is between 45 to 59% and Logical AND is used when both the conditions would be true
if(percentage >= 35 && percentage < 45) //means percentage is between 35 to 44%
If the percentage falls below 35% then the condition will execute the else part and will print fail as output
e.g. else{
printf("fail");
Note: In the above program statements for any condition we should be able to run only the required block of code, not all the conditions, and will remove the Logical AND(&&) to make the program easier to understand.
To do so we can add else part in every if condition and it execute the expected result and will consume less time to check other conditions.
This is how Operators could be used to perform specific tasks in C.
Arithmetic Operators
In C programming language if we want to do any mathematical operations we make use of Arithmetic Operators.
Assume variable A holds 5 and variable B holds 10 then.
Operator (+) -> Adds two operands
Example: A + B will give 15 (5+10=15)
Operator (-) -> Subtracts the second operand from the first
Example: A - B will give -5 (5-10=-5)
Operator (*) -> Multiply both operands
Example: A * B will give 50 (5*10=50)
Operator (/) -> Divide numerator by de-numerator
Example: B / A will give 2 (10/5=2)
Operator (%) -> Modulus Operator gives the remainder of an integer division
Example: B % A will give 0
Operator (++) -> Increment operator increases integer value by one
Example: A++ will give 6
Operator (--) -> Decrement operator decreases integer value by one
Example: A-- will give 4
Modulus Operator
It is an arithmetic operator that is denoted by a percentage(%) symbol and gives the remainder after division. For example, if we divide two integer numbers we will have the following expression as:
A/B = Q Remainder R
Where,
A -> is the dividend
B -> is the divisor
Q -> is the quotient
R -> is the remainder
If the numerator is smaller than the denominator, then the remainder is equal to the numerator.
e.g. 10 % 3 =1
3 % 10 =3 //If smaller number i.e. 3 is divided by bigger number i.e. 10, then the numerator becomes the remainder.
Modulus operators always work with integer numbers instead of float numbers. In order to find the remainder, we make use of the modulus operator(%) and is written in the form: A mod B = R
Example: 17 % 3 = 2 //It gives us remainder as 2 because when we divide 17 by 3 then we get 5 as quotient and remainder as 2.
Note: There is a significant between a modulus and division i.e. in modulus the remainder part is the expected result, whereas in division we consider the quotient as the answer.
goto
goto statement could be used for altering the normal sequence of program execution by transferring control to some other part of the program.
Syntax:
ControlComesHere:
......................................
......................................
......................................
goto label;
statement;
In this syntax, “ControlComesHere” is an identifier. When the control of the program reaches to goto statement, the control of the program will jump to the label: ControlComesHere and executes the code below it.
Though goto statement is included in the ANSI standard of C, the use of goto statements should be reduced as much as possible in a program.
Reasons to avoid goto statement
using goto statement makes the logic of the program become complex and tangled. In modern programming, goto statement is considered a harmful construct and bad programming practice.
Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation. Assume if A = 6; and B = 4; now in the binary format they will be as follows:
A = 0110
B = 0100
-----------------
A&B = 0100
A|B = 0110
A^B = 0010
~A = 1001
Operator (&) -> Bitwise AND Operator copy a bit to the result if it exists in both operands.
Example: (A & B) will give 4 which is 0100
Operator (|) ->Bitwise OR Operator copies a bit if it exists in either operand.
Example: (A | B) will give 6 which is 0110
Operator (^) -> Bitwise XOR Operator copies the bit if it is set in one operand but not both.
Example: (A ^ B) will give 2 which is 0010
Operator (~) -> Bitwise One’s Complement Operator is unary and has the effect of 'flipping' bits.
Example: (~A) will give 1001
Operator (<<) -> Bitwise Left Shift Operator. The left operand's value is moved left by the number of bits specified by the right operand.
Example: A << 2 will give 24 which is 0001 1000
Operator (>>) -> Bitwise Right Shift Operator. The left operand's value is moved right by the number of bits specified by the right operand.
Example: A >> 2 will give 1 which is 0001
Assignment Operators
An assignment operator is an operator that is used for assigning a value to a variable. This operator is denoted by equal to(=) symbol. There are following shorthand assignment operators supported by C programming language as follows:
An assignment operator can be divided into two types:
Simple assignment
Operator (=) -> Simple assignment operator, used to assigns values to variables.
Example: a=10
Compound assignment: It includes (+=, -=, *=, /=, %=) and is called a compound assignment operator because we are combining two operators, equal to and arithmetic operators.
Operator (+=) -> First addition than assignment will happen
Example: a+=10 => a = a+10
Note: a +=b is equivalent to a = a+b
A similar concept is applicable to other shorthand operators as well.
Operator (-=) -> First subtraction than assignment will happen
Example: a-=10 => a = a-10
Operator (*=) -> First multiplication than assignment will happen
Example: a*=10 => a = a*10
Operator (/=) -> First division than assignment will happen
Example: a/=10 => a = a/10
Operator (%=) -> First perform the modulas and then assignment
Example: a%=10 => a = a%10
Operator (<<=) -> First perform the bitwise left shift and then assignment
Example: a<<=10 => a = a << 10
Operator (>>=) -> First perform the bitwise right shift and then assignment
Example: a>>=10 => a = a >> 10
Operator (&=) -> First perform the bitwise AND operation and then assignment
Example: a&=10 => a = a & 10
Operator (|=) -> First perform the bitwise OR operation and then assignment
Example: a|=10 => a = a | 10
Operator (^=) -> First perform the bitwise XOR operation and then assignment
Example: a^=10 => a = a ^ 10
Typecasting
Typecasting is a method to convert a variable from one data type to another data type. For example, if we want to store a double value into a simple float then you can typecast double to float.
There are two types of type conversions in C:
Implicit typecasting(Widening Conversion)
Explicit typecasting(Narrowing Conversion)
Implicit type casting: If a compiler converts one data into another type of data automatically then it is called Implicit typecasting. There is no data loss in this type of conversion.
e.g: We can typecast an integer of value 2 to a double data type without losing any data.
2 -> 2.00 //here we are storing the same exact data in a different data type.
Let us take another example of Implicit type casting to understand how it actually works:
e.g: short a = 15; //Initializing variable of short data type
int b; //Declaring a variable b of int type
int b = a; //Implicit type casting
Whenever we make use of a mixed data type like in our example, then automatically the lower data type is converted to a higher data type.
for e.g: short -> is converted to int data type, and the conversion always happens for compatible data type only, as both short and int are of Integer type, as we know that, int -> consist of 32-bit of memory, whereas short -> consist of 16-bit of memory. While performing this expression there is no data loss and it typecast automatically in an implicit way.
Explicit type casting: When the data of one type is converted explicitly(forcefully) to another type as per the user convenience is known as Explicit typecasting. Here user can typecast the result to make a particular data type by using the cast operator. When we want to convert a higher data type value into a lower data type we make use of Explicit type. It is user-defined conversion, also known as typecasting.
Syntax: (datatype_name) expression
Example: int a=5, b=2; //Initializing variable of int data type
float c; //Declaring another variable c of float type
c =a/b; //Before typecasting the value of c would be 2
If done in an implicit way(there would be a data loss) as, a & b are int datatype and it would return an integer data like int/int i.e. 5/2 = 2 (In this expression the expected result should be 2.5 but we are getting the result as 2, because the value of the variables is of int type, so it will truncate the fraction part and hence losing the actual data). To overcome this situation we need to explicitly change the variable a to float type in the expression and we will use typecasting.
c = (float)a/b; //After typecasting the value of c would be 2.5
What will happen that the variable a will be converted forcefully from int to float and because of typecasting variable a would act like a float data type.
Now the second variable b which is an int type can be divided and the resultant produced for variable c would be a float number.
NOTE: Typecasting and type conversion have a significant difference as we can say conversions which are done automatically by the compiler and don't need any user involvement can be termed as Implicit type conversion or Implicit typecasting. Similarly, in Explicit type conversion also known as typecasting, means the data of a higher data type is converted or stored in a lower data type, and in this process, there is a data loss.
Preference
Operator precedence describes the order in which C will read expression.
For example, in this expression a=2+b*4
It contains two operations, an addition, and a multiplication. Operators with higher precedence will be executed first; in this case as the preference level of multiplication is 13 whereas for addition level is 12. It means that the C compiler evaluates multiplication first. Operators on the same line in the chart have the same precedence, and the "Associativity" column on the right gives their evaluation order.
Associativity
When an expression contains two operators of equal preference the conflict between them is settled using the associativity of the operators.
Storage classes
In C language, each variable has a storage class that decides the scope, visibility, and lifetime of that variable. These are the available Storage classes in C programming,
Automatic variables
External variables
Static variables
Register variables
Automatic variables
A variable declared inside a function without any storage class specification is by default an automatic variable. They are created when a function is called and is destroyed automatically when the function exits. Automatic variables can also be called local variables because they are local to a function. By default, they are assigned garbage value by the compiler.
Example:
void main()
{
int abc;
or
auto int abc; //Both are same
}
External or Global variable
A variable that is declared outside any function is a Global variable. A Global variable remains available throughout the entire program. One important thing to remember about the global variable is that their values can be changed by any function in the program.
extern keyword
The extern keyword is used before a variable to inform the compiler that this variable is declared somewhere else. The extern declaration does not allocate storage for variables. Global variables from one file can be used in other using the extern keyword.
Static variables
A static variable tells the compiler to persist the variable until the end of the program. Instead of creating and destroying a variable whenever it comes into and goes out of scope, static is initialized only once and remains in existence till the end of the program. A static variable can either be internal or external depending upon the place of declaration.
The scope of the internal static variable remains inside the function in which it is defined. External static variables remain restricted to the scope of a file in each they are declared. They are assigned 0 (zero) as the default value by the compiler.
Register variables
Register variable informs the compiler to store the variable in a register instead of memory. Register variable has faster access than the normal variable. Frequently used variables are kept in the register. Only a few variables can be placed inside the register.
Syntax: register int number;
const
It's really quite simple: const means that something is not modifiable, so a data object that is declared with const as a part of its type specification must not be assigned to in any way during the run of a program.
Example: const int pi= 3.14 //we are telling the compiler, the value of variable pi is constant
volatile
A volatile keyword indicates that value may change between different accesses, even if it does not appear to be modified. This keyword prevents an optimizing compiler from optimizing away subsequent reads or writes and thus incorrectly reusing a stale value or omitting writes.
volatile values primarily arise in hardware access (memory-mapped I/O), where reading from or writing to memory is used to communicate with peripheral devices, and in threading, where a different thread may have modified a value.
Syntax: volatile int x;
int volatile x;
Here both the declarations are correct for volatile.
Loops in C
Loops in the world of programming, this means repeating the execution to statement or block of the statement with respect to the condition specified by the programmer.
Fact about loops
90% of the execution time of a computer program is spent executing 10% of the code, this is known as the 90/10 law.
There should be a condition, which must get satisfied after some specific loops so that the loop could be terminated, else your program will end-up executing an infinite loop, and execution will never end, so be cautious.
Loops in C programming
In C programming there is various type of loops, in-fact as the conventions of C programming is been followed by many other programming languages, so majorly in any other programming language there exist three types of loops.
while loop
for loop
do-while loop
while loop
In a while loop, the initialization, condition and increment and decrement is done in three different sections of the code.
Syntax of while loop:
Initialization;
while(test expression)
{
//block of code
Increment/decrement of counter
}
The condition and scope
The condition in the loop does not have any restriction; we can use any condition and any number of comparisons.
Example:
while(i<=10 || j >=10)
while (a == b && b==c &&(i==2))
Both the statements are syntactically correct.
Scope
The default of any loop and any other conditional statement is one statement
Example:
while(i<=10)
{
printf(“%d”, i++);
}
And
while(i<=10)
printf(“%d”, i++);
Both are correct and will the same output.
Infinite loop
The infinite loop means the condition in the loop is true infinitely.
Example:
inti=1;
while(i<=10)
{
printf(“%d”,i);
}
In the above block of code, we can observe that it’s an infinite loop as the condition will always be true. The value I will remain 1 throughout the life-time of this block of code.
The best way to write an infinite while loop.
Example:
while(1)
{
//block of code.
}
Note: In infinite loop Initialization, condition, and increment/decrement are optional.
About increment and decrement
We can use increment and decrement according to our requirements. And there is no restriction that we should only use integer counters in a loop.
Example:
float x=1.0;
inti=1;
while(x > 0)
{
printf(“%d ”,i++ );
x=x-0.1;
}
The above block of code will give output as
1 2 3 4 5 6 7 8 9 10
Increment and decrement operator
The increment and decrement operators are equivalent to current value plus one or current value minus one.
10 ++ and ++ 10 gives 11
Whereas 10+++ will give us 12, it will add two to 10, try to play with ++ and -- only in your program to avoid confusion.
These operations not only work on integer values, but these will also operations works on any other compatible datatype.
Example: 0.1++ will give us value 1.1
Prefix and postfix
Increment and decrement operators have 2 variation or types:
prefix
postfix
In prefix, operators are written before their operands.
Example:++10
In postfix operators are written after their operands.
Example: 10++
For loop
In for loop, the initialization, condition, and increment or decrement is done in the same statement of the code.
Structure of for loop
The working of a while and for loop is the same, just the syntax differs. Now in some situation for loops suits better and some other situation while loop suits better. It’s the choice of the coder and in a situation, while loop is been used, for loop can also be used in the same situation.
Syntax: for(initialization; condition; increment/decrement)
Condition
The condition in the loop doesn’t have any restriction; we can use any condition and any number of comparisons.
Scope
As the default of any loop and any other conditional statement is one statement.
Example:
for(inti =1; i <= 10; i++)
{
printf(“%d”, i++);
}
Infinite loop
The best way to code an infinite loop using for loop.
for(;;)
{
//block of code.
}
Note: For infinite loops Initialization, condition, and increment/decrement are optional.
Break and continue
In the discussion on infinite loop, I have told you that there are provisions in C programming to terminate the loop, even though the condition is correct. One of these provisions is making use of keyword break; we will now see the usage of break and also what usage is of continue statement.
Break
In C programming, the break is used in terminating the loop immediately after it is encountered. The break statement is normally used with a conditional if statement.
Syntax: break;
Continue
Sometimes if the coder wants to skip a few statements inside the loop. In such cases, continue statements are used.
Syntax: continue;
The do-while loop
In C programming, do...while loop is similar to while loop. The only difference between do…while and while loop is that, in while loops, we test the conditions first and if found true then we execute the block of code but, in do...while loop code is executed first then the condition is checked. So, the block of code is executed at least once in do...while loops.
Syntax of do-while:
initialization
do
{
//block of code
Increment/decrement;
}while(test expression);
Note: Observe the semi-colon at the end of while condition’s parenthesis.
Scope
As the default of any loop and any other conditional statement is one statement
Example:
int i=1;
do{
printf(“%d”, i++);
}while(i<10);
And
int i=1;
do
printf(“%d”, i++);
while(i<10);
Both are correct and will have the same output
Note: The only places you can avoid braces '{ }'are for the bodies of if-else, for, while, or do-while statements if the body consists of a single statement.
Infinite loop in do…while
Example:
do
{
//Block of code
}while(1);
Multiple initializations
As we have seen already that we can test multiple conditions and any of the above loops, in-fact we can and make multiple initializations and increment or decrement.
Example: for(i=10,j=2; i<=10 && j>0; i--,j++)
Nesting of loops
A Nested loop is a loop inside a loop, an inner loop within the body of an outer one.
Syntax:
Outer_loop {
Inner_loop {
// inner loop statements.
}
// outer loop statements.
}
Outer_loop and Inner_loop are valid loops that can be used for any of three looping structures like, for loop, while loop, and do-while loop also.
Example:
for(int i=1;i<=3;i++) // outer loop
{
for(int j=1;j<=2;j++) // inner loop
{
printf("value of i= %d\n",i); // printing the value.
printf("value of j= %d\n",j); // printing the value.
}
}
Case control structure
The statements which are used to execute only a specific block of code in a given series of a block of code are called case control structure. The structure is known as decision making using switch case.
Syntax:
switch (condition/expression/value)
{
case label1:
statements;
break;
case label2:
statements;
break;
default:
statements;
break;
}
If the expression or the condition matches any one of the cases then that particular case would be executed.
Note: Default case is optional
In this program, we will understand the basic arithmetic operations. So let us take an example where will depict various operations like addition, subtraction, multiplication, and division. The name of the program would be "Basic calculator"
First, we will declare variables as option, a, b
e.g: int option a,b; //a and b are the two operands
Then we will ask the user to enter two values using the print statement.
To take the user input we will use printf() and scanf() function.
To make this program a menu-driven program we will use an infinite while loop.
e.g: while(1) //infinite loop
Now we will ask the user to enter options that will be seen on the output to perform all operations using the printf() function.
Then using switch case we will define the operations in various cases and each case defines one arithmetic operation respectively.
So in this way, we can perform a menu-driven basic calculator program using a case-control structure.
Functions
Functions in the programming world define the significant importance of dividing a complex program into smaller chunks (subprograms) to make our program easy to understand and reuse later. A function is a block of statements enclosed within “{ }” (curly braces) that takes input, performs some computations, and produces a result (output).
A function is considered as one of the basic pillars of C programming language and no program in C could execute without functions.
A function is also known as a procedure or subroutine.
Why Functions?
To reduce the complexity of our program
Achieve reusability and modularity(breaking into subprograms)
To make the process of debugging easier.
Easy to modify.
To avoid rewriting the same logic/code again and again.
Better memory utilization.
Function prototype
Function prototype also known as function declaration is necessary to provide information to the compiler about function, about return type, parameter list, and function name, etc.
Syntax: return_type function_name ( data_type arguments );
prototype declaration comprised of three parts function name, return type, and a parameter list(arguments).
return_type: Type of output returned by the function, e.g. char, int, float type, etc.
function_name: The name of the function followed by parentheses “()”
arguments: The type and number of arguments that the function expects when the function is called.
Examples:
int sum(int,int);
int square(int);
void display();
int getValue(char);
Global vs. Local variables
Local Variable
Local variables are declared inside a function.
Local Variables cannot be accessed outside the function.
Local Variables are alive only for a function.
Example:
void main()
{
int x=5,y=3; // Internal declaration
printf("x=%d and y=%d",x,y);
}
Here x and y are local variables that are declared inside the function only.
Global Variable
Global Variables are declared before the main function.
Global Variables can be accessed in any function.
Global Variables are alive until the end of the program.
Example:
int a=4,b=2; // Global variable
void main()
{
printf("a=%d and b=%d",a,b);
}
Global variables can be accessed from any point of the program and are declared prior to main() function.
Program to demonstrate a number is prime or not using functions.
Let us take a simple example to define the functions using a program in C:
int num,i,flag=1; //declare variables num, i and initialize the variable flag as 1
Then we will ask the user to provide input with the help of printf() and store the variable num in scanf() function
e.g. printf("Enter the number to find it is prime or not : "); //to display user input on console
scanf("%d",&num); //to store address of variable
Now we will run a loop where the value of i is initialized as 2 and num value is less than 1
e.g. for(i=2;i<num;i++)
if(num%i==0) //the value of num is restricted to less than 1
flag=0; //set the flag value as zero
if(flag == 0) //If the value is zero means it is not a prime number
If the flag value is equal to zero, it will print the number is not a prime number on the console using the print statement.
And in the else part, If the flag value is not equal to zero or greater than zero, it will print the number as a prime number.
********************************************************************************************************************************
Let us take another example to demonstrate a leap year or not using functions.
In the program we have to take three conditions into consideration namely:
If a year is divisible by 400 then it can be considered as a leap year.
If a year is divisible by 100, but not divisible 400 then it is not a leap year.
Also if a year is divisible by 4 then it can be considered as a leap year.
int year; //declare variable_name as year
printf("\nEnter a year to check if it is a leap year\n") //ask the user to provide input on the console
scanf("%d", &year); //to store address of variable
if ( year%400 == 0) //If a year is divisible by 400 then it is a leap year
else if ( year%100 == 0) //If a year is divisible by 100, but not divisible by 400 or any number then it is not a leap year
else if ( year%4 == 0 ) //If a year is divisible by 4 then it is also a leap year
else //rest for all other conditions the year is not a leap year
So this how we can implement functions in C using both the programs.
Usage of function
A function is one of the most important concepts in the C programming language. There are many advantages or uses of the function in a program. Here are some of the aspects which make functions so important in C.
To reduce the complexity of our program.
Achieve reusability and modularity(breaking into subprograms)
To make the process of debugging easier.
Easy to modify.
To avoid rewriting the same logic/code again and again.
Better memory utilization.
Functions can be called from anywhere in a program at any number of times.
Note: Writing the programs in a single function called main() will work well for small programs, but if the complexity of the program increases, the entire program cannot be written in one function. It needs to be broken down into several functions, each of which would be performing a specific type of task.
Command-line argument
Command-line arguments are given after the name of the program in the command-line shell (command prompt) of Operating Systems.
To pass command line arguments, we typically define main() with two arguments: the first argument is the number of command-line arguments and the second is a list of command-line arguments.
Syntax: int main(int argc, char *argv[])
Here,
argc: refers to the counts the number of arguments on the command line and
argv[ ]: It is a pointer array that holds pointers of type char which points to the arguments passed to the program.
Arrays in C
An array is a collection or a group of elements with the same data type. In order to store multiple values in a variable, we make use of arrays. It has the capability to store multiple values in the same variable. Let us take an example:
int abc; //as it as a variable it can store only one value in it and many a time storing a single value in a variable is not enough. So to overcome this scenario we make use of a special type of variable known as arrays.
int testArray[4]; //size of array is 4, so it will start from zero i.e. testArray[0], testArray[1], testArray[2], testArray[3], so this how we access the value of arrays.
Note: The index of the array always starts with Zero. The rules followed to create a variable is the same for declaring array_name also.
Syntax: data_type array_name [size];
data_type: type of data stored in the array.
array_name: a name given to the array.
size: Number of elements an array can hold.
In C, based on the dimensions arrays are classified as:
One-dimensional array(1D array): In a One-dimensional array the elements of the array are defined in a row and the values are stored in a linear order(one after another), and here dimension is represented as [] square brackets(called as subscripts). So, it has a single subscript, and immediately after writhing the array_name, it is followed by an Array subscript or index that starts at 0. If the size of an array is 5 then the first element is at index 0, while the last element is at index 4.
Example: int oneD_array = 5;
These elements can be stated on the index of array as:
First element - oneD_array[0]
Second element - oneD_arrayr[1]
Third element - oneD_array[2]
Fourth element - oneD_array[3]
Fifth element - oneD_array[4]
2. Multidimensional array(includes a 2D array,3D array, 4D array, and so on....)
Out of which one-dimensional array(1D array) and two-dimensional array(2D array) are mostly used in C.
Arrays in C are further defined in two basic data types:
Numerical arrays: int, float, double.
Character arrays: These arrays are those which we declare with a char data type.
Working with array
When we create an array, we are creating, a group of data or elements that are of the same data type. We cannot mix the data specified in the array i.e. if we want to use integers and character data type for an array, it is recommended to create two separate arrays specifying these two data types each. Let us understand with the help of a program.
In our program, we have declared two variables, the first variable is an array of size 10 and the second one is a normal variable whose name is i. e.g: int testArray[10], i; // testArray and i are two variables here in this program
We will run a loop and this loop will continue to loop over 10 times as the condition will be true 10 times.
e.g: for(i=0;i<10;i++) //a for loop which will run till i=9 as arrays index position starts at zero, means it will run from i=0 to i=9
Now we will display the value inside array i.e. testArray and passing i variable in the index location.
e.g: printf("%d", testArray[i]); //passing i in the subscript or index of the array
Whenever we don't initialize the variable and try to print it, there would be a garbage value inside it, even for an array or even for a normal variable also.
In order to initialize the array, we can simply add the elements inside curly braces "{ }"
e.g: int testArray[10] = {1,2,3,4,5}, i; //here the values would be like (1 2 3 4 5 0 0 0 0 0) because we have not initialized the other elements value and as the size is 10, the compiler automatically intializes the rest of the value as zero by default.
Sorting an array
Sorting is nothing but arranging numbers in ascending or descending order. We can use various algorithms to sort a number in arrays. Let us consider an example, where we will take user input to sort the numbers in ascending order in the following steps:
Steps:
We need to sort the given array in ascending order such that each element will be arranged from smallest to largest. The numbers to be sorted are 8 3 5.
We can simply compare the elements present with each other. So we will compare the first number with the second number.
If the first number i.e. 8 is greater than the second number, we will swap both the values.
e.g: 3 8 5 //here the first number value will be changed to 3 and the second number value will be 8.
Similarly, we need to compare the value for the second and third numbers also.
e.g: 3 5 8 //here we swap the values from smallest to the largest number
So this is how we can sort a given array.
There are many ways to sort a given array and sorting of the array can be performed using the following algorithms in C:
Selection Sort
Binary Sort
Merge Sort
Insertion Sort, etc.
Strings
Strings is a collection of characters or we can call it an array of characters. A character is nothing but a single letter, alphabets, numerics, special symbols all these can be considered as a character in C language.
example: suppose a is a character, either it can be a capital letter or small letter and are enclosed within a single quote known as characters.
'a' 'A' -> these are characters.
Declaration of Strings
Syntax: char stringname[size];
Instead of using int and float as data type we mostly use char as a datatype for strings.
Note: In strings, all the rules which were followed for writing one-dimensional arrays are also followed here. So the rules for declaring integer arrays, character arrays would be the same.
Example: char str[6] = {'H', 'E', 'L', 'L', 'O, '\0'} //here 6 is the size the array that contain elements within.
Here in the strings, the Null character is represented as slash zero '\0' and is used to end the string because the compiler doesn't know where the string ends, so we make use of '\0' to end the strings of characters.
String Input from user
In this program, we will take the user's input from the user, and the user input would be for the name field. Let us follow the steps to perform a user input:
Steps:
In our program, there would a character array of size 30
e.g: char name[30];
Note: If we are declaring and initializing the character array at the same time then the size is optional because the compiler will calculate the size of the array.
In this program, we have allocated 30 bytes of memory in an array, so we can store 30 characters from the user input.
Now we will write a print statement.
e.g: printf("Please Enter Name:"); //to display as an output on console
After that, we will write a scanf function in our program.
e.g: scanf("%s",name); //here we will not use ampersand(&) symbol because the name by default gives to address to scanf function.
Whenever we want to take a user input from a string or character array we need not make use of the ampersand(&) symbol followed by the variable name.
Take another print statement to display a string on the console as output.
e.g: printf("Hello %s",name); //If we are not using %s in the print statement then it would print Hello as output because as we know %s is an identifier to specify strings, the value or name of the variable defined in the previous print statement can be printed using %s and it will concatenate both strings as output like, for e.g: Hello Chaand
String library functions
C supports a wide range of functions that manipulate null-terminated strings.
Commonly used string functions in C
Let us take a simple example where str1, str2 would be the string variables.
strlen() -> Calculates the length of string.
Example:
int len;
string str1 = "Chaand"; //value of str1
len = strlen(str1); // returns size of str1 which is 5
strcpy() -> Copies a string to another string, means this library function copies value of second string to first string, like: strcpy(destination , source).
Example: strcpy( str2, str1 ); // Copies the string value to str2 to str1
Note: It will include all the white spaces and characters in the string except for NULL('\0') character.
strcat() -> Concatenates(joins) two strings
Example: strcat( str1, str2); // Concatenates str1 and str2 and the resultant string is stored in str1
strcmp() -> Compares two string
Example: strcmp( str1, str2); //used to compare the values of two strings
strlwr() -> Converts string to lowercase
Example: char str[] = "WELCOME TO STUDYEASY!";
printf("%s", strlwr(str)); // will print value of str[] in all lower case characters, like welcome to studyeasy!
strupr() -> Converts string to uppercase
Example: char str[] = "welcome to studyeasy!";
printf("%s", strupr(str)); // will print value of str[] in all upper case characters, like WELCOME TO STUDYEASY!
Note: Don't forget to include <string.h> library function in your program, else you won't be able to access any of the following string functions mentioned.
Multidimensional arrays
As we know that an array is a group of elements with similar data types. In C programming, multidimensional arrays can be defined as the combination of multiple arrays. A multidimensional array has more than two subscripts and also known as an array of arrays. Based on the dimensions arrays are classified as:
2D array(two-dimensional array)
3D array(three-dimensional array)
4D array(four-dimensional array) and so on...
The total number of elements stored in a multidimensional array can be calculated by multiplying the size of all the dimensions.
for example: array int a[3][4][5] can store (3*4*5) = 60 elements.
Out of which one-dimensional array(1D array) and two-dimensional array(2D array) are mostly used in C. Two dimensional arrays have two subscripts, which means the dimensions enclosed within the square brackets is two. 2D arrays are those which are stored in a matrix form or in simple words, the data is represented in a row and column order(that means if the data is in a tabular format then we can use this type of array).
Here the difference between one-dimensional array(1D array) and two-dimensional array(2D array) is with respect to subscripts only, 1D array has one subscript whereas 2D array has two subscripts. Let us understand with an example below,
example: int a [3]; // one dimensional array
int a[3][4]; //3 and 4 are the size of an array and it is a 2D array
Syntax for 2D arrays: data_type array_name [size1] [size2];
data_type: type of data stored in the array.
array_name: a name given to the array.
size1, size2: sizes of the dimensions.
Note: If we are using one-dimensional array then we will use one loop because the array condition depends on the subscript, similarly if we want to use two dimensional arrays we must use two loops and so on.
example: for(i=0; i<5; i++) //one dimensional array
for(i=0; i<5; i++)
for(j=0; j<2; j++) //two dimensional array has two subscripts so we will use two loops i for row and j for column
Passing arrays to functions
We pass arrays to a function when we need to pass a list of values for a given function. In C, there are ways where we can pass an array to a function:
By simply declaring array as a parameter in the function.
Also, we can declare a pointer in the function to hold the base address of the array.
In C, we can pass an entire array to a function, similar to what we do in passing variables to a function.
Syntax: function_name(array_name); //passing array
Let's take a simple program where we will understand how to pass an array to a function.
In our program, we will first declare a function that will take two inputs or two arguments.
e.g. int sum( int arr[], int size);
Here, sum -> is a function, arr[] -> is the base value of the array, and size -> will tell the size of the array elements.
Now in the main() function, we will pass the name of the array as an array and let us consider, the size would be 5
e.g. int array[5] = { 1000, 2, 3, 17, 50}, result; //an int array with 5 elements
A variable result will store the expected output for our program.
We can call the function sum and pass the name of the array i.e. array and then the size of the array.
e.g. result = sum( array, 5 ); //pass pointer to the array as an argument
In the function part we are taking a variable name arr and size as an integer type, int sum( int arr[], int size);
Then we will run a loop where we will add the value in the variable sum
e.g. sum = sum + arr[i];
At last, we will return the value of the function sum and print the output in our console.
e.g. return sum;
Memory layout of an array
To understand this concept, let us say a statically allocated variable or an array has a fixed size in memory. As we know, memory is a very useful resource in any programming language. Whenever we define an array the elements are in adjacent cells and it is a contiguous chunk of memory being allocated for a particular array, say for example we are talking about a character array and we have initialized this character array with a string.
example: char demo[]= 'HELLO'; //demo is the name of character array
Note: The memory layout for any other array is identical.
Let us give some memory location to the string 'HELLO' for a better understanding and each character will hold a cell memory address respectively. It could be as follows:
H -> 4001
E -> 4002
L -> 4003
L -> 4004
O -> 4005
\0 -> 4006 (NULL or string terminator symbol)
As we know, an array initial position or it starts from 0, so demo[0] will contain the address 4001. Similarly for other characters, the position would in a continuous form like demo[1] -> 4002, demo[2] -> 4003, demo[3] -> 4004 and so on.
Enum in C
An Enumerated datatype(Enum) is used to create our own user-defined datatype that contains constant (fixed) values stored in the form of numeric values.
It starts at 0 (zero) by default and incremented by 1 in a sequential manner.
Syntax: enum enum_name {v1, v2 …vn};
Need of Enum
Enum names are automatically initialized by the compiler and internally, the compiler treats it as integers.
Enum helps in writing clear codes and to make our program more readable.
Enum is a user-defined datatype, which means we can have a variable that is of type enum.
typedef
typedef is a keyword that is used to give a new symbolic name for the existing name in a C program. This is the same as defining an alias for the commands.
typedef unsigned int NATURAL_NO;
After this type definition, the identifier NATURAL_NO can be used as an abbreviation for the type unsigned int.
For example:
NATURAL_NO x, y;
Structure in C
A Structure is a collection of different kind of datatype variables grouped under a single type. These datatypes could be an integer(int), character(char), float, double, array, or any other type of data. Structures are also used to represent a record.
Let's take a simple example in which we will store information about a student, these data would be for student id, name, age, and gender. Here we can see that the information been provided are of various data types like,
id -> could be an integer data
name -> could be a string data
age -> could be an integer data
gender -> could be a string data
So, we can see that there are various datatypes been used here to store a record for students. In C, Structure has the facility to provide or store different kinds of data types grouped within a single datatype, and to create a Structure in our program we make use of the struct keyword.
Syntax:
struct structure_name
{
<data_type> member1;
<data_type> member2;
................
} structure variables;
Whenever we create a structure, it would have a particular name, and inside this, it will have different kinds of data members or datatypes grouped within.
Note: In structure, we can also define a structure variable in the main() function, or else we can define a structure variable after closing the function, as you can see in the syntax, both ways are correct.
We can also define more than one structure variables in our program by using a comma-separator between the variables like,
Example: struct Student s1,s2; //declaring variables of struct Student
Union
A union is a special data type available in C that enables you to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multi-purpose.
Unions are conceptually similar to structures. The syntax of union is also similar to that of structure. The only difference is in terms of storage.
In structure, each member has its own storage location, whereas all members of the union use a single shared memory location which is equal to the size of its largest data member.
This implies that although a union may contain many members of different types, it cannot handle all the members at the same time. A union is declared using the union keyword.
Union occupies the size of the largest member-only and hence occupies less memory.
Syntax:
union union_name
{
data_type member1; //member1 name of the variable
data_type member2; //member2 name of the variable
. . . . . . . . . . . . . . . .
. . . . . . . .. . . . . . . .
data_type memberN; //memberN name of the variable
};
Example:
union Student
{
int mark; //mark is of integer type
char name[20]; //name is array of characters
float average; //average is a floating point number
};
C Pointer
Pointers deal with memory access and manipulate the content in a particular location in memory. We can say that in C language, a pointer is a special type of variable that stores addresses of other variables rather than storing values.
To designate variables as pointers *(asterisk symbol) is used, followed by the variable name and it is known as indirection pointer that is used to dereference a pointer.
When we declare a variable in our program, for example, let's say we declare a variable 'x' of type integer then when this program will execute, the computer will allocate this variable some amount of memory. So how much memory it allocates would depend upon the type of datatype it contains.
example: int -> allocates 4 bytes of memory.
char -> allocates 1 byte of memory and so on.
A computer has an internal structure called a lookup table where it stores this information that there is a variable x of type integer and has a specified address in memory.
Whenever we create a variable in a program, it has its own memory address and if we want to store this variable's address to some other variable we make use of Pointer. In simple words, we can say Pointer is a variable that holds addresses of another variable within itself.
Note: If we have an integer variable and we want to create a pointer for that, then the pointer will be also of integer type means if we create a variable of any data type, then the pointer would be also of the same type.
Understanding Pointers
To start with let's recall the definition of pointers and we will understand, why it is an essential concept in C Programming language.
Definition: A pointer is a variable that stores the address of an object. Unlike other normal C variables, a pointer is a special type of variable that holds addresses of some other variable within itself, and here object can be anything, it could be a variable, an array, structure, function, or a pointer itself.
Whenever a variable is defined the compiler allocates some memory based on its data type. The syntax for a variable declaration and pointer is almost similar, but the only difference is in a pointer we make use of an asterisk symbol(*) before the variable name.
Syntax: datatype *variable_name;
Here, datatype -> means the type of data stored in the address of the variable.
* -> asterisk symbol defines as an Indirection Operator.
Pointer Operators
& -> Address of (Reference) operator.
* -> Value at address(Indirection) operator.
In C, functions are based on how we specify the arguments, also known as actual and formal parameters:
Actual parameters: These are parameters that are passed to a function and appear in the function calls.
Formal parameters: The parameters which are received by a function.
We can call a function based on two different ways, these are:
Call by value: Here the values are copied from the actual parameters to the formal parameters and these two parameters are stored in the different memory locations and any changes made in the formal parameters are not reflected back to the value of the actual parameter. In call by value procedure, we are simply passing the values to the variables and not the variables itself. So, this is called call by value.
Call by reference: In Call by reference the memory address is passed from the actual parameters to the formal parameters and the same memory location is used for both actual and formal parameters. Here reference indicates the address of the variable. If any changes made in the formal parameters, it also gets reflected in the actual parameter value because here we are passing the addresses not the values.
Program to demonstrate a pointer accepts two strings and store concatenation of these strings without using library functions.
Let us understand the basics first, to do so, take different variable types in our example.
e.g. int x; //x is an int type of the variable and hence x will contain an integer value.
int *x; //means x is a pointer type variable and it is capable of accepting an integer entity.
char *y; //y is a variable of pointer type which will contain an address of a character.
char *y[10]; //y is a pointer type entity that will store the base address of a character array.
The compiler will accommodate 10 memory locations for this character array.
Files Handling in C
A file represents a sequence of a byte on the disk where a group of related data is stored. A file is created for the permanent storage of data. In C, we use a structure pointer of the file type to declare a file.
Here in this files concept, we can save the input data as well as we can save the output data. So, files consist of a group of strings i.e. we can read a number of lines of texts in the files.
Types of Files
In C, there are two types of files in which data can be stored either in characters equivalent to their ASCII character set or in binary format. These are:
Text files: Data will be stored in the form of ASCII values. So for every character, there is an equivalent numerical value.
for example: C -> ASCII code for C is 067
All the text related information like alphabets, digits, and special symbols comes under Text files. When we are creating a program using the C compiler, we will save the program using the extensions .C and this .C files also comes under the Text files, other extensions for Text files are .txt, .doc, etc. so everything other than the binary files is considered as Text files extensions.
2. Binary files: Any data which is represented using 0's and 1's format will come under this Binary files type. Usually, these files are used for computers to understand any data. These files are not human-readable and hence can't be recognized by the word processor.
Binary files are saved with the following file extensions like .bin and .exe type of format.
Reading text from a file
The first thing we should understand, what actually is a FILE and why it is used.
A FILE is a special type of data type which is defined inside the header file <stdio.h> and in fact, it is a data type, not a keyword in C Programming language. Suppose we have not included this header file <stdio.h> in our program it will throw a warning describing that FILE data type is not declared.
Opening a file
Syntax: FILE *fopen(const char *filename, const char *mode);
Here's a simple example of using fopen:
Example:
FILE *fp;
fp=fopen("test.txt", "r"); // r used for opening a text file for reading mode
Closing a File
The fclose() function is used to close an opened file.
Syntax: int fclose( FILE *fp );
Example: fclose(fp);
In C, there are three various modes for reading:
r: It is used for opening an existing text file, the only purpose is to read the text files.
r+: It is an advanced option, which works for both reading and writing of a text file.
rb: It is used as a reading mode for binary files only.
C provides a number of functions that help to perform basic file I/O operations.
List of Functions used in a reading mode:
fopen() -> create a new file or open an existing file
getc() -> reads a character from a file
fscanf() -> reads a set of data from a file
getw() -> reads an integer from a file
File opening Modes in C
r -> opens a text file for reading mode
r+ -> opens a text file in both reading and writing mode
rb -> opens a binary file for reading mode
r+ -> opens a text file in both reading and writing mode
rb+ -> opens a binary file in both reading and writing mode
C provides a number of functions that help to perform basic file I/O operations.
List of Functions used in a writing mode:
fclose() -> closes a file
putc() -> writes a character to a file
fprintf() -> writes a set of data to a file
putw() -> writes a integer to a file
fseek() -> set the position to the desired point
ftell() -> gives current position in the file
rewind() -> set the position to the beginning point
File opening Modes in C
w -> opens or creates a text file for writing mode.
a -> opens a text file in append mode
r+ -> opens a text file in both reading and writing mode
w+ -> opens a text file in both reading and writing mode
a+ -> opens a text file in both reading and writing mode
wb -> opens or create a binary file for writing mode
ab -> opens a binary file in append mode
rb+ -> opens a binary file in both reading and writing mode
wb+ -> opens a binary file in both reading and writing mode
ab+ -> opens a binary file in both reading and writing mode
After knowing the fundamentals of Files in C, let's take a simple program example where we will see how to read as well as write(means append) a text file and store the information of that text file into some another text file.
Suppose, we have three text files namely a1.txt, a2.txt, and a3.txt in our program, out of which a3.txt is a blank text file and a1.txt, a2.txt has some content in it.
Our motive is to store the content of both the text file i.e. a1 and a2 into a3. To do so let us follow the program flow in the following steps:
We will read the first text file, copy, and store the contents of the first text file i.e. a1.txt into the third text file i.e. a3.txt and similarly, we will do for the second text file also.
e.g. FILE *fp1 = fopen("a1.txt", r); //*fp1 is the FILE pointer that will hold the reference to the opened(or created) file and the mode r specifies it is a reading mode.
FILE *fp2 = fopen("a2.txt", r); //*fp2 is also a FILE pointer and the mode r specifies it is a reading mode.
FILE *fp3 = fopen("a3.txt", w); //*fp3 is a FILE pointer and the mode w specifies it is used in a writing mode.
Now, a1.txt has some text content in it, for example, C programming and a2.txt have text content like Golden step to become a software developer and a3.txt is a blank text file(no text is available in this text file)
In order to read every character, we would require a character variable.
e.g. char c; //variable c of character type
In our program, we will try to open all these three files using IF condition and check if it satisfies the given condition and if not we will print the output as Could not open files and will exit from this program.
e.g. if(fp1 == NULL || fp2 == NULL || fp3 == NULL) //check the condition and open the three files
To print a string of output on screen we make use of puts() function.
e.g. puts("Could not open files"); //used as a printing statement for string objects.
We will run a while loop for this.
e.g. while((c = fgetc(fp1)) != EOF) //fgetc() function is used to obtain from a file and a single character at a time. EOF means end of file.
Now we will fputc() function to write character by character for the third text file.
e.g. fputc(c, fp3); //to write contents of fp3
At last, we will close all the three text files.
e.g. fclose(fp1); //to close fp1 file pointer
fclose(fp2); //to close fp1 file pointer
fclose(fp3); //to close fp1 file pointer
When we execute this program it will show the contents present in both files a1.txt and a2.txt in the third file i.e. a3.txt
The C programming language is one of the foundation or base-language of many programming languages today. Dennis Ritchie developed the C language and it has known as the mother of programming languages. It has nearly been four decades since the C programming language invention and yet it is in use in many applications today. The invention of the C language made the usage of languages like COBOL, PASCAL, and FORTRAN obsolete. The C language is widely in use today. Many other programming languages have their programming structure evolved from the C language just like the C++ and C# programming languages. The C language is very robust and it could be used to implement many programs, software, and applications. Any person who is interested in learning programming should first make sure that he/she has a strong basic background in C programming language. A person who masters the varied aspects of the C programming language can master any other programming language with relative ease.
Why you should take this course
1. 69 lectures, 9 Sections, and 6 quizzes
2. Reduced length of videos: We have removed any useless second from the videos to save the user's time.
3. Use of Zoom and pan: We have used the Zoom and Pan technique to improve the visibility of the content in the videos on computers and mobile devices.
4. Easy to understand: The instructor has a neutral accent, Which makes understanding him easy.
5. Downloadable material are available with many videos, In order to help the users
6. The size of the videos is small, as high compression and advance codecs are used to render, which makes the buffering of videos fast.
7. Regular updates (if required)
This course covers concepts like:
Why we should learn C programming
History of c programming language
Where C programming stands in programming world
Where C is Used
Comparison of C programming launguage with English
Variables and Constants under C programming
Keywords under C programming
Hello World program demonstration
Lets become good coders
datatypes
format specifiers and escape sequences
How to Interchange values of variables
Decision making using if condition
Operators
Understanding Typecasting
Storage classes
Const and volatile
Understanding loops
Understanding break And continue
Understanding Case control structure
Function Prototyping
Global vs Local variable
Understanding arrays
Understanding Strings
String input under user, demonstration
String manipulation functions
Multidimensional array
Passing arrays to functions
Enum
Typedef
Structures
Union under C programming
Pointers
Call be reference
Memory layout of array
reading text from a file
Writing on a file
Read from file and write into another file
Appending file
No question asked - Money Back Guarantee!
There is no risk, this course comes with a 30-day money-back guarantee. Once you purchase the course, if for any reason you are not satisfied with the course, please let us know, we will refund 100%, no questions asked. So you have nothing to lose, sign up for this course, and learn “C programming, Golden step to becoming a software developer”!
The price of this course is low, but there would be a hike in price in regular interval Happy Learning :)