Lecture_2_Principles of C language (1)
Lecture_2_Principles of C language (1)
Another example
#include <stdio.h>
#include <math.h>
int main()
{
float x, y;
x = 6.28;
y=sin(x);
return 0;
}
$ gcc -lm MyProgram.c; a.out
C variables
Type of variables
You must use the proper format in the printf and scanf functions.
/*Print a character*/
#include <stdio.h>
int main()
{
char a='h';
printf("%c\n",a);
return 0;
}
/*Print an integer*/
#include <stdio.h>
int main()
{
int a=10;
printf("%d\n",a);
return 0;
}
/* Print a floating number */
#include <stdio.h>
int main()
{
float a=10.5;
printf("%f\n",a);
return 0;
}
/* Print floating numbers */
#include <stdio.h>
int main()
{
float a, b=9.0, c;
a=10.0; c=-2.3;
printf("a = %f\n",a);
printf("c = %f\n",c);
return 0;
}
Input/Output
printf("format",argument);
Examples:
printf("Hello world !\n");
printf("Two integers are %d and %d.\n",a,b);
printf("Two floating numbers are %f and %f.\n",a,b);
printf("Three floating numbers are %f, %f and %f.\n",a,b,c);
Logical operators:
Symbol Meaning
&& And
|| Or
! Not
if (a>0 && a<100) printf("a is between 0 and 100.\n");
if (a>0 || a<-5) printf("a is positive or less than -5.\n");
int a=20;
if (!(a==10)) printf("a is not equal to 10.");
if (a==10)
{ printf("You entered 10.\n");
return 0;
}
else ....
Increment/decrement operators
Symbol Meaning
++ b=++a a is incremented by 1 and assigned to b. Same as a=a+1;b=a;
b=a++ a is assigned to b first and incremented by 1. Same as b=a;a=a+1;
−− b=− −a a is decremented by 1 and assigned to b. Same as a=a−1; b=a;
b=a− − a is assigned to b first and decremented by 1. Same as b=a;a=a−1;
i=100;
i++;
is the same as
i=100;
i=i+1;
Substitution operators
Symbol Meaning
= a=b b is assigned to a.
+= a+=b a + b is assigned to a. Same as a=a+b;
−= a−=b a − b is assigned to a. Same as a=a−b;
*= a*=b a * b is assigned to a. Same as a=a*b;
/= a/=b a / b is assigned to a. Same as a=a/b;
%= a % = b Remainder of a / b is assigned to a. Same as a=a%b;
i=i+1
i+=1
i++
++i
The difference between ++i and i++ is that the former pre-increments i before any
operation while the latter post-increments i after the operation is done.
Control statements
The following are five statements that can control the flow of the program:
• if .... else
• for ( ; ; )
• while
• do while
• switch
if Statement
#include <stdio.h>
int main()
{
int i;
printf("Enter an integer ");
scanf("%d",&i);