# C 從入門到改行
Tags: C, 程式
Status: In progress
# 輸入輸出
你好世界!
```c
printf("hello world!");
```
```c
puts("owo")
```
輸入咚咚
```c
scanf("%d",&a); //輸入整數(十進制)
```
%%%
| 輸出控制符 | 意思 |
| --- | --- |
| %d | 十進位(int) |
| %o | 八進位(int) |
| %x | 十六進位(int) |
| %f,%lf | 十進位(float,double) |
## Math
```c
long gcd(long a, long b)
{
if (b==0)
return a;
return gcd(b,a%b);
}
```
random
```c
srand(time(NULL));//用時間當亂數種子
```
## Array
array input
```c
for(i = 0; i < num; i++) {
scanf("%d", arr + i);
}//第1種
```
```c
for(i = 0; i < num; i++) {
scanf("%d", &arr[i]);
}//第2種
```
get array size
```c
int arr[] = {1,2,3};
// sizeof(Array_name) / sizeof(Array_type)
int size = sizeof(arr) / sizeof(int);
// or int size = sizeof(arr) / sizeof(arr[0]);
printf("陣列大小:%d",size);
```
## String
讀取字串直到換行
```c
char str[100];
scanf("%[^\n]s",str);
```
如果讀取錯誤可能是前個字串的 “ \n “ 卡在輸入緩衝區
可以用 scanf("\n") 解決
```c
fscanf(file_name, type, name);
```
💡 檔案讀取
:::spoiler
```c
int a;
char mon[20];
int year;
printf("請輸入每幾個換行:");
scanf("%d",&a);
fscanf(fp, "%s", mon);
fscanf(fp,"%d",&year);
printf("Runners' data of %s, %d\n",mon,year);
```
:::
字串長度
```c
strlen(str);//求字串str的長度
```
### string practice
- 1. [https://www.hackerrank.com](https://www.hackerrank.com/challenges/playing-with-characters)
```c
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main()
{
char c, s1[100], s2[100];
scanf("%c", &c);
scanf("%s",s1);
scanf("\n");
scanf("%[^\n]s",s2);
printf("%c\n",c);
printf("%s\n",s1);
printf("%s",s2);
return 0;
}
```
```c
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
//Complete the following function.
void calculate_the_maximum(int n, int k) {
//Write your code here.
int a=0,b=0,c=0;
for(int i=1;i<n;i++){
for(int j=2;j<=n;j++){
if(i!=j){
if ((i&j) < k) a = a > (i&j) ? a : i&j ;
if ((i|j) < k) b = b > (i|j) ? b : i|j ;
if ((i^j) < k) c = c > (i^j) ? c : i^j ;
}
}
}
printf("%d\n%d\n%d\n",a ,b, c);
}
int main() {
int n, k;
scanf("%d %d", &n, &k);
calculate_the_maximum(n, k);
return 0;
}
```