← Previous | 🏠 Homepage | Next Chapter → |
How 'C' Programs Work?
- Write Code – Type your program in Turbo C.
-
Compile – Turn the code into machine language.
-
Run – See the output on the screen.
Popular Compilers
- Windows/MS-DOS: Turbo C, Turbo C++, Microsoft C
-
Linux: gcc
Turbo C/C++ is best for beginners.
Open
TC.EXE
(usually inC:\TC\BIN
)-
File → New to start a new program
-
Type your code
-
Press F2 to save
-
Press Ctrl + F9 to run
-
Press Alt + F5 to see output
Turbo C creates a .EXE
file that works on any PC!
Fix for Turbo C++ Error
-
Options → Compiler → C++ Options → Set CPP always
-
Options → Environment → Editor → Set extension to .C
Taking Input with scanf()
int p, n;
float r, si;
scanf("%d %d %f", &p, &n, &r);
-
Use & before variable names (e.g.,
&p
) -
Values must be separated by space, tab, or Enter key.
Sample Program
main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("You entered: %d", num);
}
Types of C Instructions
- Type Declaration – to define variables
-
Arithmetic – to do math
-
Control – to decide program flow (we’ll learn later)
Type Declaration in C
Before using a variable, you must declare its type:
int a;
float b;
char ch;
You can also declare and give values at the same time:
int x = 10, y = 20;
float a = 1.5, b = a + 2.0; // b must come after a!
But this won’t work:
int x = y = 10; // y not defined yet
Arithmetic Instructions
+ - * / % (= assigns value)
Example:
int a = 10;
float b = 5.5, c;
c = b * 2 + 3;
-
/
= division -
%
= remainder (only for int)
Types of Math Statements
Integer – all numbers are integers
int x = 10 + 20;
Float (Real) – all numbers are decimal
float x = 3.2 / 1.6;
Mixed – both int and float
float avg = (a + b) / 2;
Important Tips
- Only one variable allowed on left of
=
-
%
doesn’t work with float -
'A'
stores ASCII value (like 65) -
You can do math with
char
,int
,float
-
No
^
or**
for power! Use:
#include <math.h>
int x = pow(3, 2); // 3^2 = 9
Integer & Float Conversion in C
When doing math in C:
-
int + int
→ result is int -
float + float
→ result is float -
int + float
→ result is float (int is converted to float first)
Examples:
5 / 2 → 2 (int result)
5.0 / 2 → 2.5 (float result)
5 / 2.0 → 2.5 (float result)
Conversion in Assignment
int i;
float b;
i = 3.5; // 3.5 becomes 3 (float → int)
b = 30; // 30 becomes 30.0 (int → float)
Even with big formulas, same rules apply!
Important:
-
int
cuts off decimal part (no rounding!) -
float
can store decimals -
Mixed math = float result
-
Assigning float to int = decimal is dropped
Example:
int k;
float a;
k = 2 / 9; // = 0
a = 2 / 9; // = 0.0
k = 2.0 / 9; // = 0.222... → becomes 0
a = 2.0 / 9; // = 0.222...
No comments:
Post a Comment