UNIT 2
Introduction To Programming
C is a procedural programming language. It was initially developed by Dennis Ritchie in the year 1972. It was mainly developed as a system programming language to write an operating system. The main features of C language include low-level access to memory, a simple set of keywords, and clean style, these features make C language suitable for system programming’s like an operating system or compiler development.
Many later languages have borrowed syntax/features directly or indirectly from C language. Like syntax of Java, PHP, JavaScript, and many other languages are mainly based on C language. C++ is nearly a superset of C language (There are few programs that may compile in C, but not in C++).
Beginning with C programming:
- Structure of a C program
after the above discussion, we can formally assess the structure of a C program. By structure, it is meant that any program can be written in this structure only. Writing a C program in any other structure will hence lead to a Compilation Error.
The structure of a C program is as follows:
The components of the above structure are:
- Header Files Inclusion: The first and foremost component is the inclusion of the Header files in a C program.
A header file is a file with extension .h which contains C function declarations and macro definitions to be shared between several source files.
Some of C Header files:
- Stddef.h – Defines several useful types and macros.
- Stdint.h – Defines exact width integer types.
- Stdio.h – Defines core input and output functions
- Stdlib.h – Defines numeric conversion functions, pseudo-random network generator, memory allocation
- String.h – Defines string handling functions
- Math.h – Defines common mathematical functions
Syntax to include a header file in C:
#include
2. Main Method Declaration: The next part of a C program is to declare the main() function. The syntax to declare the main function is:
Syntax to Declare main method:
Int main()
{}
3. Variable Declaration: The next part of any C program is the variable declaration. It refers to the variables that are to be used in the function. Please note that in the C program, no variable can be used without being declared. Also, in a C program, the variables are to be declared before any operation in the function.
Example:
Int main()
{
Int a;
.
.
4. Body: Body of a function in C program, refers to the operations that are performed in the functions. It can be anything like manipulations, searching, sorting, printing, etc.
Example:
Int main()
{
Int a;
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("GeeksQuiz"); Return 0; } |
Let us analyse the program line by line.
Line 1: [ #include <stdio.h> ] In a C program, all lines that start with # are processed by pre-processor which is a program invoked by the compiler. In a very basic term, pre-processor takes a C program and produces another C program. The produced program has no lines starting with #, all such lines are processed by the pre-processor. In the above example, pre-processor copies the pre-processed 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. 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.
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 4 [ printf(“GeeksQuiz”); ] printf() is a standard library function to print something on standard output. The semicolon at the end of printf indicates line termination. In C, semicolon is always used to indicate end of statement.
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.
3. How to execute the above program:
In order to execute the above program, we need to have a compiler to compile and run our programs.
4. Windows: There are many compilers available freely for compilation of C programs like Code Blocks and Dev_CPP. We strongly recommend Code Blocks.
Linux: For Linux, gcc comes bundled with the Linux , Code Blocks can also be used with Linux.
Steps to solve logical and numerical problems
10 Steps to Solving a Programming Problem
1. Read the problem at least three times (or however many makes you feel comfortable)
You can’t solve a problem you don’t understand. There is a difference between the problem and the problem you think you are solving. It’s easy to start reading the first few lines in a problem and assume the rest of it because it’s similar to something you’ve seen in the past. If you are making even a popular game like Hangman, be sure to read through any rules even if you’ve played it before. I once was asked to make a game like Hangman that I realized was “Evil Hangman” only after I read through the instructions (it was a trick!).
Sometimes I’ll even try explaining the problem to a friend and see if her understanding of my explanation matches the problem I am tasked with. You don’t want to find out halfway through that you misunderstood the problem. Taking extra time in the beginning is worth it. The better you understand the problem, the easier it will be to solve it.
Let’s pretend we are creating a simple function selectEvenNumbers that will take in an array of numbers and return an array evenNumbers of only even numbers. If there are no even numbers, return the empty array evenNumbers.
Function selectEvenNumbers() {
// your code here
}
Here are some questions that run through my mind:
- How can a computer tell what is an even number? Divide that number by 2 and see if its remainder is 0.
- What am I passing into this function? An array
- What will that array contain? One or more numbers
- What are the data types of the elements in the array? Numbers
- What is the goal of this function? What am I returning at the end of this function? The goal is to take all the even numbers and return them in an array. If there are no even numbers, return an empty array.
2. Work through the problem manually with at least three sets of sample data
Take out a piece of paper and work through the problem manually. Think of at least three sets of sample data you can use. Consider corner and edge cases as well.
Corner case: a problem or situation that occurs outside of normal operating parameters, specifically when multiple environmental variables or conditions are simultaneously at extreme levels, even though each parameter is within the specified range for that parameter.
Edge case: problem or situation that occurs only at an extreme (maximum or minimum) operating parameter
For example, below are some sets of sample data to use:
[1]
[1, 2]
[1, 2, 3, 4, 5, 6]
[-200.25]
[-800.1, 2000, 3.1, -1000.25, 42, 600]
When you are first starting out, it is easy to gloss over the steps. Because your brain may already be familiar with even numbers, you may just look at a sample set of data and pull out numbers like2 , 4 , 6 and so forth in the array without fully being aware of each and every step your brain is taking to solve it. If this is challenging, try using large sets of data as it will override your brain’s ability to naturally solve the problem just by looking at it. That helps you work through the real algorithm.
Let’s go through the first array [1]
- Look at the only element in the array [1]
- Decide if it is even. It is not
- Notice that there are no more elements in this array
- Determine there are no even numbers in this provided array
- Return an empty array
Let’s go through the array [1, 2]
- Look at the first element in array [1, 2]
- It is 1
- Decide if it is even. It is not
- Look at the next element in the array
- It is 2
- Decide if it is even. It is even
- Make an array evenNumbers and add 2 to this array
- Notice that there are no more elements in this array
- Return the array evenNumbers which is [2]
I go through this a few more times. Notice how the steps I wrote down for [1] varies slightly from [1, 2]. That is why I try to go through a couple of different sets. I have some sets with just one element, some with floats instead of just integers, some with multiple digits in an element, and some with negatives just to be safe.
3. Simplify and optimize your steps
Look for patterns and see if there’s anything you can generalize. See if you can reduce any steps or if you are repeating any steps.
- Create a function selectEvenNumbers
- Create a new empty array evenNumbers where I store even numbers, if any
- Go through each element in the array [1, 2]
- Find the first element
- Decide if it is even by seeing if it is divisible by 2. If it is even, I add that to evenNumbers
- Find the next element
- Repeat step #4
- Repeat step #5 and #4 until there are no more elements in this array
- Return the array evenNumbers, regardless of whether it has anything in it
- Show it is true for n = 1, n = 2, ...
- Suppose it is true for n = k
- Prove it is true for n = k + 1
Example of pseudocode
4. Write pseudocode
Even after you’ve worked out general steps, writing out pseudocode that you can translate into code will help with defining the structure of your code and make coding a lot easier. Write pseudocode line by line. You can do this either on paper or as comments in your code editor. If you’re starting out and find blank screens to be daunting or distracting, I recommend doing it on paper.
Pseudocode generally does not actually have specific rules in particular but sometimes, I might end up including some syntax from a language just because I am familiar enough with an aspect of the programming language. Don’t get caught up with the syntax. Focus on the logic and steps.
For our problem, there are many different ways to do this. For example, you can use filter but for the sake of keeping this example as easy to follow along as possible, we will use a basic for loop for now (but we will use filter later when we refactor our code).
Here is an example of pseudocode that has more words:
Function selectEvenNumberscreate an array evenNumbers and set that equal to an empty arrayfor each element in that array
see if that element is even
if element is even (if there is a remainder when divided by 2)
add to that to the array evenNumbersreturn evenNumbers
Here is an example of pseudocode that has fewer words:
Function selectEvenNumbersevenNumbers = []for i = 0 to i = length of evenNumbers
if (element % 2 === 0)
add to that to the array evenNumbersreturn evenNumbers
Either way is fine as long as you are writing it out line-by-line and understand the logic on each line.
Refer back to the problem to make sure you are on track.
5. Translate pseudocode into code and debug
When you have your pseudocode ready, translate each line into real code in the language you are working on. We will use JavaScript for this example.
If you wrote it out on paper, type this up as comments in your code editor. Then replace each line in your pseudocode.
Then I call the function and give it some sample sets of data we used earlier. I use them to see if my code returns the results I want. You can also write tests to check if the actual output is equal to the expected output.
SelectEvenNumbers([1])
selectEvenNumbers([1, 2])
selectEvenNumbers([1, 2, 3, 4, 5, 6])
selectEvenNumbers([-200.25])
selectEvenNumbers([-800.1, 2000, 3.1, -1000.25, 42, 600])
I generally use console.log() after each variable or line or so. This helps me check if the values and code are behaving as expected before I move on. By doing this, I catch any issues before I get too far. Below is an example of what values I would check when I am first starting out. I do this throughout my code as I type it out.
Function selectEvenNumbers(arrayofNumbers) {let evenNumbers = []
console.log(evenNumbers) // I remove this after checking output
console.log(arrayofNumbers) // I remove this after checking output}
After working though each line of my pseudocode, below is what we end up with. // is what the line was in pseudocode. Text that is bolded is the actual code in JavaScript.
// function selectEvenNumbers
function selectEvenNumbers(arrayofNumbers) {// evenNumbers = []
let evenNumbers = []// for i = 0 to i = length of evenNumbers
for (var i = 0; i < arrayofNumbers.length; i++) {// if (element % 2 === 0)
if (arrayofNumbers[i] % 2 === 0) {// add to that to the array evenNumbers
evenNumbers.push(arrayofNumbers[i])
}
}// return evenNumbers
return evenNumbers
}
I get rid of the pseudocode to avoid confusion.
Function selectEvenNumbers(arrayofNumbers) {
let evenNumbers = []for (var i = 0; i < arrayofNumbers.length; i++) {
if (arrayofNumbers[i] % 2 === 0) {
evenNumbers.push(arrayofNumbers[i])
}
}return evenNumbers
}
Sometimes new developers will get hung up with the syntax that it becomes difficult to move forward. Remember that syntax will come more naturally over time and there is no shame in referencing material for the correct syntax later on when coding.
6. Simplify and optimize your code
You’ve probably noticed by now that simplifying and optimizing are recurring themes.
“Simplicity is prerequisite for reliability.”
In this example, one way of optimizing it would be to filter out items from an array by returning a new array using filter. This way, we don’t have to define another variable evenNumbers because filter will return a new array with copies of elements that match the filter. This will not change the original array. We also don’t need to use a for loop with this approach. Filter will go through each item, return either true, to have that element in the array, or false to skip it.
Function selectEvenNumbers(arrayofNumbers) {
let evenNumbers = arrayofNumbers.filter(n => n % 2 === 0)
return evenNumbers
}
Simplifying and optimizing your code may require you to iterate a few times, identifying ways to further simplify and optimize code.
Here are some questions to keep in mind:
- What are your goals for simplifying and optimizing? The goals will depend on your team’s style or your personal preference. Are you trying to condense the code as much as possible? Is the goal to make it the code more readable? If that’s the case, you may prefer taking that extra line to define the variable or compute something rather than trying to define and compute all in one line.
- How else can you make the code more readable?
- Are there any more extra steps you can take out?
- Are there any variables or functions you ended up not even needing or using?
- Are you repeating some steps a lot? See if you can define in another function.
- Are there better ways to handle edge cases?
“Programs must be written for people to read, and only incidentally for machines to execute.”
7. Debug
This step really should be throughout the process. Debugging throughout will help you catch any syntax errors or gaps in logic sooner rather than later. Take advantage of your Integrated Development Environment (IDE) and debugger. When I encounter bugs, I trace the code line-by-line to see if there was anything that did not go as expected. Here are some techniques I use:
- Check the console to see what the error message says. Sometimes it’ll point out a line number I need to check. This gives me a rough idea of where to start, although the issue sometimes may not be at this line at all.
- Comment out chunks or lines of code and output what I have so far to quickly see if the code is behaving how I expected. I can always uncomment the code as needed.
- Use other sample data if there are scenarios I did not think of and see if the code will still work.
- Save different versions of my file if I am trying out a completely different approach. I don’t want to lose any of my work if I end up wanting to revert back to it!
“The most effective debugging tool is still careful thought, coupled with judiciously placed print statements.”
8. Write useful comments
You may not always remember what every single line meant a month later. And someone else working on your code may not know either. That’s why it’s important to write useful comments to avoid problems and save time later on if you need to come back to it.
Stay away from comments such as:
// This is an array. Iterate through it.
// This is a variable
I try to write brief, high-level comments that help me understand what’s going on if it is not obvious. This comes in handy when I am working on more complex problems. It helps understand what a particular function is doing and why. Through the use of clear variable names, function names, and comments, you (and others) should be able to understand:
- What is this code for?
- What is it doing?
9. Get feedback through code reviews
Get feedback from your teammates, professors, and other developers. Check out Stack Overflow. See how others tackled the problem and learn from them. There are sometimes several ways to approach a problem. Find out what they are and you’ll get better and quicker at coming up with them yourself.
10. Practice, practice, practice
Even experienced developers are always practicing and learning. If you get helpful feedback, implement it. Redo a problem or do similar problems. Keep pushing yourself. With each problem you solve, the better a developer you become. Celebrate each success and be sure to remember how far you’ve come. Remember that programming, like with anything, comes easier and more naturally with time.
FLOW CHART
Flow chart is defined as graphical representation of the logic for problem solving.
The purpose of flowchart is making the logic of the program clear in a visual representation.
Rules for drawing a flowchart
1. The flowchart should be clear, neat and easy to follow.
2. The flowchart must have a logical start and finish.
3. Only one flow line should come out from a process symbol.
4. Only one flow line should enter a decision symbol. However, two or three flow lines may leave the decision symbol.
5. Only one flow line is used with a terminal symbol.
6. Within standard symbols, write briefly and precisely.
7. Intersection of flow lines should be avoided.
Advantages of flowchart:
1. Communication: - Flowcharts are better way of communicating the logic of a system to all concerned.
2. Effective analysis: - With the help of flowchart, problem can be analysed in more effective way.
3. Proper documentation: - Program flowcharts serve as a good program documentation, which is needed for various purposes.
4. Efficient Coding: - The flowcharts act as a guide or blueprint during the systems analysis and program development phase.
5. Proper Debugging: - The flowchart helps in debugging process.
6. Efficient Program Maintenance: - The maintenance of operating program becomes easy with the help of flowchart. It helps the programmer to put efforts more efficiently on that part.
Disadvantages of flow chart:
1. Complex logic: - Sometimes, the program logic is quite complicated. In that case, flowchart becomes complex and clumsy.
2. Alterations and Modifications: - If alterations are required the flowchart may require re-drawing completely.
3. Reproduction: - As the flowchart symbols cannot be typed, reproduction of flowchart becomes a problem.
4. Cost: For large application the time and cost of flowchart drawing becomes costly.
PSEUDO CODE:
v Pseudo code consists of short, readable and formally styled English languages used for explain an algorithm.
v It does not include details like variable declaration, subroutines.
v It is easier to understand for the programmer or non-programmer to understand the general working of the program, because it is not based on any programming language.
v It gives us the sketch of the program before actual coding.
v It is not a machine readable
v Pseudo code can’t be compiled and executed.
v There is no standard syntax for pseudo code.
Guidelines for writing pseudo code:
v Write one statement per line
v Capitalize initial keyword
v Indent to hierarchy
v End multiline structure
v Keep statements language independent
Common keywords used in pseudocode
The following gives common keywords used in pseudocodes.
1. //: This keyword used to represent a comment.
2. BEGIN,END: Begin is the first statement and end are the last statement.
3. INPUT, GET, READ: The keyword is used to inputting data.
4. COMPUTE, CALCULATE: used for calculation of the result of the given expression. 5. ADD, SUBTRACT, INITIALIZE used for addition, subtraction and initialization.
6. OUTPUT, PRINT, DISPLAY: It is used to display the output of the program.
7. IF, ELSE, ENDIF: used to make decision.
8. WHILE, ENDWHILE: used for iterative statements.
9. FOR, ENDFOR: Another iterative incremented/decremented tested automatically.
Syntax for if else:
IF (condition)THEN
Statement
...
ELSE
Statement
...
ENDIF
Example: Greates of two numbers
BEGIN
READ a,b
IF (a>b) THEN
DISPLAY a is greater
ELSE
DISPLAY b is greater
END IF
END
Syntax for:
FOR( start-value to end-value) DO
Statement
...
ENDFOR
Example: Print n natural numbers
BEGIN
GET n
INITIALIZE i=1
FOR (i<=n) DO
PRINT i
i=i+1
ENDFOR
END
Syntax for A while:
WHILE (condition) DO
Statement
...
ENDWHILE
Example: Print n natural numbers
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i
i=i+1
ENDWHILE
END
Advantages:
v Pseudo is independent of any language; it can be used by most programmers.
v It is easy to translate pseudo code into a programming language.
v It can be easily modified as compared to flowchart.
v Converting a pseudo code to programming language is very easy as compared with converting a flowchart to programming language.
Disadvantages:
v It does not provide visual representation of the program’s logic.
v There are no accepted standards for writing pseudo codes.
v It cannot be compiled nor executed.
v for a beginner, it is more difficult to follow the logic or write pseudo code as compared to flowchart.
Example:
Addition of two numbers:
BEGIN
GET a,b
ADD c=a+b
PRINT c
END
Examples algorithms: pseudo code, flow chart, programming language
Write an algorithm to find area of a rectangle
Step 1: Start
Step 2: get l,b values
Step 3: Calculate A=l*b
Step 4: Display A
Step 5: Stop
BEGIN
READ l,b
CALCULATE A=l*b
DISPLAY A
END
Write an algorithm for Calculating area and circumference of circle
Step 1: Start
Step 2: get r value
Step 3: Calculate A=3.14*r*r
Step 4: Calculate C=2.3.14*r
Step 5: Display A,C
Step 6: Stop
BEGIN
READ r
CALCULATE A and C
A=3.14*r*r
C=2*3.14*r
DISPLAY A
END
Write an algorithm for Calculating simple interest
Step 1: Start
Step 2: get P, n, r value
Step3:Calculate
SI=(p*n*r)/100
Step 4: Display S
Step 5: Stop
BEGIN
READ P, n, r
CALCULATE S
SI=(p*n*r)/100
DISPLAY SI
END
Write an algorithm for Calculating engineering cutoff
Step 1: Start
Step2: get P,C,M value
Step3:calculate
Cutoff= (P/4+C/4+M/2)
Step 4: Display Cutoff
Step 5: Stop
BEGIN
READ P,C,M
CALCULATE
Cutoff= (P/4+C/4+M/2)
DISPLAY Cutoff
END
To check greatest of two numbers
Step 1: Start
Step 2: get a,b value
Step 3: check if(a>b) print a is greater
Step 4: else b is greater
Step 5: Stop
BEGIN
READ a,b
IF (a>b) THEN
DISPLAY a is greater
ELSE
DISPLAY b is greater
END IF
END
To check leap year or not
Step 1: Start
Step 2: get y
Step 3: if(y%4==0) print leap year
Step 4: else print not leap year
Step 5: Stop
BEGIN
READ y
IF (y%4==0) THEN
DISPLAY leap year
ELSE
DISPLAY not leap year
END IF
END
To check positive or negative number
Step 1: Start
Step 2: get num
Step 3: check if(num>0) print a is positive
Step 4: else num is negative
Step 5: Stop
BEGIN
READ num
IF (num>0) THEN
DISPLAY num is positive
ELSE
DISPLAY num is negative
END IF
END
To check odd or even number
Step 1: Start
Step 2: get num
Step 3: check if(num%2==0) print num is even
Step 4: else num is odd
Step 5: Stop
BEGIN
READ num
IF (num%2==0) THEN
DISPLAY num is even
ELSE
DISPLAY num is odd
END IF
END
To check greatest of three numbers
Step1: Start
Step2: Get A, B, C
Step3: if(A>B) goto Step4 else goto step5
Step4: If(A>C) print A else print C
Step5: If(B>C) print B else print C
Step6: Stop
BEGIN
READ a, b, c
IF (a>b) THEN
IF(a>c) THEN
DISPLAY a is greater
ELSE
DISPLAY c is greater
END IF
ELSE
IF(b>c) THEN
DISPLAY b is greater
ELSE
DISPLAY c is greater
END IF
END IF
END
Write an algorithm to check whether given number is +ve, -ve or zero.
Step 1: Start
Step 2: Get n value.
Step 3: if (n ==0) print “Given number is Zero” Else goto step4
Step 4: if (n > 0) then Print “Given number is +ve”
Step 5: else Print “Given number is -ve”
Step 6: Stop
BEGIN
GET n
IF(n==0) THEN
DISPLAY “ n is zero”
ELSE
IF(n>0) THEN
DISPLAY “n is positive”
ELSE
DISPLAY “n is positive”
END IF
END IF
END
Write an algorithm to print all-natural numbers up to n
Step 1: Start
Step 2: get n value.
Step 3: initialize i=1
Step 4: if (i<=n) go to step 5 else go to step 8
Step 5: Print i value
Step 6 : increment i value by 1
Step 7: go to step 4
Step 8: Stop
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i
i=i+1
ENDWHILE
END
Write an algorithm to print n odd numbers
Step 1: start
Step 2: get n value
Step 3: set initial value i=1
Step 4: check if(i<=n) goto step 5 else goto step 8
Step 5: print i value
Step 6: increment i value by 2
Step 7: goto step 4
Step 8: stop
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i
i=i+2
ENDWHILE
END
Write an algorithm to print n even numbers
Step 1: start
Step 2: get n value
Step 3: set initial value i=2
Step 4: check if(i<=n) goto step 5 else goto step8
Step 5: print i value
Step 6: increment i value by 2
Step 7: goto step 4
Step 8: stop
BEGIN
GET n
INITIALIZE i=2
WHILE(i<=n) DO
PRINT i
i=i+2
ENDWHILE
END
Write an algorithm to print squares of a number
Step 1: start
Step 2: get n value
Step 3: set initial value i=1
Step 4: check i value if(i<=n) goto step 5 else goto step8
Step 5: print i*i value
Step 6: increment i value by 1
Step 7: goto step 4
Step 8: stop
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i*i
i=i+2
ENDWHILE
END
Write an algorithm to print to print cubes of a number
Step 1: start
Step 2: get n value
Step 3: set initial value i=1
Step 4: check i value if(i<=n) goto step 5 else goto step8
Step 5: print i*i *i value
Step 6: increment i value by 1
Step 7: goto step 4
Step 8: stop
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i*i*i
i=i+2
ENDWHILE
END
Write an algorithm to find sum of a given number
Step 1: start
Step 2: get n value
Step 3: set initial value i=1, sum=0
Step 4: check i value if(i<=n) goto step 5 else goto step8
Step 5: calculate sum=sum+i
Step 6: increment i value by 1
Step 7: goto step 4
Step 8: print sum value
Step 9: stop
BEGIN
GET n
INITIALIZE i=1,sum=0
WHILE(i<=n) DO
Sum=sum+i
i=i+1
ENDWHILE
PRINT sum
END
Write an algorithm to find factorial of a given number
Step 1: start
Step 2: get n value
Step 3: set initial value i=1, fact=1
Step 4: check i value if(i<=n) goto step 5 else goto step8
Step 5: calculate fact=fact*i
Step 6: increment i value by 1
Step 7: goto step 4
Step 8: print fact value
Step 9: stop
BEGIN
GET n
INITIALIZE i=1,fact=1
WHILE(i<=n) DO
Fact=fact*i
i=i+1
ENDWHILE
PRINT fact
END
Tokens are the smallest elements of a program, which are meaningful to the compiler.
The following are the types of tokens: Keywords, Identifiers, Constant, Strings, Operators, etc.
Let us begin with Keywords.
Keywords
Keywords are predefined, reserved words in C and each of which is associated with specific features. These words help us to use the functionality of C language. They have special meaning to the compilers.
There are total 32 keywords in C.
Auto | Double | Int | Struct |
Break | Else | Long | Switch |
Case | Enum | Register | Typedef |
Char | Extern | Return | Union |
Continue | For | Signed | Void |
Do | If | Static | While |
Default | Goto | Sizeof | Volatile |
Const | Float | Short | Unsigned |
Identifiers
Each program element in C programming is known as an identifier. They are used for naming of variables, functions, array etc. These are user-defined names which consist of alphabets, number, underscore ‘_’. Identifier’s name should not be same or same as keywords. Keywords are not used as identifiers.
Rules for naming C identifiers −
- It must begin with alphabets or underscore.
- Only alphabets, numbers, underscore can be used, no other special characters, punctuations are allowed.
- It must not contain white-space.
- It should not be a keyword.
- It should be up to 31 characters long.
Constants and variables
Constants
Its value is fixed throughout the program that means constants are those variables which value is not changed throughout the program.
C constants can be divided into two major categories:
- Primary Constants
- Secondary Constants
There are two simple ways in C to define constants:
1. Using#define
e.g.
#include <stdio.h>
#define value 10
Void main() {
Int data;
Data = value*value;
Printf("value of data : %d",data);
}
Output
value of data : 100
2. Using const keyword
e.g.
#include <stdio.h>
Void main() {
Const int value = 10;
Int data;
Data =value*value;
Printf("value of data : %d",value);
}
Output
value of data : 100
Variables
Variable is used to store the value. As name indicates its value can be changed or also it can be reused many times.
Syntax
Data type variable_name;
e.g.
Int a;
Where a is the variables.
There are many types of variables in c:
- Local variable
- Global variable
- Static variable
- External variable
- Automatic variable
1. Local variable – A variable which is declared inside the function is known as local variable. It is used only inside the function in which it is declared.
2. Global variable – A variable which is declared outside the function is known as global variable. It can be used throughout the program.
3. Static variable – It is used to retain its value between multiple function calls. It is declared using static keyword.
4. External variable – You can share a variable in multiple C source files by using external variable. It is declared using extern keyword.
5. Automatic variable – Variable which is declared inside the block is known as automatic variable by default.
Data Types
A data type specifies the type of data that a variable can store such as integer, floating, character, etc.
There are the following data types in C language.
Types | Data Types |
Basic Data Type | Int, char, float, double |
Derived Data Type | Array, pointer, structure, union |
Enumeration Data Type | Enum |
Void Data Type | Void |
Basic Data Types
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 |
Char | 1 byte | −128 to 127 |
Signed char | 1 byte | −128 to 127 |
Unsigned char | 1 byte | 0 to 255 |
Short | 2 byte | −32,768 to 32,767 |
Signed short | 2 byte | −32,768 to 32,767 |
Unsigned short | 2 byte | 0 to 65,535 |
Int | 2 byte | −32,768 to 32,767 |
Signed int | 2 byte | −32,768 to 32,767 |
Unsigned int | 2 byte | 0 to 65,535 |
Short int | 2 byte | −32,768 to 32,767 |
Signed short int | 2 byte | −32,768 to 32,767 |
Unsigned short int | 2 byte | 0 to 65,535 |
Long int | 4 byte | -2,147,483,648 to 2,147,483,647 |
Signed long int | 4 byte | -2,147,483,648 to 2,147,483,647 |
Unsigned long int | 4 byte | 0 to 4,294,967,295 |
Float | 4 byte |
|
Double | 8 byte |
|
Long double | 10 byte |
|
A header file is a file with extension .h which contains C function declarations and macro definitions to be shared between several source files. There are two types of header files: the files that the programmer writes and the files that comes with your compiler.
You request to use a header file in your program by including it with the C pre-processing directive #include, like you have seen inclusion of stdio.h header file, which comes along with your compiler.
Including a header file is equal to copying the content of the header file but we do not do it because it will be error-prone and it is not a good idea to copy the content of a header file in the source files, especially if we have multiple source files in a program.
A simple practice in C or C++ programs is that we keep all the constants, macros, system wide global variables, and function prototypes in the header files and include that header file wherever it is required.
Include Syntax
Both the user and the system header files are included using the pre-processing directive #include. It has the following two forms −
#include <file>
This form is used for system header files. It searches for a file named 'file' in a standard list of system directories. You can prepend directories to this list with the -I option while compiling your source code.
#include "file"
This form is used for header files of your own program. It searches for a file named 'file' in the directory containing the current file. You can prepend directories to this list with the -I option while compiling your source code.
Include Operation
The #include directive works by directing the C pre-processor to scan the specified file as input before continuing with the rest of the current source file. The output from the pre-processor contains the output already generated, followed by the output resulting from the included file, followed by the output that comes from the text after the #include directive. For example, if you have a header file header.h as follows −
Char *test (void);
And a main program called program.c that uses the header file, like this −
Int x;
#include "header.h"
Int main (void) {
Puts (test ());
}
The compiler will see the same token stream as it would if program.c read.
Int x;
Char *test (void);
Int main (void) {
Puts (test ());
}
Once-Only Headers
If a header file happens to be included twice, the compiler will process its contents twice and it will result in an error. The standard way to prevent this is to enclose the entire real contents of the file in a conditional, like this −
#ifndef HEADER_FILE
#define HEADER_FILE
The entire header files
#endif
This construct is commonly known as a wrapper #ifndef. When the header is included again, the conditional will be false, because HEADER_FILE is defined. The pre-processor will skip over the entire contents of the file, and the compiler will not see it twice.
Computed Includes
Sometimes it is necessary to select one of the several different header files to be included into your program. For instance, they might specify configuration parameters to be used on different sorts of operating systems. You could do this with a series of conditionals as follows −
#if SYSTEM_1
# include "system_1.h"
#elif SYSTEM_2
# include "system_2.h"
#elif SYSTEM_3
...
#endif
But as it grows, it becomes tedious, instead the pre-processor offers the ability to use a macro for the header name. This is called a computed include. Instead of writing a header name as the direct argument of #include, you simply put a macro name there −
#define SYSTEM_H "system_1.h"
...
#include SYSTEM_H
SYSTEM_H will be expanded, and the pre-processor will look for system_1.h as if the #include had been written that way originally. SYSTEM_H could be defined by your Makefile with a -D option.
Data input-output
When we say Input, it means to feed some data into a program. An input can be given in the form of a file or from the command line. C programming provides a set of built-in functions to read the given input and feed it to the program as per requirement.
When we say Output, it means to display some data on screen, printer, or in any file. C programming provides a set of built-in functions to output the data on the computer screen as well as to save it in text or binary files.
The Standard Files
C programming treats all the devices as files. So, devices such as the display are addressed in the same way as files and the following three files are automatically opened when a program executes to provide access to the keyboard and screen.
Standard File | File Pointer | Device |
Standard input | Stdin | Keyboard |
Standard output | Stdout | Screen |
Standard error | Stderr | Your screen |
The file pointers are the means to access the file for reading and writing purpose. This section explains how to read values from the screen and how to print the result on the screen.
The getchar() and putchar() Functions
The int getchar(void) function reads the next available character from the screen and returns it as an integer. This function reads only single character at a time. You can use this method in the loop in case you want to read more than one character from the screen.
The int putchar(int c) function puts the past character on the screen and returns the same character. This function puts only single character at a time. You can use this method in the loop in case you want to display more than one character on the screen. Check the following example −
#include <stdio.h>
Int main( ) {
Int c;
Printf( "Enter a value :");
c = getchar( );
Printf( "\nYou entered: ");
Putchar( c );
Return 0;
}
When the above code is compiled and executed, it waits for you to input some text. When you enter a text and press enter, then the program proceeds and reads only a single character and displays it as follows −
$./a.out
Enter a value : this is test
You entered: t
The gets() and puts() Functions
The char *gets(char *s) function reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF (End of File).
The int puts(const char *s) function writes the string 's' and 'a' trailing newline to stdout.
NOTE: Though it has been deprecated to use gets() function, instead of using gets, you want to use fgets().
#include <stdio.h>
Int main( ) {
Char str[100];
Printf( "Enter a value :");
Gets( str );
Printf( "\nYou entered: ");
Puts( str );
Return 0;
}
When the above code is compiled and executed, it waits for you to input some text. When you enter a text and press enter, then the program proceeds and reads the complete line till end, and displays it as follows −
$./a.out
Enter a value : this is test
You entered: this is test
The scanf() and printf() Functions
The int scanf(const char *format, ...) function reads the input from the standard input stream stdin and scans that input according to the format provided.
The int printf(const char *format, ...) function writes the output to the standard output stream stdout and produces the output according to the format provided.
The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc., to print or read strings, integer, character or float respectively. There are many other formatting options available which can be used based on requirements. Let us now proceed with a simple example to understand the concepts better −
#include <stdio.h>
Int main( ) {
Char str[100];
Int i;
Printf( "Enter a value :");
Scanf("%s %d", str, &i);
Printf( "\nYou entered: %s %d ", str, i);
Return 0;
}
When the above code is compiled and executed, it waits for you to input some text. When you enter a text and press enter, then program proceeds and reads the input and displays it as follows −
$./a.out
Enter a value : seven 7
You entered: seven 7
Here, it should be noted that scanf() expects input in the same format as you provided %s and %d, which means you have to provide valid inputs like "string integer". If you provide "string" or "integer", then it will be assumed as wrong input. Secondly, while reading a string, scanf() stops reading as soon as it encounters a space, so "this is test" are three strings for scanf().
Character input and output
Input means to provide the program with some data to be used in the program and Output means to display data on screen or write the data to a printer or a file.
C programming language provides many built-in functions to read any given input and to display data on screen when there is a need to output the result.
In this tutorial, we will learn about such functions, which can be used in our program to take input from user and to output the result on screen.
All these built-in functions are present in C header files, we will also specify the name of header files in which a particular function is defined while discussing about it.
Scanf() and printf() functions
The standard input-output header file, named stdio.h contains the definition of the functions printf() and scanf(), which are used to display output on screen and to take input from user respectively.
#include<stdio.h>
Void main()
{
// defining a variable
Int i;
/*
Displaying message on the screen
Asking the user to input a value
*/
Printf("Please enter a value...");
/*
Reading the value entered by the user
*/
Scanf("%d", &i);
/*
Displaying the number as output
*/
Printf( "\nYou entered: %d", i);
}
When you will compile the above code, it will ask you to enter a value. When you will enter the value, it will display the value you have entered on screen.
You must be wondering what is the purpose of %d inside the scanf() or printf() functions. It is known as format string and this informs the scanf() function, what type of input to expect and in printf() it is used to give a heads up to the compiler, what type of output to expect.
Format String | Meaning |
%d | Scan or print an integer as signed decimal number |
%f | Scan or print a floating-point number |
%c | To scan or print a character |
%s | To scan or print a character string. The scanning ends at whitespace. |
We can also limit the number of digits or characters that can be input or output, by adding a number with the format string specifier, like "%1d" or "%3s", the first one means a single numeric digit and the second one means 3 characters, hence if you try to input 42, while scanf() has "%1d", it will take only 4 as input. Same is the case for output.
In C Language, computer monitor, printer etc output devices are treated as files and the same process is followed to write output to these devices as would have been followed to write the output to a file.
NOTE : printf() function returns the number of characters printed by it, and scanf() returns the number of characters read by it.
Int i = printf("studytonight");
In this program printf("studytonight"); will return 12 as result, which will be stored in the variable i, because studytonight has 12 characters.
Getchar() & putchar() functions
The getchar() function reads a character from the terminal and returns it as an integer. This function reads only single character at a time. You can use this method in a loop in case you want to read more than one character. The putchar() function displays the character passed to it on the screen and returns the same character. This function too displays only a single character at a time. In case you want to display more than one characters, use putchar() method in a loop.
#include <stdio.h>
Void main( )
{
Int c;
Printf("Enter a character");
/*
Take a character as input and
Store it in variable c
*/
c = getchar();
/*
Display the character stored
In variable c
*/
Putchar(c);
}
When you will compile the above code, it will ask you to enter a value. When you will enter the value, it will display the value you have entered.
Gets() & puts() functions
The gets() function reads a line from stdin(standard input) into the buffer pointed to by str pointer, until either a terminating newline or EOF (end of file) occurs. The puts() function writes the string str and a trailing newline to stdout.
Str → This is the pointer to an array of chars where the C string is stored. (Ignore if you are not able to understand this now.)
#include<stdio.h>
Void main()
{
/* character array of length 100 */
Char str[100];
Printf("Enter a string");
Gets( str );
Puts( str );
Getch();
}
When you will compile the above code, it will ask you to enter a string. When you will enter the string, it will display the value you have entered.
Difference between scanf() and gets()
The main difference between these two functions is that scanf() stops reading characters when it encounters a space, but gets() reads space as character too.
If you enter name as Study Tonight using scanf() it will only read and store Study and will leave the part after space. But gets() function will read it completely.
String input and output
String Input: Read a String
When writing interactive programs which ask the user for input, C provides the scanf(), gets(), and fgets() functions to find a line of text entered from the user.
When we use scanf() to read, we use the "%s" format specifier without using the "&" to access the variable address because an array name acts as a pointer. For example:
#include <stdio.h>
Int main() {
Char name[10];
Int age;
Printf("Enter your first name and age: \n");
Scanf("%s %d", name, &age);
Printf("You entered: %s %d",name,age);
}
Output:
Enter your first name and age:
John_Smith 48
The problem with the scanf function is that it never reads an entire string. It will halt the reading process as soon as whitespace, form feed, vertical tab, newline or a carriage return occurs. Suppose we give input as "Guru99 Tutorials" then the scanf function will never read an entire string as a whitespace character occurs between the two names. The scanf function will only read Guru99.
In order to read a string contains spaces, we use the gets() function. Gets ignores the whitespaces. It stops reading when a newline is reached (the Enter key is pressed).For example:
#include <stdio.h>
Int main() {
Char full_name[25];
Printf("Enter your full name: ");
Gets(full_name);
Printf("My full name is %s ",full_name);
Return 0;
}
Output:
Enter your full name: Dennis Ritchie
My full name is Dennis Ritchie
Another safer alternative to gets() is fgets() function which reads a specified number of characters. For example:
#include <stdio.h>
Int main() {
Char name[10];
Printf("Enter your name plz: ");
Fgets(name, 10, stdin);
Printf("My name is %s ",name);
Return 0;}
Output:
Enter your name plz: Carlos
My name is Carlos
The fgets() arguments are :
- The string name,
- The number of characters to read,
- Stdin means to read from the standard input which is the keyboard.
String Output: Print/Display a String
The standard printf function is used for printing or displaying a string on an output device. The format specifier used is %s
Example,
Printf("%s", name);
String output is done with the fputs() and printf() functions.
Fputs() function
The fputs() needs the name of the string and a pointer to where you want to display the text. We use stdout which refers to the standard output in order to print to the screen.For example:
#include <stdio.h>
Int main()
{char town[40];
Printf("Enter your town: ");
Gets(town);
Fputs(town, stdout);
Return 0;}
Output:
Enter your town: New York
New York
Puts function
The puts function prints the string on an output device and moves the cursor back to the first position. A puts function can be used in the following way,
#include <stdio.h>
Int main() {
Char name[15];
Gets(name); //reads a string
Puts(name); //displays a string
Return 0;}
The syntax of this function is comparatively simple than other functions.
Formatted input and output
C language provides us console input/output functions. As the name says, the console input/output functions allow us to -
- Read the input from the keyboard by the user accessing the console.
- Display the output to the user at the console.
Note : These input and output values could be of any primitive data type.
There are two kinds of console input/output functions -
- Formatted input/output functions.
- Unformatted input/output functions.
Formatted input/output functions
Formatted console input/output functions are used to take one or more inputs from the user at console and it also allows us to display one or multiple values in the output to the user at the console.
Some of the most important formatted console input/output functions are -
Functions | Description |
Scanf() |
|
Printf() |
|
Sscanf() |
|
Sprintf() |
|
Format specifiers in console formatted I/O functions
Some of the most commonly used format specifiers used in console formatted input/output functions are displayed in the table below -
Format Specifiers | Description |
%hi |
|
%hu |
|
%d |
|
%u |
|
%ld |
|
%lu |
|
%c |
|
%c |
|
%f |
|
%lf |
|
%Lf |
|
%s |
|
Optional specifiers within a format specifier
We could specify two more optional specifiers within each format specifier, such as integer value and a sign.
An integer value specifies the number of columns used on the screen for printing a value i.e. width. This integer value may or may not have a minus sign before it.
- A (-)minus sign before the integer value means left justification of the value to be printed on the screen and integer value following the minus sign is the number of blanks on its right.
- No minus sign before the integer value means right justification of the value to be printed on the screen and integer value specifies the number of blanks on its left.
What is a compilation?
The compilation is a process of converting the source code into object code. It is done with the help of the compiler. The compiler checks the source code for the syntactical or structural errors, and if the source code is error-free, then it generates the object code.
The c compilation process converts the source code taken as input into the object code or machine code. The compilation process can be divided into four steps, i.e., Pre-processing, Compiling, Assembling, and Linking.
The pre-processor takes the source code as an input, and it removes all the comments from the source code. The pre-processor takes the pre-processor directive and interprets it. For example, if <stdio.h>, the directive is available in the program, then the pre-processor interprets the directive and replace this directive with the content of the 'stdio.h' file.
The following are the phases through which our program passes before being transformed into an executable form:
- Pre-processor
- Compiler
- Assembler
- Linker
Pre-processor
The source code is the code which is written in a text editor and the source code file is given an extension ".c". This source code is first passed to the pre-processor, and then the pre-processor expands this code. After expanding the code, the expanded code is passed to the compiler.
Compiler
The code which is expanded by the pre-processor is passed to the compiler. The compiler converts this code into assembly code. Or we can say that the C compiler converts the pre-processed code into assembly code.
Assembler
The assembly code is converted into object code by using an assembler. The name of the object file generated by the assembler is the same as the source file. The extension of the object file in DOS is '.ob.,' and in UNIX, the extension is 'o'. If the name of the source file is 'hello.c', then the name of the object file would be 'hello.obj'.
Linker
Mainly, all the programs written in C use library functions. These library functions are pre-compiled, and the object code of these library files is stored with '.lib' (or '.a') extension. The main working of the linker is to combine the object code of library files with the object code of our program. Sometimes the situation arises when our program refers to the functions defined in other files; then linker plays a very important role in this. It links the object code of these files to our program. Therefore, we conclude that the job of the linker is to link the object code of our program with the object code of the library files and other files. The output of the linker is the executable file. The name of the executable file is the same as the source file but differs only in their extensions. In DOS, the extension of the executable file is '.exe', and in UNIX, the executable file can be named as 'a.out'. For example, if we are using printf() function in a program, then the linker adds its associated code in an output file.
Let's understand through an example.
Hello.c
- #include <stdio.h>
- Int main()
- {
- Printf("Hello javaTpoint");
- Return 0;
- }
Now, we will create a flow diagram of the above program:
In the above flow diagram, the following steps are taken to execute a program:
- Firstly, the input file, i.e., hello.c, is passed to the pre-processor, and the pre-processor converts the source code into expanded source code. The extension of the expanded source code would be hello.i.
- The expanded source code is passed to the compiler, and the compiler converts this expanded source code into assembly code. The extension of the assembly code would be hello.s.
- This assembly code is then sent to the assembler, which converts the assembly code into object code.
- After the creation of an object code, the linker creates the executable file. The loader will then load the executable file for the execution.
These errors can be categorized into five different types. These are like below −
- Syntax Error
- Run-Time Error
- Linker Error
- Logical Error
- Semantic Error
Let us see these errors one by one −
Syntax error
This kind of errors are occurred, when it violates the rule of C++ writing techniques or syntaxes. This kind of errors are generally indicated by the compiler before compilation. Sometimes these are known as compile time error.
In this example, we will see how to get syntax error if we do not put semicolon after one line.
Example
#include<stdio.h>
Main() {
Printf("Hello World")
}
Output
Error] expected ';' before '}' token
Rumtime error
This kind of errors are occurred, when the program is executing. As this is not compilation error, so the compilation will be successfully done. We can check this error if we try to divide a number with 0.
Example
#include<stdio.h>
Main() {
Int x = 52;
Int y = 0;
Printf("Div : %f", x/y);
}
Output
Program crashes during runtime.
Linker error
This kind of errors are occurred, when the program is compiled successfully, and trying to link the different object file with the main object file. When this error is occurred, the executable is not generated, For example some wrong function prototyping, incorrect header file etc. If the main() is written as Main(), this will generate linked error.
Example
#include<stdio.h>
Main() {
Int x = 52;
Int y = 0;
Printf("Div : %f", x/y);
}
Output
C:\crossdev\src\mingw-w64-v3-git\mingw-w64-crt\crt\crt0_c.cundefined reference to WinMain'
Logical error
Sometimes, we may not get the desired output. If the syntax and other things are correct, then also, we may not get correct output due to some logical issues. These are called the logical error. Sometimes, we put a semicolon after a loop, that is syntactically correct, but will create one blank loop. In that case, it will show desired output.
Example
#include<stdio.h>
Main() {
Int i;
For(i = 0; i<5; i++); {
Printf("Hello World");
}
}
Output
Here we want the line will be printed five times. But only one time it will be printed for the block of code.
Semantic error
This kind of error occurs when it is syntactically correct but has no meaning. This is like grammatical mistakes. If some expression is given at the left side of assignment operator, this may generate semantic error.
Example
#include<stdio.h>
Main() {
Int x, y, z;
x = 10;
y = 20;
x + y = z;
}
Output
[Error] lvalue required as left operand of assignment
Source code is the C program that you write in your editor and save with a ‘ .C ‘ extension. Which is un-compiled (when written for the first time or whenever a change is made in it and saved).
Object code is the output of a compiler after it processes the source code. The object code is usually a machine code, also called a machine language, which can be understood directly by a specific type of CPU (central processing unit), such as x86 (i.e., Intel-compatible) or PowerPC. However, some compilers are designed to convert source code into an assembly language or some other another programming language. An assembly language is a human-readable notation using the mnemonics (mnemonicis a symbolic name for a single executable machine language instruction called an opcode) in the ISA ( Instruction Set Architecture) of that particular CPU .
Executable (also called the Binary) is the output of a linker after it processes the object code. A machine code file can be immediately executable (i.e., runnable as a program), or it might require linking with other object code files (e.g. Libraries) to produce a complete executable program.
Arithmetic Expressions consist of numeric literals, arithmetic operators, and numeric variables. They simplify to a single value, when evaluated.
Here is an example of an arithmetic expression with no variables:
3.14*10*10
This expression evaluates to 314, the approximate area of a circle with radius 10. Similarly, the expression
3.14*radius*radius
Would also evaluate to 314, if the variable radius stored the value 10.
Note that the parentheses in the last expression helps dictate which order to evaluate the expression.
Multiplication and division have a higher order of precedence than addition and subtraction. In an arithmetic expression, it is evaluated left to right, only performing the multiplications and divisions.
After doing this, process the expression again from left to right, doing all the additions and subtractions.
So,
3+4*5
First evaluates to
3+20 which then evaluates to 23.
Consider this expression:
3 + 4*5 - 6/3*4/8 + 2*6 - 4*3*2
First go through and do all the multiplications and divisions:
3 + 20 - 1 + 12 - 24
Integer Division: In particular, if the division has a leftover remainder or fraction, this is simply discarded.
For example:
13/4 evaluates to 3
19/3 evaluates to 6 but
Similarly, if you have an expression with integer variables part of a division, this evaluates to an integer as well.
For example, in this segment of code, y gets set to 2.
Int x = 8;
Int y = x/3;
However, if we did the following,
Double x = 8;
Double y = x/3;
y would equal 2.66666666 (approximately).
The way C decides whether it will do an integer division (as in the first example), or a real number division (as in the second example), is based on the TYPE of the operands.
If both operands are ints, an integer division is done.
If either operand is a float or a double, then a real division is done. The compiler will treat constants without the decimal point as integers, and constants with the decimal point as a float. Thus, the expressions 13/4 and 13/4.0 will evaluate to 3 and 3.25 respectively.
The mod operator (%)
The one new operator is the mod operator, which is denoted by the percent sign(%). This operator is ONLY defined for integer operands. It is defined as follows:
a%b evaluates to the remainder of a divided by b.
For example,
12%5 = 2
19%6 = 1
14%7 = 0
19%200 = 19
The precedence of the mod operator is the same as the precedence of multiplication and division.
Every expression in C language contains set of operators and operands. Operators are the special symbols which are used to indicate the type of operation whereas operands are the data member or variables operating as per operation specified by operator. One expression contains one or more set of operators and operands. So, to avoid the ambiguity in execution of expression, C compiler fixed the precedence of operator. Depending on the operation, operators are classified into following category.
- Arithmetic Operator: These are the operators which are useful in performing mathematical calculations. Following are the list of arithmetic operator in C language. To understand the operation, assume variable A contains value 10 and variable contains value 5.
Sr. No. | Operator | Description | Example |
+ | Used to add two operands | Result of A+B is 15 | |
2. | - | Used to subtract two operands | Result of A-B is 5 |
3. | * | Used to multiply two operands | Result of A*B is 50 |
4. | / | Used to divide two operands | Result of A/B is 2 |
5. | % | Find reminder of the division of two operand | Result of A%B is 0 |
Example:
#include<stdio.h>
#include<conio.h>
Void main()
{
Int a,b,c;
Clrscr();
Printf("Enter two numbers");
Scanf("%d %d",&a,&b);
Printf("\n Result of addition of %d and %d is %d",a,b,a+b);
Printf("\n Result of subtraction of %d and %d is %d",a,b,a-b);
Printf("\n Result of multiplication %d and %d is %d",a,b,a*b);
Printf("\n Result of division of %d and %d is %d",a,b,a/b);
Printf("\n Result of modulus of %d and %d is %d",a,b,a%b);
Getch();
}
Output:
Enter two numbers
5
3
Result of addition of 5 and 3 is 8
Result of subtraction of 5 and 3 is 2
Result of multiplication of 5 and 3 is 15
Result of division of 5 and 3 is 1
Result of modulus of 5 and 3 is 2
2. Relational Operators: Relational operator used to compare two operands. Relational operator produce result in terms of binary values. It returns 1 when the result is true and 0 when result is false. Following are the list of relational operator in C language. To understand the operation, assume variable A contains value 10 and variable contains value 5.
Sr. No. | Operator | Description | Example |
1. | < | This is less than operator which is used to check whether the value of left operand is less than the value of right operand or not | Result of A<B is false
|
2. | > | This is greater than operator which is used to check whether the value of left operand is greater than the value of right operand or not | Result of A>B is true |
3. | <= | This is less than or equal to operator | Result of A<=B is false |
4. | >= | This is greater than or equal to operator | Result of A>=B is true |
5. | == | This is equal to operator which is used to check value of both operands are equal or not | Result of A==B is false |
6. | != | This is not equal to operator which is used to check value of both operands are equal or not | Result of A!=B is true |
Example:
#include<stdio.h>
#include<conio.h>
Void main()
{
Int a,b,c;
Clrscr();
Printf("Enter two numbers");
Scanf("%d %d",&a,&b);
Printf("\n Result of less than operator of %d and %d is %d",a,b,a<b);
Printf("\n Result of greater than operator of %d and %d is %d",a,b,a>b);
Printf("\n Result of leass than or equal to operator %d and %d is %d",a,b,a<=b);
Printf("\n Result of greater than or equal to operator of %d and %d is %d", a,b,a>=b);
Printf("\n Result of double equal to operator of %d and %d is %d",a,b,a==b);
Printf("\n Result of not equal to operator of %d and %d is %d",a,b,a!=b);
Getch();
}
Output:
Enter two numbers
5
3
Result of less than operator of 5 and 3 is 0
Result of greater than operator of 5 and 3 is 1
Result of less than or equal to operator of 5 and 3 is 0
Result of greater than or equal to operator of 5 and 3 is 1
Result of double equal to operator of 5 and 3 is 0
Result of not equal to operator of 5 and 3 is 1
Precedence and Associativity
Operator precedence determines the grouping of terms in an expression and decides how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has a higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Category | Operator | Associativity |
Postfix | () [] -> . ++ - - | Left to right |
Unary | + - ! ~ ++ - - (type)* & sizeof | Right to left |
Multiplicative | * / % | Left to right |
Additive | + - | Left to right |
Shift | << >> | Left to right |
Relational | < <= > >= | Left to right |
Equality | == != | Left to right |
Bitwise AND | & | Left to right |
Bitwise XOR | ^ | Left to right |
Bitwise OR | | | Left to right |
Logical AND | && | Left to right |
Logical OR | || | Left to right |
Conditional | ?: | Right to left |
Assignment | = += -= *= /= %=>>= <<= &= ^= |= | Right to left |
Comma | , | Left to right |
Example Code
#include <stdio.h>
Main() {
Int a = 20;
Int b = 10;
Int c = 15;
Int d = 5;
Int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
Printf("Value of (a + b) * c / d is : %d\n", e );
e = ((a + b) * c) / d; // (30 * 15 ) / 5
Printf("Value of ((a + b) * c) / d is : %d\n" , e );
e = (a + b) * (c / d); // (30) * (15/5)
Printf("Value of (a + b) * (c / d) is : %d\n", e );
e = a + (b * c) / d; // 20 + (150/5)
Printf("Value of a + (b * c) / d is : %d\n" , e );
Return 0;
}
Output
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50
Text Books:
1. Satinder Bal Gupta & Amit Singla, Fundamental of Computers and Programming in C, Shree Mahavir Book (Publishers), New Delhi
2. Ajay Mittal, Programming in C, ‘A Practical Approach’, Pearson Education.
3. Byron Gottfried, Schaum's Outline of Programming with C, McGraw-Hill
4. E. Balaguruswamy, Programming in ANSI C, Tata McGraw-Hill
5. YashavantKanetkar, Let Us C, BPB Publication.