Programming 1
Programming 1
2.2.2. Compiler
A compiler translates the entire high-level program into a machine language
Advantages of high-level languages
program. The high-level language program is called source program or
o easy to understand and write programs as they are user oriented
source code and the generated machine language program is called object
o they have built in libraries to perform routine tasks
program or object code. This process is called compilation. Some compilers
o programs can be ported to multiple hardware setups from same
convert high-level language into assembly language, then an assembler is
code
used to create the finished object code.
the machine language of the computer on which it will run. A language o Fast in execution
The Define Directive Examples of valid variable identifiers are: x, total, area_of_circle, x1, _a and
The “define directive” is used to define a symbolic constant which is assigned aX.
a value that will remain constant during the execution of the program. Its
general syntax is:
Remark! C is case sensitive, so the identifiers sum and SUM are different. o It provides the compiler with a list of the variables in a convenient
Same for total and Total. All key words must be in lower case. place so that it can cross check names and types for any errors.
c. The Function main( ) The body of the function main() is made up of program statements
The function main() indicates the beginning of the actual C program. It is the which represent instructions to be executed by the computer. An
point at which execution of program is started. When a C program is instruction may be an input/output statement, an arithmetic
executed, the execution control goes directly to the function main(). Every C statement, a control statement, a simple assignment statement or
program must have a function main(). The general syntax is: any other statement.
int main()
A basic C program looks like this:
{declaration of local variables;
program statements;
#include <header.h> #include <stdio.h>
return 0;
#define symbolic constant
}
Global declarations int main()
void main() {
The keyword “int” is used before the main() function to indicate the { local declarations printf(“Welcome to the world of
type of the value that is returned by the main() function. By definition, program instructions; C!”);
a function may accept no, one or more inputs and returns no or a } return 0;
single value. 'int' means that the program will return an integer value 2.5.2. Input/Output Statements
after its execution. The word “void” can be used in the place of “int” to
indicate that the program will not return any value. a. The scanf Function
It is good practice to always return a value because the operating scanf (print-formatted) is used to interpret characters input to the computer
system uses the return value to determine whether the program has and to store the interpretation in the specified variable(s).
been executed successfully or not.
Example:
The body of the main() function must be enclosed in braces (or curly scanf("%d", &x);
brackets { }). These braces are called delimiters. The left brace
indicates the start of the body of the function whereas the matching This statement reads a decimal integer from the keyboard and stores the
right brace indicates the end of the body of the function. Braces are value in the memory address of the variable x.
also used to indicate the beginning and ending of block (compound) In the statement,
statements. %d is a conversion specifier and specifies that the variable to be readis
of type integer. Other conversion specifiers used in C are %f for
floating point numbers, %c for characters and %s for strings.
c Character
&gives the address of something in memory. That is, it generates a d Decimal integer
pointer to the [Link] arguments to scanfmust be pointers f Normal floating point
(addresses), hence the need for &. s String
Scientific notation floating
b. The printf Function e
point
printf(print-formatted) is used to display information on the screen.
Examples:
Example: scanf(“%s”, &Name);
printf("The radius is %f cm",x); printf(“Name: %s”, Name);
scanf("%d %d",&x,&y);
in the statement, printf("The sum of %d and %d = %d",x,y,z);
“The radius is %f cm” is the control string. The text in between the
double quotes will be displayed except the conversion specifier %f. d. Character Input/Output
getchar and putchar are used for the input and output of single characters
x is the variable to be printed. The value of x will be printed where the respectively.
conversion specifier is placed in the control string. getchar() returns an int which is either EOF (indicating end-of-file) or the
next character in the standard input stream
Many conversion specifications can be used in a control string. In this case, putchar(c) puts the character c on the standard output stream
the programmer has to ensure that both the number of conversion
specifications and the number of variables to be printed are the same and, of #include<stdio.h>
the correct type specified. main()
{ char ch;
Example: ch=getchar();
printf(“The sum of %d and %d is %d”, x, y, x+y). printf(“%c”,ch);
}
If x=2 and y=3, then what will be displayed on the screen is: The sum of 2
and 3 is 5 2.5.3. Operators and Expressions
An operator is something which takes one or more values and does
c. Common Conversion Specifiers something useful with those values to produce a result. C has different types
of operators which can be arithmetic, relational, logical, assignment
Character Form of output operators etc.
An expression is simply the name for any string of operators, variables and c. Logical Operators
numbers. Logical operators are used to combine logical values.
b. Relational Operators Remark! Bitwise operators allow manipulation of the actual bits held in
Relational operators are used for comparisons. Expressions that use these each byte of a variable. Other bitwise operators are:
operators produce a true or false value when they are evaluated.
Right shift (>>) – binary division by 2
E.g. if a=¿ 0010111 then a >>¿ 0001011.
Opera Description Example
Also, a>>2 = 0000101
tor
Left shift (<<) – binary multiplication by 2
1. == Equal to If a == 2 and b== 5; a == b evaluates to FALSE
If a=¿ 0010111 then a <<¿ 0010110 .
2. < Less than a < b evaluates to TRUE
Also, a << 2 = 1011100
3. > Greater than a > 5 evaluates to FALSE
One’s complement (~)
Less than or b <= 5 evaluates to TRUE
4. <=
equal to
Greater or a >= 5 evaluates to FALSE
5. >= d. Assignment Operators
equal to
Assignment is the process of storing a value in a variable. The assignment
6. != Not equal to a != b evaluates to TRUE
operator is the equal sign (=).
bitwise XOR
For example:
pi=3.14 e. Increment and Decrement Operators
sum=∑ +1 Increment and decrement operators give a shorthand method of adding and
subtracting 1 from an object respectively.
The variable pi is assigned the value 3.14 and the variable sum is
++ Increment a ++≡ a=a+1
incremented by 1.
-- Decrement b-- ≡ b=b−1
C has different types of assignment operators.
Operat Description Example These operators can be prefix or postfix. With the prefix form the variable is
If the value of the variable equals ‘value1’, code segment1 is executed. Remark! If you need to select among a large group of values, a switch
Otherwise, if it equals value2, code segment2 is executed and so on. statement will run much faster than a set of nested IFs.
The statement break is used after every case in order to prevent execution The switch differs from the IF in that switch can only test for equality,
from continuing into the code segment of the next case without even whereas IF can evaluate any type of Boolean expression.
checking its value.
For example, supposing a switch statement has five cases and the value of d. WHILE Statement
the third case matches the value of expression. If no break statement were The While statement or while loop is an iteration statement. Iteration
present at the end of the third case, all the cases after case 3 would also get statements are used to execute a particular set of instructions repeatedly
executed along with case 3. If break is present only the required case is until a particular condition is met or for a fixed number of iterations.
selected and executed; after which the control gets transferred to the
next statement immediately after the switch statement. There is no break Syntax:while (condition)
after defaultbecause after the default case the control will either way get {
transferred to the next statement immediately after switch. statements;
}
The do-while statement evaluates the condition at the end of the loop after
The statement or statements are only executed if the expression is true (non- executing the block of statements at least once. If the condition is true the
zero). After every execution of the statements, the expression is evaluated loop continues, else it terminates after the first iteration.
again and the process repeats if it is true.
Syntax:do {
Example: statements to be executed;
inti=1; } while(expression);
while(i<=10)
{ Remark!
printf(“%d”, i); Pay attention to the semicolon which ends the do-while statement.
i++; The difference between while and do-while is that the while loop is an
} entry-controlled loop - it tests the condition at the beginning of the
This code will loop 10 times writing the numbers 1 to 10. loop and will not execute even once if the condition is false, whereas
the do-while loop is an exit-controlled loop - it tests the condition at
Example: A program that counts the number of blank spaces in a line of text. the end of the loop after completing the first iteration.
#include <stdio.h> Example: A program to print the sum of the digits in a number.
int main()
{ charch; short count = 0; #include<stdio.h>
printf("Type in a line of text\n"); int main()
while((ch = getchar()) != '\n') { int n, a,sum=0;
{ printf("Enter a number:");
if(ch == '') scanf("%d", &n);
count++; do{
} a =n%10;
printf("Number of spaces = %d\n",count); sum=sum+a;
return 0; n=n/10;
} } while(n>0);
printf("Sum of the digits = %d",sum);
e. DO… WHILE Statement return 0;
}
A practical use of the do-while loop is in an interactive menu-driven scanf(“%d”,&b);
program where the menu is presented at least once and then depending
upon the choice of the user, the menu is displayed again or the session is for (i=1;i<=b;i++)
terminated. Consider the same example that we saw in switch-case. Without prod=prod+a;
using an iteration statement like do-while, the user can choose any option
from the menu only once. Moreover, if a wrong choice is entered by mistake printf(“%d”,prod);
the user doesn’t have the option of entering his choice again. Both these return 0;
faults can be corrected by using the do-while loop. }
#include <stdio.h> Values can be assigned to the array as if each element were a separate
int main() variable.
{ int a, b, i, prod=0; A[0] =3; A[1] =1; A[2] =0; … A[9] =-5
scanf(“%d”,&a);
A loop can as well be used.
For example:
int main()
{ int i, n=10, A[n]
i=0;
while(i<=n)
{
printf(“Enter element at position %d”, i);
scanf(“%d”,&A[i]);
i++;
}
return 0;
}