C programming tutorial 筆記

tutorial 3 - writing hello world!


 

使用linux系統運行c,linux

安裝gcc,爲compiler,使用vim等工具寫好hello world程序,命名hello.cvim

#include <stdio.h>

int main(){  //int means the returned data type
  printf("hello world!\n"); // \n means a new line
  return 0; //the program worked as expected  
}

以後在terminal中輸入:gcc hello.c,以後會自動生成a.out文件,而後輸入 ./a.out 運行ide

 

 tutorial 10 - print variable using printf();


 

#include <stdio.h>
int main(){
  int x = 10;
  int y = x/2;
        
  printf("the magic number is: %i\n",y);    //"", is a format string, and %i inside means it's an integer, \n is new line, y is the variable you want to print
  printf("the magic number is: %i\nThe value x is: %i\n",y,x);//this will work too, first string,y and x are arguments
  
 return 0;      
}//the first output is 5;

  

tutorial 12 - taking user input and float or double datatype


#include <stdio.h>

int main(){
  int radius;
  printf("Please enter a radius");
  scanf("%i",&radius); //scanf will ask user to input a value, the & sign in front of the radius means store the input value to this address; address-of
  float area = 3.14 * radius * radius;  //float can store decimal numbers
  printf("the area is : %f\n",area);//because area is a float type, the format string must use %f    
  
  return 0;  
}

  

 tutorial 13 - type casting


 

#include <stdio.h>
int main(){
  printf("enter the number of eggs for the day: ");
  int eggs;
  scanf("%i",&eggs);
  double dozen = (double) eggs / 12; //type casting means egg now is a double type, other wise the output will always be an whole number, because eggs and 12 are both integer, even though dozen is double type.
  printf("you have %f dozen eggs .\n",dozen);  

  return 0;
}

  

tutorial 14 - working with strings

#include <stdio.h>

int main(){
  char name[31];  //for string array, we need one more character "\0" to indicate the array is finished
  printf("Please enter your name: ");
  scanf("%s",name)://for array, do not add & in front of the variable,
  printf("Hello, %s",name);

  return 0;  
}

  

 tutorial 30 - operators


 

 

 

 tutorial 35 - assignment operators


 

 

int main(){

  int pizzasToEat = 100;
  pizzasToEat += 100;  //200
  pizzasToEat -=100;  //100
  pizzasToEat *=2;  //200
  pizzasToEat /=4;  //50
  pizzasToEat %=5;  //0

  return 0;
}

  

 tutorial 36 - operator precedence


 

https://en.cppreference.com/w/c/language/operator_precedence工具

 

 tutorial 40 - type cast operator


 

int main(){
  int slices = 17;
  int people = 2;
  double halfThePizza = (double) slices / people;//double has a higher precedence then division
  
  printf("%f\n",halfThePizza);
  return 0;
}

  

 

 

參考內容:this


 

C Programming Tutorialsorm

相關文章
相關標籤/搜索