When you want to declare variable in c you also need to define the type of variable. In C there are different types e.g., int, float, char etc so first we need to tell which type of variable we are defining.
int age = 10;
We can assign and declare separately.
int age;
age = 30;
can declare multiple variables in c in a line.
int age=20, phone_number=2345566, role_number=200;
calculation between numbers is also possible using plus sign.
int x = 15;
int y = 26;
int total = x + y;
printf("%d", total);
printf used to print the variable below i have explained more about printf function.
We can even assign one variable to other variable and use it, variable in c also work fine in this case too.
int age = 25;
int updated_age = 33;
age = updated_age ;
// now age value will be printed 33.
printf("%d", age);
let's type all the code which you can run any c language complier.
#include <stdio.h>
int main() {
int age ;
age=15;
return 0;
}
For understanding code structure firs line is use to add a head file and it contains most of the c language functions and then we use int main function. Main function is basically starter of C application if you have multiple function in your coding but when you run it in a c compile it look for main function and start running application from main function so you can say main is your c program starting point and as we don't define any return type so at the end, we should return 0.
For more understanding in main function, we make link of other function and so on.
if you run the above code, you will get nothing as we have only declared and assign a variable value yet not even printed it. For printing in C we use printf function e.g., if we need simple text print, we use it like this.
#include <stdio.h>
int main() {
printf("Hello it is first line \n"); // \n will start new line
printf("Hello it is 2nd line \n");
return 0;
}
We use printf variable in c but in this case, we need to tell format to compiler like.
#include <stdio.h>
int main() {
char student_grade = 'A';
int student_age = 20;
int role_number = 31;
float monthly_fee = 2000.25;
printf("Role Number: %d\n", role_number );
printf("Grade: %c\n", student_grade );
printf("Monthly fee: %f\n", monthly_fee);
return 0;
}
For formating
- int => %d
- char => %c
- float => %f
and \n is used for new line.