Tuesday, June 5, 2018

CS2100: C Prog

1) Edit, Compile, Execute
Edit: vim first.c
Source code (first.c)
Compile: gcc first.c
Executable code (a.out)
Execute: a.out
Program output (The value of c is 3)

Edit -> Compile  -> Execute -> Edit .....

2) C keywords
Preprocessor directives:
#Include, #define

Reserve words:
int,void,float

Standard Header file:
<stdio.h>

Functions:
printf("hellow");
scanf("%f",&miles);

3) von Neumann Architecture
Note: Uninitilised variables DO NOT contain zero

Sample code:

// Converts distance in miles to kilometres.
#include <stdio.h>   /* printf, scanf definitions */
#define KMS_PER_MILE 1.609 /* conversion constant */
int main(void) {
  float miles,   // input – distance in miles
        kms;     // output – distance in kilometres
  /* Get the distance in miles */
  printf("Enter distance in miles: ");
  scanf("%f", &miles);
  // Convert the distance to kilometres
  kms = KMS_PER_MILE * miles;
  // Display the distance in kilometres
  printf("That equals %9.2f km.\n", kms);
  return 0;
}

1. Users enter number
2. kms line is executed

Von Neuman archi describes a computer comprising of
- CPU
Registers
Control unit containing instructuon register and program counter
ALU
- Memory
Stores both program and data in RAM
- I/O devices

gcc -Wall Hellow.c
The wall option shows all warnings
e.g initialisation

4) Macro Expansions
The processor replaces all instances with the constant variables that has been declared
e.g
In the above example code, where PI is defined as 3.142
The compiler reads the code as


>
int main(void) {
  ...
  areaCircle = 3.142 * radius * radius;
  volCone = 3.142 * radius * radius * height / 3.0;
}


5) Input and outputs
age - refers to the value in the variable age
&age - refers to the address of the memory cell where the value of age is stored

Format Specifiers:

These can be use in printf()
for example:
%5d is use to display an integer of width of 5, right justified
%8.3f to display a real number in a width of 8 with 3 decimal places, right justified
For scanF(), do not need to indicate the width and decimal places

6) Side effects
Apart from assigning, executing
a=12
also returns the value of a
we can make use of it like:
z=a=12

7) Operator Precdence

Take the operator as the pivot and eval accordingly

Binary operators are short-circuit evaluated,
that means in the case of ||, if one variable is eval true, it immediately returns true

<Prev Programming Languages                                              Next 3. Pointers

No comments:

Post a Comment