language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* check_mate.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jcharloi <jcharloi@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/12/06 16:12:20 by jcharloi #+# #+# */ /* Updated: 2017/12/07 13:52:43 by jcharloi ### ########.fr */ /* */ /* ************************************************************************** */ #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> int ft_strlen(char *str) { int i = 0; while (str[i] != '\0') i++; return (i); } void ft_putstr(char *str) { write(1, str, ft_strlen(str)); } char *ft_strcpy(char *dst, char *src) { int i; i = 0; while (src[i] != '\0') { dst[i] = src[i]; i++; } dst[i] = '\0'; return (dst); } char **create_tab(int len, char **argv) { char **tab; int i; i = 1; if (!(tab = (char**)malloc(sizeof(char*) * len + 1))) return (NULL); tab[len] = NULL; while (i < len + 1) { if (!(tab[i - 1] = (char*)malloc(sizeof(char) * len + 1))) return (NULL); tab[i - 1][len] = '\0'; tab[i - 1] = ft_strcpy(tab[i - 1], argv[i]); i++; } return (tab); } int check_rook(char **tab, int y, int x) { int i; int j; //printf("hjhr\n"); j = x + 1; //a droite while (tab[y][j] != '\0') { if (tab[y][j] == 'P' || tab[y][j] == 'B' || tab[y][j] == 'Q' || tab[y][j] == 'R') return (0); if (tab[y][j] == 'K') { ft_putstr("Success\n"); return (1); } j++; } j = x - 1; //printf("j : %d\n", j); //a gauche while (j >= 0) { if (tab[y][j] == 'P' || tab[y][j] == 'B' || tab[y][j] == 'Q' || tab[y][j] == 'R') return (0); if (tab[y][j] == 'K') { ft_putstr("Success\n"); return (1); } j--; } //printf("b\n"); i = y + 1; //en bas while (tab[i] != NULL) { if (tab[i][x] == 'P' || tab[i][x] == 'B' || tab[i][x] == 'Q' || tab[i][x] == 'R') return (0); if (tab[i][x] == 'K') { ft_putstr("Success\n"); return (1); } i++; } i = y - 1; //en haut //printf("i : %d\n", i); while (i >= 0) { if (tab[i][x] == 'P' || tab[i][x] == 'B' || tab[i][x] == 'Q' || tab[i][x] == 'R') return (0); if (tab[i][x] == 'K') { ft_putstr("Success\n"); return (1); } i--; } return (0); } int check_pawn(char **tab, int y, int x) { if (y > 0 && (tab[y - 1][x - 1] == 'K' || tab[y - 1][x + 1] == 'K')) { ft_putstr("Success\n"); return (1); } return (0); } int check_bishop(char **tab, int y, int x) { int i; int j; i = y + 1; j = x + 1; //en bas a droite; while (tab[i] != NULL) { if (tab[i][j] == 'P' || tab[i][j] == 'B' || tab[i][j] == 'Q' || tab[i][j] == 'R') return (0); if (tab[i][j] == 'K') { ft_putstr("Success\n"); return (1); } i++; j++; } i = y + 1; j = x - 1; //en bas a gauche while (tab[i] != NULL) { if (tab[i][j] == 'P' || tab[i][j] == 'B' || tab[i][j] == 'Q' || tab[i][j] == 'R') return (0); if (tab[i][j] == 'K') { ft_putstr("Success\n"); return (1); } i++; j--; } i = y - 1; j = x + 1; //en haut a droite; while (i >= 0) { if (tab[i][j] == 'P' || tab[i][j] == 'B' || tab[i][j] == 'Q' || tab[i][j] == 'R') return (0); if (tab[i][j] == 'K') { ft_putstr("Success\n"); return (1); } i--; j++; } i = y - 1; j = x - 1; //en haut a gauche while (i >= 0) { if (tab[i][j] == 'P' || tab[i][j] == 'B' || tab[i][j] == 'Q' || tab[i][j] == 'R') return (0); if (tab[i][j] == 'K') { ft_putstr("Success\n"); return (1); } i--; j--; } return (0); } int check_queen(char **tab, int i, int j) { if (check_bishop(tab, i, j) == 1) return (1); if (check_rook(tab, i, j) == 1) return (1); return (0); } int main(int argc, char **argv) { char **tab; int i = 0; int j = 0; if (argc > 1) { tab = create_tab(argc - 1, argv); if (tab == NULL) return (-1); while (tab[i] != NULL) { printf("tab[i] : %s\n", tab[i]); i++; } i = 0; while (tab[i] != NULL) { j = 0; while (tab[i][j] != '\0') { if (tab[i][j] == 'R') { if (check_rook(tab, i, j) == 1) return (0); } else if (tab[i][j] == 'P') { if (check_pawn(tab, i, j) == 1) return (0); } else if (tab[i][j] == 'B') { if (check_bishop(tab, i, j) == 1) return (0); } else if (tab[i][j] == 'Q') { if (check_queen(tab, i, j) == 1) return (0); } j++; } i++; } ft_putstr("Fail"); free(*tab); } ft_putstr("\n"); return (0); }
C
#include "main.h" /** *_islower - check for lowercase characters * *@c : the number to be traced *Description: checks for lowercase *Return: 0 if false & 1 if true */ int _islower(int c) { return (c >= 'a' && c <= 'z'); }
C
#include <stdio.h> #include "lexer.h" void TokenPrint(TokenT *token) { char *id = "?"; int i; if (token->id == TOK_LBRACKET) id = "["; else if (token->id == TOK_RBRACKET) id = "]"; else if (token->id == TOK_LBRACE) id = "{"; else if (token->id == TOK_RBRACE) id = "}"; else if (token->id == TOK_COMMA) id = ","; else if (token->id == TOK_COLON) id = ":"; else if (token->id == TOK_INTEGER) id = "int"; else if (token->id == TOK_REAL) id = "float"; else if (token->id == TOK_STRING) id = "str"; else if (token->id == TOK_TRUE) id = "true"; else if (token->id == TOK_FALSE) id = "false"; else if (token->id == TOK_NULL) id = "null"; printf("Token( '%s'", id); if (token->id == TOK_INTEGER || token->id == TOK_REAL || token->id == TOK_STRING) { printf(" | "); for (i = 0; i < token->size; i++) putchar(token->value[i]); } if (token->id == TOK_LBRACE || token->id == TOK_LBRACKET) printf(" | %d", token->size); printf(" | parent=%d | pos=%d )\n", token->parent, token->pos); }
C
#include <stdio.h> #include "add.h" #include "divide.h" int main(){ printf("%lf\n", add(7,5) ); printf("%lf\n", divide(6,2)); return 0; }
C
/* * Using function memmove * To compile: * $ gcc fig08_29.c -o fig08_29 */ #include <stdio.h> #include <string.h> int main(void) { char s[] = "Home Sweet Home"; // initialize char array s printf("string s before memmove is: %s\n", s); printf("string s after memmove is: %s\n", (char *) memmove(s, &s[5], 10)); }
C
#include <stdbool.h> #include <stdlib.h> #include <string.h> #include "symbol_table.h" #ifndef OUTPUT_H #define OUTPUT_H /* Writes an object file (*.ob) with the given instruction/data memory content. * Returns true on success and false on error. */ bool writeObjectFile(const char *name, unsigned short *iMemory, int ic, unsigned short *dMemory, int dc); /* Writes an entries file (*.ent) with the given entries table. * Returns true on success and false on error. */ bool writeEntriesFile(const char *name, SymbolTable* entriesTable); /* Writes an externals file (*.ext) with the given externals table. * Returns true on success and false on error. */ bool writeExternalsFile(const char *name, SymbolTable* externalsTable); /* Opens a file named <name>.<suffix> for reading or writing. * Returns NULL on error. */ FILE* openFile(const char *name, const char *suffix, const char *mode); #endif /* OUTPUT_H */
C
/* Kyle Seelman CPSC 1010 Lab, Spring 2017 Lab #1 My first "hello world" program. */ #include <stdio.h> int main(void) { printf ("Hello world\n"); printf ("Hello world\n"); printf ("Hello world\n"); printf ("Hello world\n"); printf ("Hello world\n"); printf ("Hello world\n"); printf ("Hello world\n"); printf ("Hello world\n"); printf ("Hello world\n"); printf ("Hello world\n"); return 0; }
C
// // limits.h // // this is for a 32-bit x86 system // // written by sjrct // #ifndef _LIMITS_H_ #define _LIMITS_H_ // the byte size on the machine #define CHAR_BIT 8 // char limits #define SCHAR_MAX 0x7f #define SCHAR_MIN 0xff #define UCHAR_MAX 0xff // // limits of chars without regard to sign // // the macro __CHAR_UNSIGNED__ is a GNU C extension, and is defined when chars // default to unsigned, not signed. This should jiggle with most compilers // seeing that GNU C extensions are quite widely accepted, and that most // compilers default to signed characters anyway // #ifdef __CHAR_UNSIGNED__ #define CHAR_MAX UCHAR_MAX #define CHAR_MIN 0 #else #define CHAR_MAX SCHAR_MAX #define CHAR_MIN SCHAR_MIN #endif // short limits #define SHRT_MAX 0x7fff #define SHRT_MIN 0xffff #define USHRT_MAX 0xffff // int limits #define INT_MAX 0x7fffffff #define INT_MIN 0xffffffff #define UINT_MAX 0xffffffff // long limits, for a 32-bit system or LLP64 systems #define LONG_MAX INT_MAX #define LONG_MIN INT_MIN #define ULONG_MAX UINT_MAX #endif
C
/* ヘッダファイルのインクルード */ #include <stdio.h> /* 標準入出力 */ /* main関数の定義 */ int main(void){ /* 変数の初期化 */ int a = 10; /* aを10に初期化. */ const int b = 100; /* bは100とする.(constが付いているので定数として扱われる. */ /* 配列・ポインタの初期化 */ char str1[] = "ABC"; /* str1に"ABC"という文字列をセット. */ char str2[] = "DEF"; /* str2に"DEF"という文字列をセット. */ const char * p = str1; /* ポインタでconstが型名の前の場合は, 参照先の値が変更不可になる. */ char * const q = str2; /* ポインタでconstが変数名の前の場合は, ポインタの値が変更不可になる. */ /* 値の出力 */ printf("a = %d\n", a); /* aの値を出力. */ printf("b = %d\n", b); /* bの値を出力. */ /* constに代入は不可. */ a = 20; /* aに20を代入.(これは問題なし.) */ /*b = 200;*/ /* bに200を代入.(これはビルドエラー.) */ /* 値の出力 */ printf("a = %d\n", a); /* aの値を出力. */ printf("b = %d\n", b); /* bの値を出力. */ /* 値の出力 */ printf("str1 = %s\n", p); /* p( == str1)を出力. */ printf("str2 = %s\n", q); /* q( == str2)を出力. */ /* 変更する. */ /**p = 'G';*/ /* これは変更不可なのでビルドエラー. */ *q = 'H'; /* これは変更可能. */ /* 変更する. */ p = str2; /* これは変更可能. */ /*q = str1;*/ /* これは変更不可なのでビルドエラー. */ /* 値の出力 */ printf("p = %s\n", p); /* p( == str2)を出力. */ printf("q = %s\n", q); /* q( == str2)を出力. */ /* プログラムの終了 */ return 0; }
C
#include "pogodi_broj.h" #define ANSI_COLOR_CYAN "\x1b[36m" #define ANSI_COLOR_RESET "\x1b[0m" int pretrazivanje_pokusaja(int niz[], int kljuc) // Pretrazuje da li smo 2x unijeli isti broj { int i; for( i=0; i<5; i++) { if(niz[i] == kljuc) return 1; } return 0; } int generator() // Generise slucajan broj u intervalu od 0 do 100 { srand(time(0)); int r = (rand() % 100)+1; return r; } int generator1() //Generise slucajan broj u intervalu od 0 do 5 { srand(time(0)); int r = (rand() % 5)+1; return r; } int brojac_pokusaja(int niz[]) // Broji koliko smo puta pokusali pogoditi zamisljeni broj { int i; int p = 0; for( i=0; i<5; i++) { if(niz[i] == p) return i+1; } return 0; } int brojac_bodova(int pokusaj) // Broji bodove { return 100/pokusaj; } /*void ispisi() { printf("=======================================================================================================================\n"); }*/ int rezim1() // Rezim koji radi u slucaju da igrac ne ulazi prvi put u igru { int suma_bodova = 0; int niz_pokusaja[6]= {150,150,150,150,150,150},i,k; printf("Pogodite zamisljeni broj u intervalu od 0 do 100: \n"); int p = generator(); int broj; for( i=0; i<5; i++) { do { printf("%d. pokusaj: ", i+1); broj=ucitaj_karakter(); if(broj!=-1) { if(pretrazivanje_pokusaja(niz_pokusaja, broj)) printf("Broj je vec unesen, ponovite pokusaj. \n"); } else printf("Pogresan unos, pokusajte ponovo! \n"); } while(broj < 0 || broj > 100 || pretrazivanje_pokusaja(niz_pokusaja, broj)); niz_pokusaja[i] = broj; if(broj == p) { suma_bodova += 100/(i+1); printf("Cestitamo, osvojili ste %d bodova!\n", 100/(i+1)); goto jump; } if(i == 4) printf("Zao nam je, pogrijesili ste, zamisljeni broj je %d! \n", p); else { if(p > broj) printf("Zamisljeni broj je veci od unesenog! \n"); else printf("Zamisljeni broj je manji od unesenog! \n"); } } jump: dodajStatistika("1", suma_bodova); return suma_bodova; } int rezim0() // Rezim koji radi u slucaju da igrac ulazi prvi put u igru { int suma_bodova = 0; int niz_pokusaja[6]= {150,150,150,150,150,150},i,k; printf("Pogodite zamisljeni broj u intervalu od 0 do 100: \n"); int p = generator(); int broj, broj_prethodni; int nizPomoc[3]; int pogodjeno = 0; for( i=0; i<5; i++) { for(int j=0; j<3; j++) nizPomoc[j] = generator1(); do { printf("%d. pokusaj: ", i+1); broj_prethodni = broj; broj=ucitaj_karakter(); if(broj!=-1) { if(pretrazivanje_pokusaja(niz_pokusaja, broj)) printf("Broj je vec unesen, ponovite pokusaj. \n"); } else printf("Pogresan unos, pokusajte ponovo! \n"); } while(broj < 0 || broj > 100 || pretrazivanje_pokusaja(niz_pokusaja, broj)); niz_pokusaja[i] = broj; if(broj == p || nizPomoc[0] == i || nizPomoc[1] == i || nizPomoc[2] == i) { if(broj_prethodni > p && broj > p) { if(i == 4) goto here3; goto here1; } if(broj_prethodni < p && broj < p){ if(i == 4) goto here3; goto here2; } suma_bodova += 100/(i+1); pogodjeno++; printf("Cestitamo, osvojili ste %d bodova!\n", 100/(i+1)); goto jump; } if(pogodjeno < 3 && i >= 2) { if(broj_prethodni > p && broj > p) { if(i == 4) goto here3; goto here1; } if(broj_prethodni < p && broj < p) { if(i == 4) goto here3; goto here2; } suma_bodova += 100/(i+1); pogodjeno++; printf("Cestitamo, osvojili ste %d bodova!\n", 100/(i+1)); goto jump; } if(i == 4){ here3: printf("Zao nam je, pogrijesili ste, zamisljeni broj je %d! \n", p); } else { if(p > broj) { here2: printf("Zamisljeni broj je veci od unesenog! \n"); } else { here1: printf("Zamisljeni broj je manji od unesenog! \n"); } } } jump: dodajStatistika("1", suma_bodova); return suma_bodova; } void naslov() { ispisi(); printf(ANSI_COLOR_CYAN " POGODI ZAMISLJENI BROJ\n"ANSI_COLOR_RESET); ispisi(); printf("\n"); } int igranje() // Glavna funkcija koja se poziva u PlayGround funkciji { int rezim, p, br_igranja = 0,br_bodova=0,x=1,t; char enter,c,m1; FILE *fp,*fp1; char m[20]="1"; p=atoi(m); scanf("%c",&c); while(p) { fp1=fopen("pamcenjerezima.txt","r"); fscanf(fp1,"%d",&br_igranja); fclose(fp1); fp=fopen("rezim.txt","r"); if(fp) { rezim=1; fclose(fp); } else { rezim=0; } if(rezim == 0) { br_bodova += rezim0(); br_igranja++; fp1=fopen("pamcenjerezima.txt","w"); fprintf(fp1,"%d",br_igranja); fclose(fp1); } else { br_bodova += rezim1(); } do { printf("Da li zelite ponovo da igrate ovu igru? \n"); printf("1 - Da\n"); printf("2 - Ne\n"); scanf("%s", m); p=atoi(m); if(p<1 || p>2) printf("Pogresan unos, mozete unijeti samo 1 ili 2 !\n"); } while(p<1 || p>2); if(p==2) p=0; scanf("%c",&enter); if(br_igranja == 3) { fp=fopen("rezim.txt","w"); if(fp) fclose(fp); } if(br_igranja>=3) rezim=1; else rezim = 0; } return br_bodova; } int ucitaj_karakter() // Provjerava da li je to sto se unosi broj (odnosno da nije neki karakter koji nije broj) { int i,i1,i2,i3,j; char *c; c=(char *)calloc(512,sizeof(char)); fgets(c,512,stdin); if (c[0]<48 || c[0]>57 || c[0]=='\n') { return -1; } else { i1=c[0]-48; } if(c[1]=='\n' || c[2]=='\0') { i=i1; return i; } else if (c[1]<48 || c[1]>57) { return -1; } else { i2=c[1]-48; } if(c[2]=='\n' || c[2]=='\0') { i=i1*10+i2; return i; } else if (c[2]<48 || c[2]>57) { return -1; } else { i3=c[2]-48; } for(j = 3; j<512; j++) if (c[j]!= '\n' && c[j] != '\0') { return -1; } i=100*i1+i2*10+i3; if(i>100) { return -1; } return i; }
C
#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include<netdb.h> int main() { int sock,rsock, sender_fd,reciever_fd, bytes_recieved , true = 1; int R_PORT; char send_data [1024] , recv_data[1024],RecieverPORT[1024]; char username[1024],password[1024],Recievername[1024],RecieverIP[100]; struct sockaddr_in server_addr,client_addr,Reciever_addr; int sin_size; //creating socket if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("Socket"); exit(1); } if (setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&true,sizeof(int)) == -1) { perror("Setsockopt"); exit(1); } //binding and filling address by hands server_addr.sin_family = AF_INET; server_addr.sin_port = htons(57295); server_addr.sin_addr.s_addr = INADDR_ANY; bzero(&(server_addr.sin_zero),8); if (bind(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) { perror("Unable to bind"); exit(1); } if (listen(sock, 5) == -1) { perror("Listen"); exit(1); } printf("\n Relayserver waiting on port 57295"); fflush(stdout); while(1) { sin_size = sizeof(struct sockaddr_in); sender_fd = accept(sock, (struct sockaddr *)&client_addr,&sin_size); //file descriptor used for conatcting with SENDER printf("\n Got Sender connection from (%s , %d)",inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port)); while(1){ //loop for user name and pwd authentication //getting username bytes_recieved=recv(sender_fd,username,1024,0); username[bytes_recieved]='\0'; send(sender_fd,"Enter your password:",strlen("Enter your password:"),0); //getting password bytes_recieved=recv(sender_fd,password,1024,0); password[bytes_recieved]='\0'; //authentication if((strcmp(username,"anna")==0 && strcmp(password,"a86H6T0c")==0) || (strcmp(username,"barbara")==0 && strcmp(password,"G6M7p8az")==0) || (strcmp(username,"cathie")==0 && strcmp(password,"Pd82bG57")==0) || (strcmp(username,"dohas")==0 && strcmp(password,"jO79bNs1")==0) || (strcmp(username,"eli")==0 && strcmp(password,"uCh781fY")==0) || (strcmp(username,"farah")==0 && strcmp(password,"Cfw61RqV")==0) || (strcmp(username,"shaz")==0 && strcmp(password,"Kuz07YLv")==0)||(strcmp(username,"murali")==0 && strcmp(password,"murali1234")==0)) { send(sender_fd,"valid",strlen("valid"),0); break; }else{ send(sender_fd,"not valid user",strlen("not valid user"),0); } } while(1){ //loop for retrieving receiver RECEIVER IP //getting Reciever name bytes_recieved=recv(sender_fd,Recievername,1024,0); Recievername[bytes_recieved]='\0'; send(sender_fd,"Enter RecieverPORT:",strlen("Enter RecieverPORT:"),0); //getting Receiver port number bytes_recieved=recv(sender_fd,RecieverPORT,1024,0); RecieverPORT[bytes_recieved]='\0'; //Validating receiver username and port number if((strcmp(Recievername,"gpel1.cs.ou.edu")==0)|| (strcmp(Recievername,"gpel2.cs.ou.edu")==0) || (strcmp(Recievername,"gpel3.cs.ou.edu")==0) || (strcmp(Recievername,"gpel4.cs.ou.edu")==0) || (strcmp(Recievername,"gpel5.cs.ou.edu")==0) || (strcmp(Recievername,"gpel6.cs.ou.edu")==0) || (strcmp(Recievername,"murali.ou.edu")==0)) { send(sender_fd,"valid",strlen("valid"),0); }else{ send(sender_fd,"You Enter a Invalid Recievername and PORT ",strlen("Enter valid Recievername and PORT"),0); continue; } if(strcmp(Recievername,"murali.ou.edu")==0) strcpy(RecieverIP,"192.168.2.7"); else if(strcmp(Recievername,"gpel1.cs.ou.edu")==0) strcpy(RecieverIP,"129.15.78.11"); else if(strcmp(Recievername,"gpel2.cs.ou.edu")==0) strcpy(RecieverIP,"129.15.78.12"); else if(strcmp(Recievername,"gpel3.cs.ou.edu")==0) strcpy(RecieverIP,"129.15.78.13"); else if(strcmp(Recievername,"gpel4.cs.ou.edu")==0) strcpy(RecieverIP,"129.15.78.14"); else if(strcmp(Recievername,"gpel5.cs.ou.edu")==0) strcpy(RecieverIP,"129.15.78.15"); else if(strcmp(Recievername,"gpel6.cs.ou.edu")==0) strcpy(RecieverIP,"129.15.78.16"); else if(strcmp(Recievername,"gpel7.cs.ou.edu")==0) strcpy(RecieverIP,"129.15.78.17"); break; } strcpy(RecieverIP,"192.168.2.7"); //creating a new socket for maintaining connections with RECEIVER if ((rsock = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("Socket"); exit(1); } if (setsockopt(rsock,SOL_SOCKET,SO_REUSEADDR,&true,sizeof(int)) == -1) { perror("Setsockopt"); exit(1); } strcpy(RecieverPORT,"57296"); Reciever_addr.sin_family = AF_INET; R_PORT=atoi(RecieverPORT); Reciever_addr.sin_port = htons(R_PORT); Reciever_addr.sin_addr.s_addr=inet_addr(RecieverIP); bzero(&(Reciever_addr.sin_zero),8); if (connect(rsock, (struct sockaddr *)&Reciever_addr,sizeof(struct sockaddr)) == -1){ perror("Connect"); printf("\n sorry"); exit(1); } send(rsock,"hai this is relayserver",strlen("hai this is relayserver"),0); while (1) { send(sender_fd,"Enter q or Q to exit ",strlen("Enter q or Q to exit"), 0); bytes_recieved = recv(sender_fd,recv_data,1024,0); recv_data[bytes_recieved] = '\0'; if (strcmp(recv_data , "q") == 0 || strcmp(recv_data , "Q") == 0) { send(rsock,recv_data,strlen(recv_data),0); break; } // send(sender_fd,"Enter Message to Receiver",strlen("Enter Message to Receiver"), 0); while(1) { bytes_recieved = recv(sender_fd,recv_data,1024,0); recv_data[bytes_recieved] = '\0'; if(strcmp(recv_data , "eom") == 0) { send(rsock,recv_data,strlen(recv_data),0); break; } else { send(rsock,recv_data,strlen(recv_data),0); fflush(stdout); } } bytes_recieved = recv(rsock,recv_data,1024,0); recv_data[bytes_recieved] = '\0'; send(sender_fd,recv_data,strlen(recv_data),0); } close(sender_fd); close(rsock); } close(sock); return 0; }
C
//Pattern printing-6 // 4 3 2 1 1 2 3 4 #include<stdio.h> void Display(int iVal) { int iCnt=0; for(iCnt=iVal;iCnt>=1;iCnt--) { printf("%d ",iCnt); } for(iCnt=1;iCnt<=iVal;iCnt++) { printf("%d ",iCnt); //static data } } int main() { int iValue=0; printf("Please enter the value :\n"); scanf("%d",&iValue); Display(iValue); return 0; }
C
/* * shell_insert_sort.c * * Created on: Aug 14, 2016 * Author: leo */ /* * shell_insert_sort.c * * Created on: Aug 14, 2016 * Author: leo */ #include <stdio.h> #include <stdlib.h> void shell_insert_sort(int a[],int n,int div) { int i = 0,j = 0,x = 0; for(i=div;i<n;++i) { if(a[i]<a[i-div]) { j = i - div; x = a[i]; a[i] = a[i-div]; while(x<a[j]&&j>=0) { a[j+div] = a[j]; j -= div; } a[j+div] = x; } print(a,n,i); } } void shell_sort(int a[],int n) { int div = n/2; while(div>=1) { printf("div=%d \n",div); shell_insert_sort(a,n,div); div = div/2; } } int main() { int a[] = {3,1,8,5,7,12,4,28,14,6}; shell_sort(a,10); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* asm.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: blinnea <blinnea@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/09/01 15:36:15 by fhilary #+# #+# */ /* Updated: 2020/11/07 20:29:36 by blinnea ### ########.fr */ /* */ /* ************************************************************************** */ #include "asm.h" #include <unistd.h> static void quedel(void *c, size_t cs) { if (cs && c) ft_memdel(&c); } void clear_parser(t_parse *parser) { if (parser->lables) clear_label_htable(&(parser->lables)); if (parser->op_htable) clear_op_htable(&(parser->op_htable)); if (parser->tokens) ft_elistdel(&(parser->tokens)); } static void execute(char *file) { t_parse parser; ft_bzero(&parser, sizeof(t_parse)); parser.tokens = ft_elistnew(sizeof(t_token), quedel); if ((parser.fdin = open(file, O_RDONLY)) < 0) error(ERR_OPEN_FILE, &parser); parse(&parser); get_op_htable(&parser); get_label_htable(&parser); collection(&parser); if ((parser.fdout = open(new_filename(file, ".cor"), O_CREAT | O_TRUNC | O_WRONLY, 0644)) < 0) error(ERR_CREATE_FILE, &parser); if (!parser.position) error(ERR_INVALID_CODE_SIZE, &parser); shaping(&parser); ft_printf("Writing output program to %s\n", new_filename(file, ".cor")); clear_parser(&parser); close(parser.fdin); close(parser.fdout); } int main(int ac, char **av) { if (ac == 2 && isrighttype(av[1])) execute(av[1]); else ft_printf_fd(STDERR_FILENO, "Wrong file type\n"); return (0); }
C
// 1º Exercício da lista de Structs #include <stdio.h> typedef struct { int hora; int minuto; int segundos; } Horario; typedef struct { int dia; int mes; int ano; } Data; typedef struct { Data data; Horario horario; char * texto; } Compromisso; int main() { return 0; }
C
//==============================================// // // // Point // // // //----------------------------------------------// // File : point.h */ // //----------------------------------------------// // Definisi ADT Point // // Point adalah representasi titik di koordinat // // 2 dimensi dengan titik seperti index matrix // //==============================================// //----------------------------------------------// // Contoh Visualisasi titik // //----------------------------------------------// // A . . // // . . . // // . B . // // // // Ruang 3x3 di atas adalah bidang koordinat 2D // // A menempati Point (1,1) // // B menempati Point (3,2) // //----------------------------------------------// #ifndef _POINT_H #define _POINT_H /////////////////////////// // INCLUDE // /////////////////////////// #include "boolean.h" //////////////////////////////////// // Definisi elemen Point // //////////////////////////////////// typedef struct { int X; /* absis */ int Y; /* ordinat */ } Point; ////////////////////////// // SELECTOR // ////////////////////////// /* ********* AKSES (Selektor) ********* */ /* Jika P adalah Point, maka akses elemen : */ #define PointX(P) (P).X /* Mengembalikan nilai X dari point */ #define PointY(P) (P).Y /* Mengembalikan nilai Y dari point */ /////////////////////////// // CONSTRUCTOR // /////////////////////////// Point PointCreate(int X, int Y); /* Membentuk sebuah Point dari komponen-komponennya */ /////////////////////////// // PREDIKAT // /////////////////////////// boolean PointEQ(Point P1, Point P2); /* Mengirimkan true jika P1 = P2 : absis dan ordinatnya sama */ ////////////////////////////////// // POINT OPERATIONS // ////////////////////////////////// /* *** KELOMPOK Interaksi dengan I/O device, BACA/TULIS *** */ void PointRead(Point *P); /* Membaca nilai absis dan ordinat dari keyboard dan membentuk Point P berdasarkan dari nilai X dan Y tersebut */ /* Komponen X dan Y dibaca dalam 1 baris, dipisahkan 1 buah spasi */ /* Contoh: 1 2 akan membentuk Point <1,2> */ /* I.S. Sembarang */ /* F.S. P terdefinisi */ void PointPrint(Point P); /* Nilai P ditulis ke layar dengan format "(X,Y)" dengan enter di belakang Output X dan Y harus dituliskan dalam bilangan riil dengan 2 angka di belakang koma. */ /* I.S. P terdefinisi */ /* F.S. P tertulis di layar dengan format "(X,Y)" */ #endif
C
#include "SomeObject.h" /* 虚函数的实现 */ void some_object_method1_impl (SomeObject *self, gint a) { self->m_a = a; g_print ("Method1: %i\n", self->m_a); } void some_object_method2_impl (SomeObject *self, gchar* b) { self->m_b = b; g_print ("Method2: %s\n", self->m_b); } /* 公有方法 */ void some_object_method1 (SomeObject *self, gint a) { SOME_OBJECT_GET_CLASS (self)->method1 (self, a); } void some_object_method2 (SomeObject *self, gchar* b) { SOME_OBJECT_GET_CLASS (self)->method2 (self, b); } void some_object_method3 (SomeObject *self, gfloat c) { self->m_c = c; g_print ("Method3: %f\n", self->m_c); } /* 该函数将在类对象创建时被调用 */ void some_object_class_init (gpointer g_class, gpointer class_data) { SomeObjectClass *this_class = SOME_OBJECT_CLASS (g_class); /* fill in the class struct members (in this case just a vtable) */ this_class->method1 = &some_object_method1_impl; this_class->method2 = &some_object_method2_impl; } /* 该函数在类对象不再被使用时调用 */ void some_object_class_final (gpointer g_class, gpointer class_data) { /* No class finalization needed since the class object holds no pointers or references to any dynamic resources which would need to be released when the class object is no longer in use. */ } /* 该函数在实例对象被创建时调用。系统通过g_class实例的类来传递该实例的类。 */ void some_object_instance_init (GTypeInstance *instance, gpointer g_class) { SomeObject *this_object = SOME_OBJECT (instance); /* fill in the instance struct members */ this_object->m_a = 42; this_object->m_b = "Hello"; this_object->m_c = 3.14; } /* 因为该类没有基类,所以基类构造/析构函数是空的 */ GType some_object_get_type (void) { static GType type = 0; if (type == 0) { /* 这是系统用来完整描述类型时如何被创建,构造和析构的结构体。 */ static const GTypeInfo type_info = { sizeof (SomeObjectClass), NULL, /* 基类构造函数 */ NULL, /* 基类析构函数 */ some_object_class_init, /* 类对象构造函数 */ some_object_class_final, /* 类对象析构函数 */ NULL, /* 类数据 */ sizeof (SomeObject), 0, /* 预分配的字节数 */ some_object_instance_init /* 实例对象构造函数 */ }; /* 因为我们的类没有父类,所以它将被认为是“基础类(fundamental)”, 所以我们必须要告诉系统,我们的类既是一个复合结构的类(与浮点型,整型, 或者指针不同),并且时可以被实例化的(系统可以创建实例对象,例如接口 或者抽象类不能被实例化 */ static const GTypeFundamentalInfo fundamental_info = { G_TYPE_FLAG_CLASSED | G_TYPE_FLAG_INSTANTIATABLE }; type = g_type_register_fundamental ( g_type_fundamental_next (), /* 下一个可用的GType数 */ "SomeObjectType", /* 类型的名称 */ &type_info, /* 上面定义的type_info */ &fundamental_info, /* 上面定义的fundamental_info */ 0 /* 类型不是抽象的 */ ); } return type; }
C
#include <stdio.h> int prime(n) { int i, r; int flag = 0; r = sqrt(n); for(i = 2; i <= r; i++){ if(n % i == 0){ flag = 1; break; } } if(n == 1) return 0; else if(flag == 1) return 0; else return n; } int main() { int i, num, prime1, prime2, len, test; while(scanf("%d", &num) && num != 0){ len = num / 2; for(i = 0; i<=len; i++){ test = prime(i); if(test != 0) prime1 = test; test = prime(num-i); if(test != 0) prime2 = test; if(prime1 + prime2 == num) break; } printf("%d = %d + %d\n", num, prime1, prime2); } return 0; }
C
/* * File: products.c * Author: morris * * Created on January 28, 2015, 9:14 PM */ #include <stdio.h> #include <stdlib.h> /* * */ int main(int argc, char** argv) { float salesTotal=0,items[2],cost[2]; int i; for (i=0;i<2;i++ ){ printf("Enter The price of item %d: ",i+1); scanf("%f",&cost[i]); printf("Enter The Quantity of item %d: ",i+1); scanf("%f",&items[i]); salesTotal+=items[i]*cost[i]; } printf("\nTotal for the sale is %.2f\n",salesTotal); return (EXIT_SUCCESS); }
C
#include <time.h> #include <stdio.h> #include <stdlib.h> #include <err.h> #include <string.h> #include <unistd.h> #include "time.h" int coffee(int Hours, int Mins) { // read the current time time_t now = time (NULL); // convert it to local time struct tm tm_now = *localtime (&now); // Create an HHMM chain char s_now[sizeof"HHMM"]; strftime (s_now, sizeof s_now, "%H%M", &tm_now); int timenow = atoi(s_now); int timecoffe = Hours*100 + Mins; if(timecoffe > 2359) errx(EXIT_FAILURE,"please enter a correct time \"hours:mins\""); for (int i = 0; i < 2; ++i) { int j = timecoffe % 100; timecoffe /= 100; if(i == 0 && j > 59) errx(EXIT_FAILURE,"please enter a correct time"); if(i == 1 && j > 23) errx(EXIT_FAILURE,"please enter a correct time"); } int mins = Hours *60 + Mins; int nowh = timenow/100; int nowm = nowh*60 + timenow%100; int m = 0; while(mins != nowm) { if(mins == 0 && mins != nowm) mins = 24*60; if(mins != nowm) { m+=1; mins -= 1; } } int secondes = m*60; // Returns the difference of the two times in seconds return secondes; }
C
//Koral nataf 208726257 //and //Gal or 316083690 #include <stdio.h> #include <stdlib.h> #include <string.h> #include "equation.h" #include "allEquations.h" #include "solver.h" #include "general.h" int main() { int number; printf("Number of equations: (1-3): "); scanf("%d", &number); getchar(); while (number < 1 || number > 3) { printf( "wrong input! Number of equations must be between 1-3!\n please try again..\nNumber of equations: (1-3): "); scanf("%d", &number); getchar(); } AllEquations* ae = (AllEquations*) malloc(sizeof(AllEquations)); ae->count = number; ae->eqArr = (Equation**) malloc(number * sizeof(Equation*)); for (int i = 0; i < number; i++) { ae->eqArr[i] = getEquation(i + 1, number); } Solver* solver = (Solver*) malloc(sizeof(Solver)); convertToSolver(ae, solver); printMatrix(solver->A_Mat, solver->count); printf("\nMatrix A determinant = %.3f \n\n", solver->Detrmin); printArray(solver->B_Vec, solver->count); checkSol(solver); freeAllEquations(ae); freeSolver(solver); }
C
#include <stdio.h> int main(void) { int min, max, sum; /* 入力部分 */ printf("最小値と最大値を, で区切って入力してください\n"); scanf("%d, %d", &min, &max); /* 計算部分 */ sum = (max-min+1)*(min+max)/2; /* 出力部分 */ printf("%d〜%dの合計は%dです\n", min, max, sum); return 0; }
C
#include<stdlib.h> #include<stdio.h> #include<malloc.h> /* Author Amit Sangwan Copyright 2016 linked list file to create some operation on dym=namic memory allocation like insertion,travel search and deleted element from the linked list */ struct node{ int data; struct node *next; }; void Insert(void); int Search(int); void display(void); void travel(void); void Delete(int); typedef struct node NODE; NODE *HEAD=NULL; void display(void); int main(){ NODE *temp; int data; int p=1,choice,val; while(p){ display(); scanf("%d",&choice); switch(choice){ case 1: Insert(); break; case 2: travel(); break; case 3: printf("Enter value to find\n"); scanf("%d",&val); Search(val); break; case 4: printf("Enter value to find\n"); scanf("%d",&val); Delete(val); break; case 5: exit(1); } printf("\n-----------------Press 1 to continue...\n\n"); scanf("%d",&p); } } void display(){ printf("\t\t---------------------------------------------\n\n"); printf("\t\t\tEnter your choice\n"); printf("\t\t\t1. Insert new Element\n\t\t\t2. Display list\n\t\t\t3. Search an element\n\t\t\t4. Delete an element\n\t\t\t5.Exit\n\n"); printf("\t\t---------------------------------------------\n\n"); } /* this function add new element to the lined list */ void Insert(){ NODE *temp,*p; if(HEAD==NULL){ temp=(NODE *)malloc(sizeof(NODE)); printf("Adding head....\nEnter data for head \n"); scanf("%d",&temp->data); HEAD=temp; HEAD->next=NULL; } else{ temp=HEAD; while(temp->next !=NULL){ temp = temp->next; } p =(NODE *) malloc(sizeof(NODE)); printf("Enter data for new Node\n"); scanf("%d",&p->data); p->next = NULL; temp->next = p; temp = p; temp->next = NULL; printf("inserted %d\n",temp->data); } } void travel(){ NODE *temp; temp=HEAD; int l=0; while(temp!=NULL){ printf("%d element is %d\n",l,temp->data); temp = temp->next; l++; } printf("Length of the linked list is %d\n",l); } int Search(int l){ NODE *temp; temp = HEAD; int flag=0; while(temp!=NULL){ if(temp->data==l){ flag=1; break; } temp = temp->next; } if(flag){ printf("Element found\n"); return 1; } else printf("Sorry!! Element not found\n"); return 0; } void Delete(int key){ NODE *temp,*p,*q; temp = HEAD; int f = Search(key); while(temp->data!=key){ p=temp; temp = temp->next; } q=temp->next; if(q==NULL) p->next=NULL; else p->next=q; //temp->next = temp->next->next; if(f) printf("-------Element removed----------- \n"); else printf("Element not found"); }
C
#include <stdio.h> #include <stdlib.h> int main() { int first_tree = 150; int second_tree = 142; int third_tree = 127; int total_apples = first_tree + second_tree + third_tree; printf("Apples gathered = %d", total_apples); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #define s_laenge_max 100 int gibZahlenEin(double f[]) { int z = 1; int n; int rv = 0; char s[s_laenge_max]; double zahl; printf("Ihre Zahlen\n\n"); do { do { printf("Zahl%d: ", z); fgets(s, s_laenge_max, stdin); fflush(stdin); n = sscanf(s, "%lf", &zahl); } while (n < 1); if (zahl > 0) { f[rv] = zahl; rv = rv + 1; z = z + 1; } } while (rv <= 1000 && zahl >= 0); return rv; } double berechneMittelwert(double f[], int anzahl) { double ze = 0; double rv= 0; for(int i = 0; i < anzahl; i++) { ze = ze + f[i]; } rv = ze / anzahl; return rv; } double berechneStdAbw(double f[], int anzahl, double mittelwert) { double ze; double rv; for(int i = 0; i < anzahl; i++) { ze = ze + pow((f[i] - mittelwert), 2); } rv = ze / anzahl; rv = sqrt (rv); return rv; } int main () { double f[999]; int anzahl; double mittelwert; double stdAbw; anzahl = gibZahlenEin(f); mittelwert = berechneMittelwert(f, anzahl); printf("\n\tMittelwert = %.3lf\n", mittelwert); stdAbw = berechneStdAbw(f, anzahl, mittelwert); printf("\tStellenabweichnug = %.3lf\n", stdAbw); return 0; }
C
/* Chapter 3 Exercises 3, 4, 5 */ #include <stdio.h> int main(void) { /* Exercise 3 */ // int i, j, k; // printf("Enter an int: "); // scanf("%d", &i); // printf("Enter another int: "); // scanf(" %d", &j); // printf("%d,%d", i, j); // printf("Enter 3 ints: "); // scanf("%d -%d -%d", &i, &j, &k); // float a, b; // printf("Enter two floats: "); // scanf("%f, %f", &a, &b); /* Exercise 4 */ int i; float x, y; // printf("type in: 10.3 5 6 :"); // scanf("%d%f%d", &i, &x, &j); // printf("%d|%f|%d", i, x, j); /* As Expected */ printf("type in: 12.3 45.6 789 :"); scanf("%f%d%f", &x, &i, &y); printf("%f|%d|%f", x, i, y); /* As Expected */ return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <sys/types.h> #include <unistd.h> #include <sys/wait.h> #include <dirent.h> #include <errno.h> int main(int argc, char* argv []){ pid_t child; int status; if(argc != 2){ printf("usage: tryit command\n"); exit(3); } if((child = fork())){ /*parent*/ if(child == -1){ perror("fork"); exit(EXIT_FAILURE); } if(-1 == wait(&status)){ perror("wait"); exit(3); } if(!WIFEXITED(status) || WEXITSTATUS(status)){ printf("Process %d exited with an error value.\n", child); exit(3); }else{ printf("Process %d succeeded.\n", child); exit(0); } }else{ /*child*/ execl(argv[1], argv[1], (char*)NULL); perror(argv[1]); exit(3); } return 1; /*should never get here*/ }
C
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #define UNIX #include <CAENHVWrapper.h> #include <watchHV.h> int main() { // set params to default values // options: ISet, MaxV, RUp, RDwn, Trip, VSet int res = -1; float ISet = 200., MaxV = 1800., RUp = 100., RDwn = 150., VSet = 10.; for (ushort chNum = 0; chNum <= 3; chNum++) { // ISet; default: 200. uA res = initSettings(chNum, "ISet", ISet); sleep(2); if (res == CAENHV_OK) { printf("Ch %d: Successfully set ISet to %.2f uA\n", chNum, ISet); } else { printf("Ch %d: ERROR. Could not set ISet\n", chNum); } // MaxV; default: 1800. V res = initSettings(chNum, "MaxV", MaxV); sleep(2); if (res == CAENHV_OK) { printf("Ch %d: Successfully set MaxV to %.2f V\n", chNum, MaxV); } else { printf("Ch %d: ERROR. Could not set MaxV\n", chNum); } // RUp; default: 100. V/s res = initSettings(chNum, "RUp", RUp); sleep(2); if (res == CAENHV_OK) { printf("Ch %d: Successfully set RUp to %.2f V/s\n", chNum, RUp); } else { printf("Ch %d: ERROR. Could not set RUp\n", chNum); } // RDwn; default: 150. V/s res = initSettings(chNum, "RDwn", RDwn); sleep(2); if (res == CAENHV_OK) { printf("Ch %d: Successfully set RDwn to %.2f V/s\n", chNum, RDwn); } else { printf("Ch %d: ERROR. Could not set RDwn\n", chNum); } // VSet; default: 10. V (to avoid Ovv when turned on) res = initSettings(chNum, "VSet", VSet); sleep(2); if (res == CAENHV_OK) { printf("Ch %d: Successfully set VSet to %.2f V\n", chNum, VSet); } else { printf("Ch %d: ERROR. Could not set VSet\n", chNum); } } return res; }
C
#include <stdio.h> int main() { int n,temp,i=0,j,r[20],seed=1; scanf("%d",&n); temp=n; while(temp) { r[i++]=temp%10; temp/=10; } for(j=0;j<i;j++) { seed=seed*r[j]; } printf("%d\n",seed*n); return 0; }
C
#define _CRT_SECURE_NO_WARNINGS 1 //дһжһַǷΪһַתַ֮ //磺s1 = AABCDs2 = BCDAA1 //s1 = abcds2 = ACBD0. //AABCDһַõABCDA //AABCDַõBCDAA //AABCDһַõDAABC //#include<stdio.h> //#include<string.h> //#include<Windows.h> //#include<stdlib.h> //int fun(char str1[], char str2[]) //{ // int n1 = strlen(str1); // //int n2 = strlen(str2); // int i, j; // //if (n1 != n2) return 0; // for (i = 1; i <= n1; i++) // { // { // int tem = str1[0]; // for (j = 0; i < n1 - 1; j++) // { // str1[j] = str1[j + 1]; // } // str1[n1 - 1] = tem; // } // if (0 == strcmp(str1, str2)) // { // return 1; // } // } // return 0; //} //int main() //{ // char s1[10] = "AABCD"; // char s2[10] = "BCDAA"; // printf("%s\n", s1); // printf("%s\n", s2); // printf("%d\n", fun(s1, s2)); // system("pause"); // return 0; //} //#include<stdio.h> //#include<string.h> //#include<Windows.h> //void left_move(char* str, int k)//strַ //{ // while (k != 0){ // char* cur = str; // char tmp = *cur; // while ((*(cur + 1)) != '\0'){ // *cur = *(cur + 1); // cur++; // } // *(cur) = tmp; // k--; // } //} //int Judge_string(char* str, const char* p)//жϺ //{ // int i; // if (strlen(str) != strlen(p)){ return 0; } // for (i = 1; i <= strlen(str); i++){ // left_move(str, 1); // if (strcmp(str, p) == 0)//strcmpжstrַǷpַͬ // { // return 1; // } // } // return 0; //} //int main() //{ // char str1[] = "abcd"; // char str2[] = "cdab"; // printf("%d\n", Judge_string(str1, str2)); // system("pause"); // return 0; //} //#include<stdio.h> //void left_move(char* p, int n) //{ // int i = 0; // for (i = 0; i < n; i++) // { // char tmp = *p; // int j = 0; // while (*(p + 1 + j)) // { // *(p + j) = *(p + j + 1); // j++; // } // *(p + j) = tmp; // } //} //int main() //{ // char arr[] = "ABCD"; // int num = 0; // printf("ת:"); // scanf("%d", &num); // left_move(arr, num); // printf("תַ"); // printf("%s\n", arr); // return 0; //} //#include<stdio.h> //#define ROW 4 //#define COL 4 //int Yang(int arr[ROW][COL], int n) { // int i = 0, j = COL-1; // int tmp = arr[i][j]; // while (1) { // if (tmp == n) { return 1; } // else if (tmp < n && j >= 0) // { // tmp = arr[++i][j]; // } // else if (tmp > n&& j >= 0) // { // tmp = arr[i][--j]; // } // else { return 0; } // } //} //int main() //{ // int a[ROW][COL] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16 }; // int i = 0, j = 0, num; // printf("array is:\n"); // for (i = 0; i < ROW; i++) // { // for (j = 0; j < COL; j++) // { // printf("%5d", a[i][j]); // } // printf("\n"); // } // printf("please enter:"); // scanf("%d", &num); // if (Yang(a, num)) { // printf("%dڸ\n", num); // } // else // { // printf("%dڸ\n", num); // } // return 0; //} //#include<stdio.h> //int main() //{ // char c = '0'; // printf("%d %d", sizeof(c), sizeof(char)); // return 0; //} #include<stdio.h> int main() { int i = 1, j = 1, k = 2; if ((j++ || k++) && i++) printf("%d,%d,%d\n", i, j, k); return 0; }
C
#define _CRT_SECURE_NO_WARNINGS 1 #pragma warning(disable:4996) // #include <stdio.h> #include <windows.h> #include <math.h> void change1(int* x, int* y); void change2(int* x, int* y); void change3(int* x, int* y); int main() { int x = 0, y = 0; printf(":"); scanf("%d%d", &x, &y); change1(&x, &y); printf("%d %d\n", x, y); system("pause"); return 0; } void change1(int* x, int* y)//Ƚϲõķ { *x = *x + *y; *y = *x - *y; *x = *x - *y; } void change2(int* x, int* y)//õķ { int tmp = *x; *x = *y; *y = tmp; } void change3(int* x, int* y)//Ƚķ { *x = *x ^ *y; *y = *x ^ *y; *x = *x ^ *y; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ struct bstr {scalar_t__ len; unsigned int* start; } ; /* Variables and functions */ int bstr_parse_utf8_code_length (unsigned int) ; int bstr_decode_utf8(struct bstr s, struct bstr *out_next) { if (s.len == 0) return -1; unsigned int codepoint = s.start[0]; s.start++; s.len--; if (codepoint >= 128) { int bytes = bstr_parse_utf8_code_length(codepoint); if (bytes < 1 || s.len < bytes - 1) return -1; codepoint &= 127 >> bytes; for (int n = 1; n < bytes; n++) { int tmp = (unsigned char)s.start[0]; if ((tmp & 0xC0) != 0x80) return -1; codepoint = (codepoint << 6) | (tmp & ~0xC0); s.start++; s.len--; } if (codepoint > 0x10FFFF || (codepoint >= 0xD800 && codepoint <= 0xDFFF)) return -1; // Overlong sequences - check taken from libavcodec. // (The only reason we even bother with this is to make libavcodec's // retarded subtitle utf-8 check happy.) unsigned int min = bytes == 2 ? 0x80 : 1 << (5 * bytes - 4); if (codepoint < min) return -1; } if (out_next) *out_next = s; return codepoint; }
C
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> int main(int argc, char const *argv[]) { char frases[5][50],nomeArquivo[30],c; printf("Nome do arquivo> " ); fgets(nomeArquivo,sizeof(nomeArquivo),stdin); int j = 0; for (size_t i = 0; i < 5; i++) { printf("%zu frase >",i ); scanf("%s",frases[i] ); } FILE *fp = fopen(nomeArquivo,"w"); for (size_t i = 0; i < 5; i++) { j = 0; fprintf(fp, "%lu",strlen(frases[i]) ); fprintf(fp, "%s"," " ); while (j < strlen(frases[i])) { c = frases[i][j]; c = toupper(c); fprintf(fp, "%c",c ); j++; } fprintf(fp, "%c",'\n' ); } fclose(fp); int aux = 0; fp = fopen(nomeArquivo,"r"); for (size_t i = 0; i < 5; i++) { aux = 0; fscanf(fp,"%d",&aux); //c=fgetc(fp); while (aux>-1) { if((c = fgetc(fp)) != ' ') printf("%c",c ); aux--; } printf("\n"); } fclose(fp); return 0; }
C
#include <stdio.h> #define MAXLINE 1000 /* maximum input line length */ int getlinep(char *, int); void copy(char to[], char from[]); /* print the longest input line */ main() { char s[MAXLINE], maxs[MAXLINE]; int len, max; max = 0; while ((len = getlinep(s, MAXLINE)) > 0) { if (len > max) { max = len; copy(maxs, s); } } printf("\nResult: %s", maxs); return 0; } /* getline: read a line into s, return length */ int getlinep(char *s, int lim) { int c; char *sc = s; while (--lim > 0 && (c = getchar()) != EOF && c != '\n') { *s++ = c; } if (c == '\n') { *s++ = c; } *s = '\0'; return s - sc; } void copy(char to[], char from[]) { int i; i = 0; while ((to[i] = from[i]) != '\0') ++i; }
C
// Stack using Linked List #include<stdio.h> #include<stdlib.h> typedef struct Stack { int data; struct Stack *next; }Stack; Stack *top = NULL; Stack* newNode() { Stack *temp=(Stack *)malloc(sizeof(Stack)); temp->data=0; temp->next=NULL; return temp; } int stack_empty() { if(top==NULL) { return 1; } return 0; } void push() { printf("\nEnter data to be inserted:"); Stack * temp=newNode(); scanf("%d",&temp->data); temp->next=top; if(top==NULL) { top=temp; return; } top=temp; } void pop() { if(stack_empty()) { printf("Stack Underflow!!!"); return; } printf("\nThe data popped of is\n"); printf("%d",top->data); Stack * temp = top; top=top->next; free(temp); } void peek() { if(stack_empty()) { printf("Stack Empty ! \nNothing to show!!"); return; } Stack * temp = top; printf("\nThe data Elements are:\n"); while(temp!=NULL) { printf("%d\t",temp->data); temp=temp->next; } } void main() { int choice=-1; while(choice!=4) { printf("\nWelcome to stack implementation using linked lists:-"); printf("\nThe Operations are:-"); printf("\n1->Insert an Element"); printf("\n2->Delete an Element"); printf("\n3->Display the Stack Contents"); printf("\n4->Exit the Menu"); printf("\nEnter your choice:-"); scanf("%d",&choice); switch(choice) { case 1: push(); peek(); break; case 2: pop(); peek(); break; case 3: peek(); break; case 4: printf("\nExiting the Menu\n\tThanku!!"); break; default:printf("Wrong choice Entered!!"); exit(0); } } }
C
#include <unistd.h> //biblioteca necessárioa para chamar a função write. void ft_putstr(char *str) //definindo a função void com um ponteiro tipo char como parâmetro. { int i = 0; //definindo uma variável tipo int para servir de ponto de partida para a repetição while while (str[i] != '\0') //repetição while que percorre os valores da string até e encontrar o valor '\0'(ultimo valor de uma string). { write(1, &str[i], 1); //função write que imprime o valor contido no endereçço do ponteiro str para cada valor de 'i'. i++; //incremento da variável 'i' para fazer o loop percorrer os valores. } }
C
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* reverseKGroup(struct ListNode* head, int k) { if(head == NULL) return head; const int MAX = 8192; //length of linked list int i = 0, len = 0; struct ListNode *ptrArr[MAX], *pre, *cur = (struct ListNode *)malloc(sizeof(struct ListNode)); while (head) { ptrArr[len++] = head; head = head->next; } int tail = len - len%k; while(i < tail){ if ((i+1) % k == 0){ for (int j=0; j<k; j++){ pre = cur; pre->next = cur = ptrArr[i-j]; } } i++; } if(tail < len){ cur->next = ptrArr[tail]; }else{ cur->next = NULL; } free(cur); if(len < k){ return ptrArr[0]; } else{ return ptrArr[k-1]; } }
C
/** * @file send_data.c * @author Zuber Ahmed * @brief Source code to send data serially using USART with a set BAUD rate * @version 0.1 * @date 2021-07-28 * * @copyright Copyright (c) 2021 * */ #include "send_data.h" void USART_initialization(uint16_t baud_rate) { UBRR0L = baud_rate; /// Setting the Baud Rate for the Transmission UBRR0H = (baud_rate>>8)&(0x00FF); /// Setting the Baud Rate for the Transmission UCSR0C |= (1<<UMSEL00) | (1<<UCSZ01) | (1<<UCSZ00); /// Setting Asynchronous USART, 8-bit Data UCSR0B |= (1<<TXEN0) | (1<<TXCIE0); /// Enabling Transmitter, and it's respective interrupt } void Write_char_usart(char data) { while(Transmission_check) /// Checking if Transmission is complete { } UDR0 = data; /// Sending the data to the UDR0 register } void Manage_display(int option){ USART_initialization(103); /// Intializing with 9600 Baud, Baud Rate = 103 if(option == 1) /// Logic to Display the Temperature 20 °C { Write_char_usart('2'); Write_char_usart('0'); Write_char_usart(' '); Write_char_usart('C'); Write_char_usart(' '); } if(option == 2) /// Logic to Display the Temperature 25 °C { Write_char_usart('2'); Write_char_usart('5'); Write_char_usart(' '); Write_char_usart('C'); Write_char_usart(' '); } if(option == 3) /// Logic to Display the Temperature 29 °C { Write_char_usart('2'); Write_char_usart('9'); Write_char_usart(' '); Write_char_usart('C'); Write_char_usart(' '); } if(option == 4) /// Logic to Display the Temperature 33 °C { Write_char_usart('3'); Write_char_usart('3'); Write_char_usart(' '); Write_char_usart('C'); Write_char_usart(' '); } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/time.h> #define PORT 1111 int main(){ struct timeval start, intermediate, stop; int clientSocket, ret; struct sockaddr_in serverAddr; char buffer[1024] = {0}; char s1[10], s2[10]; if((clientSocket = socket(AF_INET, SOCK_STREAM, 0)) < 0){ perror("socket failed."); exit(EXIT_FAILURE); } memset(&serverAddr, '\0', sizeof(serverAddr)); serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(PORT); serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); if((ret = connect(clientSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr))) < 0){ perror("connection failed."); exit(EXIT_FAILURE); } printf("Send the request.\n"); scanf("%s", s2); while(1){ FILE *file; // printf("Enter file name : "); // scanf("%s %s", s1, s2); gettimeofday(&start, NULL); send(clientSocket, s2, strlen(s2), 0); gettimeofday(&intermediate, NULL); if(strcmp(buffer, ":exit") == 0){ close(clientSocket); printf("[-]Disconnected from server.\n"); exit(1); } if(recv(clientSocket, buffer, 1024, 0) < 0){ printf("[-]Error in receiving data.\n"); } else{ file = fopen("values.csv", "a"); fprintf(file, "%s\n", buffer); fclose(file); printf("Data received back from Server : %s\n", buffer); } gettimeofday(&stop, NULL); printf("Sending time:%lu Response Time:%lu\n", (intermediate.tv_sec - start.tv_sec)*1000000 + (intermediate.tv_usec - start.tv_usec), (stop.tv_sec - intermediate.tv_sec)*1000000 + (stop.tv_usec - intermediate.tv_usec)); } return 0; }
C
#include "unity.h" #include "blhm.h" #include <stdio.h> int cmp_key(int m, int r) { return m - r; } size_t int_map_hash(int m) { return m; } HASH_MAP(int_map, int, int, int_map_hash, cmp_key, 16, 1024); struct int_map a; void setUp(void) { int_map_init(&a); } void tearDown(void) { int_map_free(&a); } void test_num_buckets() { TEST_ASSERT_EQUAL(int_map_num_buckets(&a), 16); } void test_set_and_find() { int_map_set(&a, 5, 50); // Find pointer and find achieve the same thing with different behaviours. // Test both here TEST_ASSERT_EQUAL(*int_map_find_ptr(&a, 5), 50); int found_value; TEST_ASSERT_EQUAL(int_map_find(&a, 5, &found_value), true); TEST_ASSERT_EQUAL(found_value, 50); TEST_ASSERT_EQUAL(int_map_count(&a), 1); } void test_set_and_replacement_and_find() { int_map_set(&a, 5, 50); int_map_set(&a, 5, 20); // Find pointer and find achieve the same thing with different behaviours. // Test both here TEST_ASSERT_EQUAL(*int_map_find_ptr(&a, 5), 20); int found_value; TEST_ASSERT_EQUAL(int_map_find(&a, 5, &found_value), true); TEST_ASSERT_EQUAL(found_value, 20); TEST_ASSERT_EQUAL(int_map_count(&a), 1); } void test_find_missing_element() { // Find pointer and find achieve the same thing with different behaviours. // Test both here TEST_ASSERT_EQUAL(int_map_find_ptr(&a, 5), NULL); int found_value; TEST_ASSERT_EQUAL(int_map_find(&a, 5, &found_value), false); TEST_ASSERT_EQUAL(int_map_count(&a), 0); } void test_set_and_remove() { int_map_set(&a, 5, 50); int_map_remove(&a, 5); TEST_ASSERT_EQUAL(int_map_find_ptr(&a, 5), NULL); TEST_ASSERT_EQUAL(int_map_count(&a), 0); } void test_remove_nothing() { int_map_remove(&a, 5); TEST_ASSERT_EQUAL(int_map_count(&a), 0); } void test_set_and_remove_nothing() { int_map_set(&a, 5, 50); int_map_remove(&a, 10); TEST_ASSERT_EQUAL(*int_map_find_ptr(&a, 5), 50); TEST_ASSERT_EQUAL(int_map_count(&a), 1); } void test_add_two_remove_one() { int_map_set(&a, 5, 50); int_map_set(&a, 6, 50); int_map_remove(&a, 5); TEST_ASSERT_EQUAL(int_map_find_ptr(&a, 5), NULL); TEST_ASSERT_EQUAL(*int_map_find_ptr(&a, 6), 50); TEST_ASSERT_EQUAL(int_map_count(&a), 1); } /// This test makes sure that data doesn't get corrupted even in loaded buckets void test_remove_from_loaded_buckets() { // Load up a map for (size_t i = 0; i < 10000; i++) { int_map_set(&a, i, i + 10); } // Delete the middle element int_map_remove(&a, 5000); // Check for consistency for (size_t i = 0; i < 10000; i++) { int* found_ptr = int_map_find_ptr(&a, i); if (i == 5000) { TEST_ASSERT_EQUAL(found_ptr, NULL); } else { TEST_ASSERT_EQUAL(*found_ptr, i + 10); } } TEST_ASSERT_EQUAL(int_map_count(&a), 9999); } void test_change_key() { int_map_set(&a, 5, 50); int_map_change_key(&a, 5, 10); TEST_ASSERT_EQUAL(*int_map_find_ptr(&a, 10), 50); TEST_ASSERT_EQUAL(int_map_count(&a), 1); } void test_change_missing_key() { int_map_change_key(&a, 5, 10); TEST_ASSERT_EQUAL(int_map_count(&a), 0); } void test_change_one_in_two() { int_map_set(&a, 5, 50); int_map_set(&a, 10, 100); int_map_change_key(&a, 5, 15); TEST_ASSERT_EQUAL(*int_map_find_ptr(&a, 15), 50); TEST_ASSERT_EQUAL(int_map_count(&a), 2); } void test_change_replace() { int_map_set(&a, 5, 50); int_map_set(&a, 10, 100); int_map_change_key(&a, 5, 10); TEST_ASSERT_EQUAL(*int_map_find_ptr(&a, 10), 50); TEST_ASSERT_EQUAL(int_map_count(&a), 1); } /// This test makes sure that data doesn't get corrupted even in loaded buckets void test_change_inloaded_buckets() { // Load up a map for (size_t i = 0; i < 10000; i++) { int_map_set(&a, i, i + 10); } // Delete the middle element int_map_change_key(&a, 5000, 0); // Check for consistency for (size_t i = 0; i < 10000; i++) { int* found_ptr = int_map_find_ptr(&a, i); if (i == 0) { TEST_ASSERT_EQUAL(*found_ptr, 5010); } else if (i == 5000) { TEST_ASSERT_EQUAL(found_ptr, NULL); } else { TEST_ASSERT_EQUAL(*found_ptr, i + 10); } } TEST_ASSERT_EQUAL(int_map_count(&a), 9999); } /// Sanity test that we haven't bungled up globals and can have coexisting maps void test_init_many() { struct int_map b, c, d; int_map_init(&b); int_map_init(&c); int_map_init(&d); for (size_t i = 0; i < 100; i++) { int_map_set(&b, i, i); } for (size_t i = 0; i < 1000; i++) { int_map_set(&c, i, i + 1); } for (size_t i = 0; i < 10000; i++) { int_map_set(&d, i, i + 2); } for (size_t i = 0; i < 100; i++) { TEST_ASSERT_EQUAL((*int_map_find_ptr(&b, i)) + 1, (*int_map_find_ptr(&c, i))); } for (size_t i = 0; i < 1000; i++) { TEST_ASSERT_EQUAL((*int_map_find_ptr(&c, i)) + 1, (*int_map_find_ptr(&d, i))); } for (size_t i = 0; i < 10000; i++) { TEST_ASSERT_EQUAL(*int_map_find_ptr(&d, i), i + 2); } TEST_ASSERT_EQUAL(int_map_count(&b), 100); TEST_ASSERT_EQUAL(int_map_count(&c), 1000); TEST_ASSERT_EQUAL(int_map_count(&d), 10000); int_map_free(&b); int_map_free(&c); int_map_free(&d); } void test_general_usage() { int_map_set(&a, 5, 10); int_map_set(&a, 10, 10); int_map_set(&a, 5, 50); int_map_set(&a, 10, 5); TEST_ASSERT_EQUAL(*int_map_find_ptr(&a, 5), 50); TEST_ASSERT_EQUAL(*int_map_find_ptr(&a, 10), 5); TEST_ASSERT_EQUAL(int_map_find_ptr(&a, 13210), NULL); TEST_ASSERT_EQUAL(int_map_find_ptr(&a, 132111), NULL); int value; TEST_ASSERT_EQUAL(int_map_find(&a, 5, &value), true); TEST_ASSERT_EQUAL(value, 50); TEST_ASSERT_EQUAL(int_map_find(&a, 10, &value), true); TEST_ASSERT_EQUAL(value, 5); TEST_ASSERT_EQUAL(int_map_find(&a, 24123123, &value), false); TEST_ASSERT_EQUAL(int_map_find(&a, 231312, &value), false); int_map_remove(&a, 5); TEST_ASSERT_EQUAL(int_map_find_ptr(&a, 5), NULL); TEST_ASSERT_EQUAL(*int_map_find_ptr(&a, 10), 5); printf("Remove 5\n"); int_map_remove(&a, 5); TEST_ASSERT_EQUAL(int_map_find_ptr(&a, 5), NULL); TEST_ASSERT_EQUAL(*int_map_find_ptr(&a, 10), 5); printf("Remove 10\n"); int_map_remove(&a, 10); TEST_ASSERT_EQUAL(int_map_find_ptr(&a, 10), NULL); TEST_ASSERT_EQUAL(int_map_find_ptr(&a, 10), NULL); } int touched = 0; int deleted = 0; bool delete_callback(struct int_map_entry* v) { touched += 1; return v->key % 2; } void post_delete_callback(struct int_map_entry* v) { deleted += 1; } void test_delete_matching() { // Load up a map for (size_t i = 0; i < 10000; i++) { int_map_set(&a, i, i); } int_map_delete_matching(&a, delete_callback, post_delete_callback ); //Test that we deleted every even key and that the map is smaller because of it TEST_ASSERT_EQUAL(touched, 10000); TEST_ASSERT_EQUAL(deleted, 5000); TEST_ASSERT_EQUAL(int_map_count(&a), 5000); }
C
#include <stdio.h> int main(){ int ind[] = {0, 2}; int x[3][4] = {{0,1,2,3},{4,5,6,7},{8,9,10,11}}; printf(x[ind]); }
C
#include "../../lib/test_lib.h" #include "../../libmx.h" char *test_case_name = "mx_binary_search"; // Tests void test_binary_search() { // Given char *arr[] = {"222", "Abcd", "aBc", "ab", "az", "z"}; int count= 0; // When int result = mx_binary_search(arr, 6, "ab", &count); // Then ASSERT_EQUALS(3, result); ASSERT_EQUALS(3, count); } void test_binary_search_2() { // Given char *arr[] = {"222", "Abcd", "aBc", "ab", "az", "z"}; int count= 0; // When int result = mx_binary_search(arr, 6, "aBc", &count); // Then ASSERT_EQUALS(2, result); ASSERT_EQUALS(1, count); } void test_binary_search_3() { // Given char *arr[] = {"222", "abcd", "aBc", "ab", "az", "z"}; int count= 0; // When int result = mx_binary_search(arr, 6, "aBz", &count); // Then ASSERT_EQUALS(-1, result); ASSERT_EQUALS(0, count); }
C
#include "ClientReadBuffer.H" #include "ClientChannel.H" #include "util.H" int ClientReadBuffer::hasCompleteMessage () { unsigned int headerLength, dataLength, trailerLength; return locateMessage (buffer_ + start_, buffer_ + start_ + length_, headerLength, dataLength, trailerLength); } int ClientReadBuffer::locateMessage(const unsigned char *start, const unsigned char *end, unsigned int &headerLength, unsigned int &dataLength, unsigned int &trailerLength) { unsigned int size = end - start; if (size < 4) return 0; if (firstMessage_) { if (size < 12) return 0; if (*start == 0x42) bigEndian_ = 1; else bigEndian_ = 0; channel_->setBigEndian(bigEndian_); dataLength = 12 + RoundUp4(GetUINT(start + 6, bigEndian_)) + RoundUp4(GetUINT(start + 8, bigEndian_)); } else { dataLength = (GetUINT(start + 2, bigEndian_) << 2); if (dataLength == 0) { // probably this application is using big request extension // we need to get the new request size; but read more bytes first if (size >= 8) { dataLength = (GetULONG (start + 4, bigEndian_) << 2); } } } if (size < dataLength) return 0; firstMessage_ = 0; headerLength = 0; trailerLength = 0; return 1; }
C
#include<stdio.h> //输入十个整数,将最小的与第一个交换,把最大的与最后一个交换。写三个函数:(1)输入十个数;(2)进行处理;(3)输出10个数。 void myScan(int *p, int n); void myPrint(int **p, int n); void covrt(int **p, int n); void myScan(int *p, int n) { int i = 0; while(i < n) { printf("输入第%d个数:", i+1); scanf("%d", p+i); i++; } } void myPrint(int **p, int n) { for(int i = 0; i < 10; i++) { printf("%d ", **(p+i)); } printf("\n"); } void covrt(int **p, int n) { int i, **min, **max, *temp; min = p; max = p; for(i = 0; i < 10; i++) { if(**min > **(p+i)) { min = p + i; } if(**max < **(p+i)) { max = p + i; } } temp = *p; *p = *min; *min = temp; //《学习辅导》,加一个判断,解决冲突 if(max == p) { max = min; } temp = *(p+n-1); *(p+n-1) = *max; *max = temp; } int main() { int a[10], *b[10], **p, i; p = b; for(i = 0; i < 10; i++) { *(p+i) = &a[i]; } myScan(a, 10); myPrint(b, 10); covrt(b, 10); myPrint(b, 10); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_del.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: oltkache <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/05/27 14:57:18 by oltkache #+# #+# */ /* Updated: 2018/05/27 14:57:19 by oltkache ### ########.fr */ /* */ /* ************************************************************************** */ #include "asm.h" void ft_del_arg(t_lb *a) { t_lb *tmp; while (a) { tmp = a->next; ft_strdel(&(a->name)); free(a); a = tmp; } } void ft_del_op(t_lb *op) { t_lb *tmp; while (op) { tmp = op->next; ft_strdel(&(op->name)); ft_del_arg(op->op); free(op); op = tmp; } } void ft_del_lb(t_lb *l) { t_lb *tmp; while (l) { tmp = l->next; ft_strdel(&(l->name)); ft_del_op(l->op); free(l); l = tmp; } } void ft_del_lst(t_list *lst) { t_list *tmp; while (lst) { tmp = lst->next; ft_strdel((char**)(&(lst->content))); free(lst); lst = tmp; } } void ft_del_all(t_list *lst, t_lb *lb, char *name) { ft_del_lb(lb); ft_del_lst(lst); ft_strdel(&(name)); }
C
// Lstipple.c // OpenGL SuperBible, Chapter 4 // Demonstrates line stippling // Program by Richard S. Wright Jr. #include <windows.h> #include <gl/gl.h> #include <gl/glu.h> #include <gl/glut.h> #include <math.h> // Define a constant for the value of PI #define GL_PI 3.1415f // Rotation amounts static GLfloat xRot = 0.0f; static GLfloat yRot = 0.0f; // Called to draw scene void RenderScene(void) { GLfloat y; // Storeage for varying Y coordinate GLint factor = 1; // Stippling factor GLushort pattern = 0x5555; // Stipple pattern // Clear the window with current clearing color glClear(GL_COLOR_BUFFER_BIT); // Save matrix state and do the rotation glPushMatrix(); glRotatef(xRot, 1.0f, 0.0f, 0.0f); glRotatef(yRot, 0.0f, 1.0f, 0.0f); // Enable Stippling glEnable(GL_LINE_STIPPLE); // Step up Y axis 20 units at a time for(y = -90.0f; y < 90.0f; y += 20.0f) { // Reset the repeat factor and pattern glLineStipple(factor,pattern); // Draw the line glBegin(GL_LINES); glVertex2f(-80.0f, y); glVertex2f(80.0f, y); glEnd(); factor++; } // Restore transformations glPopMatrix(); // Flush drawing commands glutSwapBuffers(); } // This function does any needed initialization on the rendering // context. void SetupRC() { // Black background glClearColor(0.0f, 0.0f, 0.0f, 1.0f ); // Set drawing color to green glColor3f(0.0f, 1.0f, 0.0f); } void SpecialKeys(int key, int x, int y) { if(key == GLUT_KEY_UP) xRot-= 5.0f; if(key == GLUT_KEY_DOWN) xRot += 5.0f; if(key == GLUT_KEY_LEFT) yRot -= 5.0f; if(key == GLUT_KEY_RIGHT) yRot += 5.0f; if(key > 356.0f) xRot = 0.0f; if(key < -1.0f) xRot = 355.0f; if(key > 356.0f) yRot = 0.0f; if(key < -1.0f) yRot = 355.0f; // Refresh the Window glutPostRedisplay(); } void ChangeSize(int w, int h) { GLfloat nRange = 100.0f; // Prevent a divide by zero if(h == 0) h = 1; // Set Viewport to window dimensions glViewport(0, 0, w, h); // Reset coordinate system glMatrixMode(GL_PROJECTION); glLoadIdentity(); // Establish clipping volume (left, right, bottom, top, near, far) if (w <= h) glOrtho (-nRange, nRange, -nRange*h/w, nRange*h/w, -nRange, nRange); else glOrtho (-nRange*w/h, nRange*w/h, -nRange, nRange, -nRange, nRange); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } int main(int argc, char* argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutCreateWindow("Stippled Line Example"); glutReshapeFunc(ChangeSize); glutSpecialFunc(SpecialKeys); glutDisplayFunc(RenderScene); SetupRC(); glutMainLoop(); return 0; }
C
#include<stdio.h> #include<conio.h> main() { int sum=0,temp,n,r; printf("Enter the number:\n"); scanf("%d",&n); temp=n; while(temp!=0) { r=n%10; n=n/10; sum=sum+(r^3); } if(sum==temp) printf("%d is armstrong number"); else printf("%d is not an armstrong number"); }
C
#include <stdio.h> #include "SDL.h" #include "SDL_image.h" extern unsigned long long int tsCount(); extern void fadeShiftAsm(unsigned char *buf, const int width, const int height); void fadeShiftC(unsigned char* buf, int width, int height) { unsigned long long int size = width * height; while (size--) { *(buf) = (*buf / 4) * 3 + (*(buf + 50) / 4); ++buf; } } SDL_Surface* loadImage(const char *fileName) { return IMG_Load(fileName); } void Paint(SDL_Surface* image, SDL_Surface* screen) { SDL_BlitSurface(image, NULL, screen, NULL); SDL_UpdateRect(screen, 0, 0, 0, 0); }; int main(const int argc, const char **argv) { SDL_Event event; SDL_Init(SDL_INIT_VIDEO); SDL_Surface *image = loadImage(argv[1]); SDL_WM_SetCaption(argv[1], "lab8"); SDL_Surface *screen = SDL_SetVideoMode(image->w, image->h, 8, (Uint32) SDL_SWSURFACE); if (image->format->palette) { SDL_SetColors(screen, image->format->palette->colors, 0, image->format->palette->ncolors); } Paint(image, screen); unsigned long long int timerStart = 0, timerEnd = 0; int done = 0; while (!done) { if (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYUP: switch (event.key.keysym.sym) { case SDLK_q: done = 1; break; case SDLK_f: SDL_LockSurface(image); timerStart = tsCount(); fadeShiftC(image->pixels, image->w, image->h); timerEnd = tsCount(); printf("C done in %llu cycles.\n", timerEnd - timerStart); SDL_UnlockSurface(image); Paint(image, screen); break; case SDLK_g: SDL_LockSurface(image); timerStart = tsCount(); fadeShiftAsm(image->pixels, image->w, image->h); timerEnd = tsCount(); printf("Asm done in %llu cycles.\n", timerEnd - timerStart); SDL_UnlockSurface(image); Paint(image, screen); break; case SDLK_r: image = loadImage(argv[1]); Paint(image, screen); printf("\nReloaded!\n\n"); break; default: break; } break; case SDL_QUIT: done = 1; break; default: break; } } } SDL_FreeSurface(image); SDL_Quit(); return 0; }
C
/* * SPDX-FileCopyrightText: 2020-2022 Espressif Systems (Shanghai) CO LTD * * SPDX-License-Identifier: Apache-2.0 */ #ifndef LIBUNWIND_H #define LIBUNWIND_H #include "sdkconfig.h" #include <stddef.h> #include <stdint.h> #if CONFIG_IDF_TARGET_ARCH_RISCV #include "libunwind-riscv.h" #elif CONFIG_IDF_TARGET_X86 #include "libunwind-x86.h" #else /* This header must be a standalone one, so, it shall not trigger an error when * pre-processed without including any of the architecture header above. * The implementation can trigger a compile error if UNW_UNKNOWN_TARGET * macro is defined. */ #define UNW_UNKNOWN_TARGET 1 typedef void* ExecutionFrame; #endif #ifdef __cplusplus extern "C" { #endif /* Error codes returned by the functions defined below */ #define UNW_ESUCCESS 0 #define UNW_EUNSPEC 1 /* General failure */ #define UNW_EBADREG 3 /* Register given is wrong */ #define UNW_ESTOPUNWIND 5 #define UNW_EINVAL 8 /* Bad parameter or unimplemented operation */ #define UNW_EBADVERSION 9 #define UNW_ENOINFO 10 /* A libunwind context is the equivalent of an ESP-IDF ExecutionFrame */ typedef ExecutionFrame unw_context_t; /* A register number is an unsigned word in our case */ typedef uint32_t unw_regnum_t; /* In our current implementation, a cursor is the same as a context */ typedef unw_context_t unw_cursor_t; /* long should represent the size of a CPU register */ typedef unsigned long unw_word_t; /* At the moment, we don't support the operations using the following types, * so just set them to void* */ typedef void* unw_addr_space_t; typedef void* unw_fpreg_t; /** * @brief Get the current CPU context. * * @param[out] ctx Pointer to `unw_context_t` structure. It must not be NULL * as it will be filled with the CPU registers value * * @return UNW_ESUCCESS on success, -UNW_EUNSPEC if ctx is NULL * * @note This function MUST be inlined. Marking it as "static inline" or * __attribute__((always_inline)) does not guarantee that it will inlined by * the compiler for all the architectures. Thus, define this function as a macro. * @note If the caller of this function returns, all the pointers, contexts, cursors * generated out of the initial returned context shall be considered invalid and * thus, must **not** be used. */ #define unw_getcontext(ctx) ({ int retval; \ if (ctx == NULL) { \ retval = -UNW_EUNSPEC; \ } else { \ UNW_GET_CONTEXT(ctx); \ retval = UNW_ESUCCESS; \ } \ retval; \ }) /** * @brief Initialize a cursor on a local context. Multiple cursor can be initialized on * a given CPU context, they can then be manipulated independently. * * @param[out] c Pointer on cursor to be returned. Must not be NULL * @param[in] ctx Pointer on the context returned by the function `unw_getcontext` * * @return UNW_ESUCCESS on success, -UNW_EUNSPEC if one of the parameter is NULL. */ int unw_init_local(unw_cursor_t* c, unw_context_t* ctx); /** * @brief Perform a step "up" on the given cursor. After calling this function, the * cursor will point to the caller's CPU context. Thus, it is then possible * to retrieve the caller's address by getting the PC register out of the cursor. * Check `unw_get_reg` function for this. * * @param[in] cp Current cursor * * @returns 0 if the previous frame was the last one * @returns Positive value on success * @returns -UNW_EBADVERSION if the DWARF information's version is not compatible with the eh_frame_parser implementation * @returns -UNW_ENOINFO if the caller information are not present in the binary. (if the caller is in ROM for example) * @returns -UNW_ESTOPUNWIND if unwinding is terminated */ int unw_step(unw_cursor_t* cp); /** * @brief Get the value of a CPU register from a given cursor. * * @param[in] cp Pointer to the cursor * @param reg Register number to retrieve the value of * @param[out] valp Pointer that will be filled with the register value * * @returns UNW_ESUCCESS on success * @returns -UNW_EUNSPEC if any pointer passed is NULL * @returns -UNW_EBADREG if the register number is invalid */ int unw_get_reg(unw_cursor_t* cp, unw_regnum_t reg, unw_word_t* valp); /** * @brief Set the value of a CPU register in a given cursor. * * @param[in]cp Pointer to the cursor * @param reg Register number to set the value of * @param val New register value * * @returns UNW_ESUCCESS on success * @returns -UNW_EUNSPEC if the pointer passed is NULL * @returns -UNW_EBADREG if the register number is invalid */ int unw_set_reg(unw_cursor_t* cp, unw_regnum_t reg, unw_word_t val); #endif // LIBUNWIND_H
C
//@File: vars00.c // // The {\tt vars00} program first allocates a number of variables in the // Real-Time database and then randomly reads values of variables // while collecting data to evaluate response times. //@ #define VERSMAJ 1 #define VERSMIN 1 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <errno.h> #include <signal.h> #include <time.h> #include <sys/time.h> #include "base/msglib.h" char MyName[10]; // //+Entry help // // help prints an usage message // static void help() { printf("\nVARS00 - %s. L.Fini\n\n",GetVersionID()); printf("Elementary tests on variable creation and accessing\n\n"); printf("Usage: vars00 [-c <cnt>] [-v] [-d delay] <Num> [<server>]\n\n"); printf(" vars00 -h print an help message\n\n"); printf(" -v verbose mode.\n"); printf(" -c <cnt> Stop after cnt read requests.\n"); printf(" -d delay Specify delay time (seconds. Fractions allowed).\n\n"); printf(" <num> Use different <num> for concurrent vars: this\n"); printf(" argument is REQUIRED!\n"); printf(" <server> Server numeric address (default: \"127.0.0.1\")\n\n"); printf("The program must be stopped with Ctrl-C or sending the INT signal.\n\n"); } //+Entry doquit // // Signal handler for ctrl-C stopping // MsgBuf msgb; double dsec,maxtime,mintime,avgtime; long seconds,useconds,nsec,nusec; struct timeval before,after; int count; int verbose=0,silent=0; static void doquit(int thesig) { if(count>0) avgtime = avgtime /(double)count; printf("\n %d messages. round-trip min/avg/max %f/%f/%f\n", count,mintime,avgtime,maxtime); exit(0); } static int DisplayVariables() { Variable *TheVar; if(WaitMsgFromServer(&msgb) !=NO_ERROR) { printf("Error from server\n\n"); return 0; } gettimeofday(&after,NULL); if(hdr_CODE(msgb)==VARREPLY) { TheVar=(Variable *)msg_BODY(msgb); nsec=after.tv_sec-before.tv_sec; // Compute delay nusec=after.tv_usec-before.tv_usec; dsec = (double)nsec*1000.0 +(double)nusec*0.001; if(dsec>maxtime) maxtime=dsec; // Cumulate statistics if(dsec<mintime)mintime=dsec; avgtime += dsec; if(verbose) { int i; printf("%s cnt:%d time:%f (ms) Value: ", TheVar->H.Name,count,dsec); if(TheVar->H.Type==INT_VARIABLE) for(i=0;i<TheVar->H.NItems;i++) printf(" %ld",TheVar->Value.Lv[i]); else if(TheVar->H.Type==REAL_VARIABLE) for(i=0;i<TheVar->H.NItems;i++) printf(" %.2f",TheVar->Value.Dv[i]); else if(TheVar->H.Type==CHAR_VARIABLE) for(i=0;i<TheVar->H.NItems;i++) printf(" %s",TheVar->Value.Sv); else { printf("Bad variable buffer format\n"); } printf("\n"); } } else { printf("Unexpected message from server:\n"); printf(" From: %s\n",hdr_FROM(msgb)); printf(" to: %s\n",hdr_TO(msgb)); printf(" SeqNum: %d\n",hdr_SEQN(msgb)); printf(" Code: %x\n",hdr_CODE(msgb)); printf(" pLoad: %d\n",hdr_PLOAD(msgb)); printf(" MsgLen: %d\n\n",hdr_LEN(msgb)); } return 1; } //+Main: Test Msgd-RTDB variable management // // This program connects to the MsgD-RTDB process to test the // variable management. // // First it creates a number of variables, then accesses at random for // reading // #define MAX_VARS 100 char VarName[MAX_VARS][VAR_NAME_LEN+1]; int main(int argc, char **argv) { int i,Nvars,stat; double rfact; double secdelay=1.0; char *server; int stopcnt=0, cnt=1; struct timespec delay; SetVersion(VERSMAJ,VERSMIN); i=1; for(i=1;i<argc;i++) { // Process command arguments if(*argv[i] != '-') break; if(strcmp(argv[i],"-v")==0) verbose=1; if(strcmp(argv[i],"-c")==0) { cnt=atoi(argv[++i]); stopcnt=1; } if(strcmp(argv[i],"-s")==0) verbose=0; if(strcmp(argv[i],"-h")==0) { help(); exit(0); } if(strcmp(argv[i],"-d")==0) secdelay=atof(argv[++i]); } if(i>=argc) { help(); return 1; } stat=atoi(argv[i++]); if(i>=argc) server="127.0.0.1"; else server=argv[i++]; Nvars=20; delay.tv_sec=floor(secdelay); // Set delay time secdelay -= delay.tv_sec; delay.tv_nsec=(secdelay*1.0e+9); signal(SIGINT,doquit); // Install signal handler for quitting sprintf(MyName,"VARS00-%2.2d",stat); if(verbose) printf("%s connecting to server at: %s ...",MyName,server); // Connect to MsgDRTDB server if((stat=ConnectToServer(server,MyName,1))!=NO_ERROR) { printf("Error connecting to server at: %s\n",server); printf("Error code: %d - %s\n\n",stat,strerror(errno)); return 1; } if(verbose) printf("done!\n"); InitMsgBuf(&msgb,0); // Initialize the message structure for(i=0;i<Nvars;i++) { int j; snprintf(VarName[i],VAR_NAME_LEN+1,"%s.%4.4d",MyName,i); if(i%2) { long VLong[7]; for(j=0;j<7;j++) VLong[j]=i*1000+j; if(verbose) printf("Creating INT variable: %s\n",VarName[i]); stat=CreaVar(MyName,VarName[i],INT_VARIABLE, "P",7,&msgb); if(stat==NO_ERROR) stat=SetVar(MyName,VarName[i],INT_VARIABLE, 7,VLong,&msgb); } else { double VDouble[5]; for(j=0;j<5;j++) VDouble[j]=i+0.01*j; if(verbose) printf("Creating REAL variable: %s\n",VarName[i]); stat=CreaVar(MyName,VarName[i],REAL_VARIABLE, "P",5,&msgb); if(stat==NO_ERROR) stat=SetVar(MyName,VarName[i],REAL_VARIABLE, 5,VDouble,&msgb); } if(IS_ERROR(stat)) printf("Error creating variable %s: %d\n",VarName[i],stat); } mintime=10000000; maxtime=0.0; avgtime=0.0; count=0; rfact=(double)Nvars/((double)(RAND_MAX)+1.0); if(verbose) printf("\n"); while(cnt) { if(stopcnt) cnt--; nanosleep(&delay,NULL); i= random() * rfact; sprintf(VarName[i],"%s.%4.4d",MyName,i); gettimeofday(&before,NULL); stat=GetVar(MyName,VarName[i],count,&msgb); if(DisplayVariables()==0) break; count++; } doquit(0); return 0; }
C
#include <stdio.h> #include<math.h> int main() { int a,b,c,lar,sec_large,small; printf("Enter sides of tringle"); scanf("%d%d%d",&a,&b,&c); if(a==b&&b==c) printf("Equilateral"); else if(a==b||b==c||c==a) printf("Isoceles"); else printf("Scalene"); lar = a>b?(a>c?a:c):(b>c?b:c); sec_large = a>b?(b>c?b:(c>a?a:c)):(a>c?a:(c>b?b:c)); small = a<b?(a<c?a:c):(b<c?b:c); printf("%d%d%d",lar,sec_large,small); if(pow(small,2) + pow(sec_large,2)== pow(lar,2)) printf("Right angle triangle"); return 0; }
C
/* * Pipeline.c * * Created: 04.11.2017 16:46:16 * Author: Alex */ #include "Pipeline.h" S_EFF_PARAMS eff_params[EFFECT_COUNT]; static uint8_t g_eff_indx = 0; static uint8_t g_total_effects = 0; void build_effect_pipeline() { // eff_params[g_total_effects].init_callback = init_color_swap; eff_params[g_total_effects].effect_type = COLOR_SWAP_EFF; g_total_effects++; // eff_params[g_total_effects].init_callback = init_fire_effect; eff_params[g_total_effects].effect_type = FLASH_EFF; g_total_effects++; // Rainbow HsvColor hsvc = {0, 200, 255}; pack_color(eff_params[g_total_effects].step_params.packed_params, hsvc); eff_params[g_total_effects].init_callback = rainbow_init_effect; eff_params[g_total_effects].effect_type = RAINBOW_EFF; g_total_effects++; // Flash eff_params[g_total_effects].init_callback = init_strobo_flash; eff_params[g_total_effects].effect_type = FLASH_EFF; g_total_effects++; } void run_pipeline() { // S_EFF_PARAMS *p_eff_params = &eff_params[g_eff_indx]; // p_eff_params->init_callback(&p_eff_params->step_params); // for(uint16_t ic = 0; ic < p_eff_params->step_params.n_eff_step_count; ic++) { p_eff_params->step_params.step_callback(); } // if(++g_eff_indx == g_total_effects) { g_eff_indx = 0; } }
C
bool isUgly(int num) { if(num==1) return true; while(num!=2 && num!=3 && num!=5 && num!=0){ if(num%2==0) num/=2; else if(num%3==0) num/=3; else if(num%5==0) num/=5; else return false; } if(num!=0) return true; else return false; }
C
/* FULLY AUTOMATIC VENDING MACHINE – dispenses your cuppa on just press of button. A vending machine can serve range of products as follows: Coffee Espresso Coffee Cappuccino Coffee Latte Coffee Tea Plain Tea Assam Tea Ginger Tea Cardamom Tea Masala Tea Lemon Tea Green Tea Organic Darjeeling Tea Soups Hot and Sour Soup Veg Corn Soup Tomato Soup Spicy Tomato Soup Beverages Hot Chocolate Drink Badam Drink Badam-Pista Drink Write a program to take input for main menu & sub menu and display the name of sub menu selected in the following format (enter the first letter to select main menu): Welcome to CCD Enjoy your Example 1: Input: c 1 Output Welcome to CCD! Enjoy your Espresso Coffee! Example 2: Input t 9 Output INVALID OUTPUT! */ #include <stdio.h> #include <ctype.h> // for tolower(), toupper() int main(void){ char c[3][25] = {"Espresso Coffee", "Cappuccino Coffee", "Latte Coffee"}; char t[8][25] = {"Plain Tea", "Assam Tea", "Ginger Tea", "Cardamom Tea", "Masala Tea", "Lemon Tea", "Green Tea", "Organic Darjeeling Tea"}; char s[4][25]={"Hot and Sour Soup","Veg Corn Soup","Tomato Soup","Spicy Tomato Soup"}; char b[3][25]={"Hot Chocolate Drink","Badam Drink","Badam-Pista Drink"}; char ch; int item ,i; scanf("%c", &ch); scanf("%d", &item); // Coffee if (tolower(ch) == 'c'){ for(i=0; i<3; i++){ if(item == i+1){ printf("Welcome to CCD\nEnjoy your %s!\n", c[i]); break; } } if (i == 3){ printf("INVALID OPTION!\n"); } } // Tea if (tolower(ch)=='t'){ for (i = 0; i<8; i++){ if (item == i+1){ printf("Welcome to CCD\nEnjoy your %s!\n", t[i]); break; } } if (i == 8){ printf("INVALID OPTION!\n"); } } // Soups if (tolower(ch)=='s'){ for (i = 0; i<4; i++){ if (item == i+1){ printf("Welcome to CCD\nEnjoy your %s!\n", s[i]); break; } } if (i == 4){ printf("INVALID OPTION!\n"); } } //Beverages if (tolower(ch)=='b'){ for (i = 0; i<3; i++){ if (item == i+1){ printf("Welcome to CCD\nEnjoy your %s!\n", t[i]); break; } } if (i == 3){ printf("INVALID OPTION!\n"); } } }
C
// Figure 9-37. A program with system-call int main(int argc *char argv[]) { int fd, n = 0; char buf[1]; fd = open("data", 0); if (fd < 0) { printf("Bad data file\n"); exit(1); } else { while (1) { read(fd, buf, 1); if (buf[0] == 0) { close(fd); printf("n = %d\n", n); exit(0); } n = n + 1; } } }
C
// common.h -- Defines typedefs and some global functions. // From JamesM's kernel development tutorials. #ifndef COMMON_H #define COMMON_H // this is a macro which calls the panic function and automatically // specifies the line and the file of the MACRO usage #define PANIC(msg) panic(msg, __FILE__, __LINE__); #define USIGNED_INT_MAX 0xFFFFFFFF // Some nice typedefs, to standardise sizes across platforms. // These typedefs are written for 32-bit X86. typedef unsigned int u32int; typedef int s32int; typedef unsigned short u16int; typedef short s16int; typedef unsigned char u8int; typedef char s8int; // https://wiki.osdev.org/I/O_Ports // An I/O port is usually used as a technical term for a specific address on the // x86's IO bus. This bus provides communication with devices in a fixed order // and size, and was used as an alternative to memory access. // // https://stackoverflow.com/questions/3215878/what-are-in-out-instructions-in-x86-used-for // The term "port" is coined in the intel manuals. // outb - output a byte to a port // with "b" meaning byte void outb(u8int value, u16int port); // outw - output a WORD (16 bit) to a port // and "w" meaning word (16 bits). void outw(u16int value, u16int port); // outl - output a DWORD to a port // and "l" meaning long (32 bits). void outl(u32int value, u16int port); // inb - read a byte from a port u8int inb(u16int port); // inw - read a word from a port // "w" meaning word (16 bits) u16int inw(u16int port); // inl - read a DWORD from a port // "l" meaning DWORD (32 bits) u32int inl(u16int port); // check if the bit BIT in FLAGS is set. #define CHECK_FLAG(flags, bit) ((flags) & (1 << (bit))) // video memory begins here. #define VGA_ADDRESS 0xB8000 // VGA provides support for 16 colors */ #define BLACK 0 #define GREEN 2 #define RED 4 #define YELLOW 14 #define WHITE_COLOR 15 unsigned short *terminal_buffer; unsigned int vga_index; // Some screen stuff. // The number of columns. #define COLUMNS 80 // The number of lines. #define LINES 24 // The attribute of an character. #define ATTRIBUTE 7 // The video memory address. #define VIDEO 0xB8000 // Variables. // Save the X position. int xpos; // Save the Y position. int ypos; // Point to the video memory. volatile unsigned char *video; void k_cls(void); void k_itoa(char *buf, int base, int d); void k_putchar(int c); void k_printf(const char *format, ...); void k_memcpy(u8int *dest, const u8int *src, u32int len); void k_memset(u8int *dest, u8int val, u32int len); int k_strcmp(char *str1, char *str2); char *k_strcpy(char *dest, const char *src); char *k_strcat(char *dest, const char *src); void k_print_float(float data); extern void panic(const char *message, const char *file, u32int line); #endif // COMMON_H
C
/* A biblioteca padrão da linguagem C possui muito poucas funções para manipulação de cadeias de caracteres. Uma das funções muito comumente utilizadas em manipulação de strings é a função trim, que remove espaços e tabulações no início e fim de uma cadeia de caracteres. Essa função é geralmente utilizada para "corrigir" eventuais erros na entrada de dados de usuário. Assim sendo, a aplicação da função na cadeia de caracteres " Estruturas de Dados 1 " retornaria uma cadeia de caracteres "Estruturas de Dados 1" Escreva uma função strtrim que recebe um ponteiro para uma cadeia de caracteres destino e um ponteiro para uma cadeia de caracteres de origem e escreva no destino a mesma cadeia sem espaços no início e fim da cadeia. Considere como espaço em branco além do caracter de espaço os caracteres '\t', '\n', '\r' Em seguida, escreva um programa que leia uma sequencia de linhas de texto da entrada padrão e imprima o resultado da aplicação da função strtrim em cada linha. */ #include <stdio.h> #include <stdlib.h> #include "strtrim.c" int main(void) { char *entrada[50]; scanf("%s*c", entrada); printf("Entrada: %s - %u\n", entrada, strlen(entrada)); strtrim(entrada, entrada); printf("Saída: %s - %u\n", entrada, strlen(entrada)); return 0; }
C
#ifndef INODE_H #define INODE_H #include <unistd.h> #include <sys/types.h> typedef struct inode { mode_t mode; //read/write/execute uid_t uid; // user ID of the file owner off_t size; // size of the file in bytes time_t atime; // last access time time_t ctime; // creation time time_t mtime; // last modification time time_t dtime; // deletion time gid_t gid; // group ID of the file dev_t dev; // ID of device containing file nlink_t links_count; // number of hard links pointing to this file int num_blocks; // number of blocks allocated to this file int flags; // file = 1 directory = 0 int blocks_off; // offset for the data block offsets. } inode; #endif
C
/* The kernel call implemented in this file: * m_type: SYS_VIRCOPY * * The parameters for this kernel call are: * m5_l1: CP_SRC_ADDR source offset within userspace * m5_i1: CP_SRC_ENDPT source process endpoint * m5_l2: CP_DST_ADDR destination offset within userspace * m5_i2: CP_DST_ENDPT destination process endpoint * m5_l3: CP_NR_BYTES number of bytes to copy */ #include "systask.h" #undef EXTERN #define EXTERN extern #include "../../glo.h" #if (USE_VIRCOPY || USE_PHYSCOPY) /*===========================================================================* * st_copy * *===========================================================================*/ int st_copy(message *m_ptr) /* pointer to request message */ { proc_usr_t *src_ptr, *dst_ptr; int src_nr, dst_nr, rcode ; struct vir_cp_req req, *req_ptr; MUKDEBUG(MSG5_FORMAT, MSG5_FIELDS(m_ptr)); /*!!!!!!!!!!!!!! VERIFICAR QUE EL M_SOURCE/REQUESTER TENGA PRIVILEGIOS !!!!!!!!!!!!!!!!!!!!*/ req_ptr = &req; req_ptr->src.proc_nr_e = m_ptr->CP_SRC_ENDPT; req_ptr->dst.proc_nr_e = m_ptr->CP_DST_ENDPT; req_ptr->count = m_ptr->CP_NR_BYTES; if( req_ptr->src.proc_nr_e == SELF) req_ptr->src.proc_nr_e = sys_who_e; if( req_ptr->dst.proc_nr_e == SELF) req_ptr->dst.proc_nr_e = sys_who_e; MUKDEBUG(VIRCP_FORMAT, VIRCP_FIELDS(req_ptr)); /* Parameter checking */ if( (req_ptr->src.proc_nr_e == req_ptr->dst.proc_nr_e) || (req_ptr->src.proc_nr_e == ANY) || (req_ptr->dst.proc_nr_e == ANY) || (req_ptr->src.proc_nr_e == NONE) || (req_ptr->dst.proc_nr_e == NONE) ) ERROR_RETURN(EDVSENDPOINT); src_nr = _ENDPOINT_P(req_ptr->src.proc_nr_e); dst_nr = _ENDPOINT_P(req_ptr->dst.proc_nr_e); CHECK_P_NR(src_nr); /* check process number limits */ CHECK_P_NR(dst_nr); /* check process number limits */ src_ptr = PROC2PTR(src_nr); MUKDEBUG("SRC " PROC_USR_FORMAT,PROC_USR_FIELDS(src_ptr)); dst_ptr = PROC2PTR(dst_nr); MUKDEBUG("DST " PROC_USR_FORMAT,PROC_USR_FIELDS(dst_ptr)); if( src_ptr->p_rts_flags == SLOT_FREE) ERROR_RETURN(EDVSSRCDIED); if( dst_ptr->p_rts_flags == SLOT_FREE) ERROR_RETURN(EDVSDSTDIED); if ( req_ptr->count <= 0 ) ERROR_RETURN(EDVSINVAL); if ( req_ptr->count > MAXCOPYLEN ) ERROR_RETURN(E2BIG); /* Now try to make the actual virtual copy. */ MUK_vcopy( rcode, req_ptr->src.proc_nr_e, m_ptr->CP_SRC_ADDR, req_ptr->dst.proc_nr_e, m_ptr->CP_DST_ADDR, req_ptr->count); return(rcode); } #endif /* (USE_VIRCOPY || USE_PHYSCOPY) */
C
/* record.h * purpose and definitions: * - record structure * - parses records * - sets the address for emittion * - emits record adresses * global variables: * LC_old , LC_cur , assembly , second_pass * Author: Nick Stanwood **********************************************************************************/ #ifndef RECORD_H #define RECORD_H #include <ctype.h> #include "instruction.h" #include "operand.h" #define SR 2 #define PC 0 extern int As_val[]; extern int Ad_val[]; struct record{ char line[256]; char dir[6]; //largest directive is 5 char long struct instruction inst; char label[33]; //maximum size of a label is 32 struct op src; struct op dst; bool error; }; extern unsigned int LC_cur; extern unsigned int LC_old; bool second_pass; bool error_flag; /*this struct gets its data set for the current record being parsed*/ extern struct record assembly; /* print_record() * prints a parsed record to the .LIS file with the addressing modes * of each operand and the LC * for debugging purposes */ extern void print_record(void); /* parse_record() * dissects a record into its constituent parts * as it goes through it checks for possible errors such as: * - more than one label on a line * - too many operands */ void parse_record(void); /* clear_record() * sets all int values in the global struct record assembly to 0 * and all strings to empty strings */ void clear_record(void); /* set_adddress() * used on the second pass only, creates the address to be * emitted with the Location Counter for each instruction */ void set_address(void); #endif
C
#include <stdio.h> #include <math.h> int a = 0; int y = 0; int z = 0; double x = 0; int main(void) { printf("a = "); scanf("%d", &a); printf("y = "); scanf("%d", &y); printf("z = "); scanf("%d", &z); if (pow(y,2)-(2*a) <= 0) { printf("Виконується логарифмування числа, меншого за нуль"); return 1; } x = a*sqrt(pow(y,2)-(2-a))+pow(cos(z),2); printf("\nx = %f\n", x); return 0; }
C
#ifndef LOGGING_H #define LOGGING_H #include <bwio.h> #include "arm_lib.h" #include "syscall.h" #define LOGLEVEL_NONE 0 // logging off #define FATAL_RAINBOW 0 // Alleviate pain caused by fatal errors // Sending a fatal message implies execution cannot continue. // The same is true for failed asserts. In both of these cases // we exit the task if the processor is in user mode, or panic // the kernel if the processor is not in user mode. #define LOGLEVEL_FATAL 1 // Log fatal messages only #define LOGLEVEL_ERROR 2 // above + error messages #define LOGLEVEL_WARN 3 // above + warning messages #define LOGLEVEL_LOG 4 // above + general logs #define LOGLEVEL_DEBUG 5 // above + debug messages // Foreground Colors #define BLACK_TEXT "\033[30m" #define RED_TEXT "\033[31m" #define GREEN_TEXT "\033[32m" #define YELLOW_TEXT "\033[33m" #define BLUE_TEXT "\033[34m" #define MAGENTA_TEXT "\033[35m" #define CYAN_TEXT "\033[36m" #define WHITE_TEXT "\033[37m" // Background Colors #define BLACK_BACKGROUND "\033[40m" #define RED_BACKGROUND "\033[41m" #define GREEN_BACKGROUND "\033[42m" #define YELLOW_BACKGROUND "\033[43m" #define BLUE_BACKGROUND "\033[44m" #define MAGENTA_BACKGROUND "\033[45m" #define CYAN_BACKGROUND "\033[46m" #define WHITE_BACKGROUND "\033[47m" #define RESET_FORMATTING "\033[0m" #ifndef VERBOSITY #define VERBOSITY LOGLEVEL_NONE #endif #define PRINTLOG(type, msg, ...) { \ bwprintf(COM2, "%s:<%s:%d> - ", type, __FILE__, __LINE__); \ bwprintf(COM2, msg, ##__VA_ARGS__); \ bwprintf(COM2, "\n\r"); \ } // Prints with colored text, resets formatting #define PRINTLOGCOLOR(text_color, type, msg, ...) { \ bwprintf(COM2, RESET_FORMATTING); \ bwprintf(COM2, text_color); \ bwprintf(COM2, "%s:<%s:%d> - ", type, __FILE__, __LINE__); \ bwprintf(COM2, msg, ##__VA_ARGS__); \ bwprintf(COM2, RESET_FORMATTING); \ bwprintf(COM2, "\n\r"); \ } // Prints with colored text and background, resets formatting #define PRINTLOGFULLCOLOR(text_color, background_color, type, msg, ...) { \ bwprintf(COM2, RESET_FORMATTING); \ bwprintf(COM2, background_color); \ bwprintf(COM2, text_color); \ bwprintf(COM2, "%s:<%s:%d> - ", type, __FILE__, __LINE__); \ bwprintf(COM2, msg, ##__VA_ARGS__); \ bwprintf(COM2, RESET_FORMATTING); \ bwprintf(COM2, "\n\r"); \ } // Prints with rainbow text, resets formatting #define PRINTLOGRAINBOW(type, msg, ...){ \ bwprintf(COM2, RESET_FORMATTING); \ bwprintf(COM2, RED_TEXT); \ bwprintf(COM2, "%s:<%s:%d> - ", type, __FILE__, __LINE__); \ for(int i = 0; msg[i]; i++) { \ switch(i%6) \ { \ case 0: bwprintf(COM2, RED_TEXT); break; \ case 1: bwprintf(COM2, YELLOW_TEXT); break; \ case 2: bwprintf(COM2, GREEN_TEXT); break; \ case 3: bwprintf(COM2, CYAN_TEXT); break; \ case 4: bwprintf(COM2, BLUE_TEXT); break; \ case 5: bwprintf(COM2, MAGENTA_TEXT); break; \ } \ /*bwprintf(COM2, "\033[3");*/ \ /*bwputc(COM2, '0' + i%6 + 1);*/ \ /*bwprintf(COM2, "m");*/ \ bwputc(COM2, msg[i]); \ } \ bwprintf(COM2, RESET_FORMATTING); \ bwprintf(COM2, "\n\r"); \ } #if VERBOSITY >= LOGLEVEL_FATAL #define FATAL(msg, ...) { \ if(FATAL_RAINBOW) { PRINTLOGRAINBOW("FATAL", msg, ##__VA_ARGS__); }\ else { PRINTLOGFULLCOLOR(BLACK_TEXT, RED_BACKGROUND, "FATAL", msg, ##__VA_ARGS__); }\ if (!user_mode()) panic(); \ Exit(); \ } #define assert(cond) { \ if (!(cond)) { \ if(FATAL_RAINBOW) { PRINTLOGRAINBOW("FATAL - ASSERT FAILED", #cond); } \ else { PRINTLOGFULLCOLOR(BLACK_TEXT, RED_BACKGROUND, "FATAL - ASSERT FAILED", #cond); } \ if (!user_mode()) panic(); \ Exit(); \ } \ } #else #define FATAL(msg, ...) { } #define assert(cond, ...) { } #endif #if VERBOSITY >= LOGLEVEL_ERROR #define ERROR(msg, ...) { PRINTLOGCOLOR(RED_TEXT, "ERROR", msg, ##__VA_ARGS__) } #else #define ERROR(msg, ...) { } #endif #if VERBOSITY >= LOGLEVEL_WARN #define WARN(msg, ...) { PRINTLOGCOLOR(YELLOW_TEXT, "WARN", msg, ##__VA_ARGS__) } #else #define WARN(msg, ...) { } #endif #if VERBOSITY >= LOGLEVEL_LOG #define LOG(msg, ...) { PRINTLOGCOLOR(WHITE_TEXT, "LOG", msg, ##__VA_ARGS__) } #else #define LOG(msg, ...) { } #endif #if VERBOSITY >= LOGLEVEL_DEBUG #define DEBUG(msg, ...) { PRINTLOGCOLOR(MAGENTA_TEXT, "DEBUG", msg, ##__VA_ARGS__) } #else #define DEBUG(msg, ...) { } #endif #define print(msg, ...) { bwprintf(COM2, msg, ##__VA_ARGS__); } #endif
C
/******************************************************************************* Header Files *******************************************************************************/ #include <stdio.h> #include <stdlib.h> /******************************************************************************* List Structure *******************************************************************************/ typedef struct Node { int data; struct Node* next; } Node_t; /******************************************************************************* Function Prototypes *******************************************************************************/ void Insert(Node_t** headPtr, int x); void Reverse(Node_t** headPtr); void Print(Node_t* head); /******************************************************************************* Main *******************************************************************************/ int main() { Node_t* head = NULL; Insert(&head, 2); Insert(&head, 4); Insert(&head, 6); Insert(&head, 5); Print(head); Reverse(&head); printf("Reversing List...\n"); Print(head); } /******************************************************************************* Insert Function *******************************************************************************/ void Insert(Node_t** headPtr, int x) { Node_t* temp = (Node_t*)malloc(sizeof(Node_t)); temp->data = x; temp->next = *headPtr; *headPtr = temp; } /******************************************************************************* Reverse Function *******************************************************************************/ void Reverse(Node_t** headPtr) { Node_t *current, *prev, *next; current = *headPtr; prev = NULL; while (current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } *headPtr = prev; } /******************************************************************************* Print Function *******************************************************************************/ void Print(Node_t* head) { printf("List is:"); while (head != NULL) { printf(" %d", head->data); head = head->next; } printf("\n"); }
C
float pp1(int n) { int i; float s; for (i=1;i<=n;i++) s+=(float)1/i; return s; } float dequy(int n) { if (n==1) return 1; return (1/(float)n)+dequy(n-1); } main() { int n; printf("Nhap n : "); scanf("%d",&n); printf("\nPhuong phap 1 : S=%f",pp1(n)); printf("\nDe quy : S=%f",dequy(n)); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX(x, y) ((x) > (y) ? (x) : (y)) int main() { int cases; while (scanf("%d", &cases) != EOF && cases) { int book[2000] = { 0 }, max = -1, max_num = -1, max_left = -1, max_right = -1; int original_cases = cases; while (cases--) { int temp; scanf("%d", &temp); if (book[temp] == 0) { book[temp] = cases; } else { if (MAX(book[temp] - cases, max) > max) { max = MAX(book[temp] - cases, max); max_left = original_cases - book[temp] - 1; max_right = original_cases - cases - 1; max_num = temp; } } } if (max_num != -1) printf("(%d,%d):%d\n", max_left, max_right, max_num); else printf("No solution\n"); } return 0; }
C
#include<pthread.h> #include<semaphore.h> #include<stdio.h> const int max=10; pthread_mutex_t m1=PTHREAD_MUTEX_INITIALIZER; sem_t s1; void* efun1(void* pv) //producer { int i; printf("A--welcome\n"); pthread_mutex_lock(&m1); for(i=1;i<=max;i++) { printf("A--%d\n",i); sleep(1); } pthread_mutex_unlock(&m1); sem_post(&s1); //pthread_exit(NULL); } void* efun2(void* pv) //consumer { int i; printf("B--welcome,waiting for semaphore\n"); sem_wait(&s1); //changing sequence lead to deadlock pthread_mutex_lock(&m1); for(i=1;i<=max;i++) { printf("B--%d\n",i); sleep(1); } pthread_mutex_unlock(&m1); //pthread_exit(NULL); } int main() { printf("main--Welcome\n"); pthread_t pt1,pt2; //thread handles sem_init(&s1,0,0); pthread_create(&pt1,NULL,efun1,NULL); pthread_create(&pt2,NULL,efun2,NULL); pthread_join(pt1,NULL); pthread_join(pt2,NULL); sem_destroy(&s1); pthread_mutex_destroy(&m1); printf("main--Thank you\n"); return 0; }
C
//add characters to char array inside struct #include<stdio.h> #include<string.h> //may be added as well int main(){ struct Ev{ int oda_sayisi; char adres[100]; float metrekare; } test_ev,test_ev2; test_ev.oda_sayisi=4; test_ev.metrekare=120.5; //if you want to work on char array inside a structure //you need use strcpy() to attach value for char array strcpy(test_ev.adres,"Goztepe/Kadikoy"); printf("Numberof room= %d\n",test_ev.oda_sayisi); printf("Metersquare=%f\n",test_ev.metrekare); printf("Adress= %s\n",test_ev.adres); test_ev2.oda_sayisi=5; return 0; }
C
/********************************************************************* * pullup.c : Change the pullup resistor setting for GPIO pin *********************************************************************/ #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <setjmp.h> #include <sys/mman.h> #include <signal.h> #include "gpio_io.c" /* GPIO routines */ #include "timed_wait.c" /* Delay */ /********************************************************************* * 0x7E200094 GPPUD GPIO Pin Pull-up/down Enable * 0x7E200098 GPPUDCLK0 GPIO Pin Pull-up/down Enable Clock 0 *********************************************************************/ #define GPIO_GPPUD *(ugpio+37) #define GPIO_GPPUDCLK0 *(ugpio+38) static inline void gpio_setpullup(int gpio,int pull) { unsigned mask = 1 << gpio; /* GPIOs 0 to 31 only */ unsigned pmask = pull >= 0 ? ( 1 << !!pull ) : 0; GPIO_GPPUD = pmask; /* Select pullup setting */ timed_wait(0,500,0); GPIO_GPPUDCLK0 = mask; /* Set the GPIO of interest */ timed_wait(0,500,0); GPIO_GPPUD = 0; /* Reset pmask */ timed_wait(0,500,0); GPIO_GPPUDCLK0 = 0; /* Set the GPIO of interest */ timed_wait(0,500,0); } /********************************************************************* * Command line arguments are of the form <gpio>={low,high or none}, * for example: ./pullup 7=high 8=low * * Only the first character of the argument after '=' is checked. *********************************************************************/ int main(int argc,char **argv) { int x, gpio, p; char arg[64]; gpio_init(); for ( x=1; x<argc; ++x ) { if ( sscanf(argv[x],"%d=%s",&gpio,arg) != 2 ) goto errxit; if ( *arg == 'n' ) p = -1; else if ( *arg == 'l' || *arg == 'h' ) p = *arg == 'h' ? 1 : 0; else goto errxit; if ( gpio < 0 || gpio > 31 ) { fprintf(stderr,"%s: GPIO must be <= 31\n", argv[x]); return 1; } gpio_setpullup(gpio,p); } return 0; errxit: fprintf(stderr,"Argument '%s' must be in the form\n" " <gpio>=<arg> where arg is h, l or n.\n", argv[x]); return 1; } /********************************************************************* * End pullup.c - by Warren Gay * Mastering the Raspberry Pi, ISBN13: 978-1-484201-82-4 * This source code is placed into the public domain. *********************************************************************/
C
#include"stdafx.h" #include"c.h" #include<stdio.h> #include<stdlib.h> int factorial6_10(int n) { int k, total = 1; for (k = 1; k <= n; k++) total *= k; return total; } void ex6_10() { int num; printf("пJ@Ӽ:"); scanf("%d", &num); printf("Factorial(%d)=%d\n", num, factorial6_10(num)); }
C
////////////////////////////////////////////////////////////// // Accept on number from user if number is less than 10 then print "Hello" otherwise print "Demo". // Author : Annaso Chavan ///////////////////////////////////////////////////////////// #include<stdio.h> void Display(int no) { if(no < 10) { printf("Hello"); } else { printf("Demo"); } } int main() { int iValue = 0; printf("Enter number :"); scanf("%d",&iValue); Display(iValue); return 0; }
C
#include "9cc.h" // 入力プログラム char *user_input; int main(int argc, char **argv) { if (argc != 2) { error("引数の個数が正しくありません"); return 1; } // トークナイズしてパースする user_input = argv[1]; token = tokenize(user_input); Function *pg = program(); codegen(pg); return 0; }
C
#include <stdio.h> #define MAX 64 int team_num(int num);//输入参赛队伍数量 void team_name(char name[][MAX], int num);//输入每个参赛队伍的名称 int arrange(int begin, int num);//对每个参赛队伍进行排序 int show(char name[][MAX], int num);//将结果打印出来 int schedule[MAX][MAX]; int team_num(int num) { int flag = 1; printf("请输入参赛的队伍数量:"); while(flag) { scanf("%d", &num); getchar(); if(num & num -1) { printf("参赛队伍数量必须是2的N次方!!请输入正确的数字:"); } else { flag = 0; } } return num; } int arrange(int begin, int num) { int i, j; if(num == 2) { schedule[begin][1] = begin; schedule[begin][2] = begin+1; schedule[begin+1][1] = begin+1; schedule[begin+1][2] = begin; return 0; } //回溯法(递归函数) arrange(begin, num/2); arrange(begin + num/2, num/2); for(i = begin; i <begin + num/2; i++) { for(j = num/2 + 1; j <= num; j++) { schedule[i][j] = schedule[i + num/2][j -num/2]; } } for(i = begin + num/2; i < begin + num; i++) { for(j = num/2 + 1; j <= num; j++) { schedule[i][j] = schedule[i - num/2][j - num/2]; } } } void team_name(char name[][MAX], int num) { for(int i = 0; i < num; i++) { printf("请输入第%d个参赛队伍的名字:", i+1); scanf("%s", name[i]); getchar(); } } int show(char name[][MAX], int num) { printf("\n\n比赛安排如下:\n"); printf("队 伍"); for(int i = 1; i < num; i++) { printf("\t第%d天", i); } putchar('\n'); for(int i = 1; i <= num; i++) { for(int j = 1; j <= num; j++) { printf("%s\t", name[schedule[i][j]-1]); } putchar('\n'); } return 0; } int main(void) { int num = team_num(num); char name[num][MAX]; team_name(name, num); arrange(1, num); show(name, num); return 0; }
C
#ifndef FILE_ACCESS_IMPL_H #define FILE_ACCESS_IMPL_H typedef struct file_struct{ FILE* fp; unsigned long long size; unsigned long long total_read_size; unsigned long long total_write_size; char fname[FILE_NAME_SIZE]; }file_st; /* モード ファイル 機能 ファイルがないとき * "r" テキスト 読み取り エラー * "w" テキスト 書き込み 新規作成 * "a" テキスト 追加書き込み 新規作成 * "rb" バイナリ 読み取り エラー * "wb" バイナリ 書き込み 新規作成 * "ab" バイナリ 追加書き込み 新規作成 * "r+" テキスト 読み取り及び書き込み エラー * "w+" テキスト 読み取り及び書き込み 新規作成 * "a+" テキスト 追加書き込み 新規作成 * "rb+" バイナリ 読み取り及び書き込み エラー * "wb+" バイナリ 読み取り及び書き込み 新規作成 * "ab+" バイナリ 追加書き込み 新規作成 */ /* "typedef int (*FUNCPTR)(int a,int b);" を定義しておくと * "FUNCPTR"を型として使用できる。 * 例: * * typedef int (*FP_SAMPLE_TYPE)(int a); * * int funcB(int a){ * return a; * } * * void funcA(){ * int ret; * FP_SAMPLE_TYPE sample; * sample = funcB(); * ret = sample(1); * } */ typedef int (*FP_OPEN_TYPE)(file_st** fst, const char* mode_str, const char* fname); typedef int (*FP_CLOSE_TYPE)(file_st* fst); typedef int (*FP_WRITE_TYPE)(file_st* fst, const unsigned char* buf, unsigned long long size); typedef int (*FP_READ_TYPE)(file_st* fst, unsigned char* buf, unsigned char* total_buf, unsigned long long size); typedef int (*FP_GET_SIZE_TYPE)(file_st* fst); typedef int (*FP_GET_TOTAL_READ_TYPE)(file_st* fst); typedef int (*FP_GET_TOTAL_WRITE_TYPE)(file_st* fst); typedef int (*FP_MKDIR_TYPE)(const char* base_dir, const char* add_dir); int openEx(file_st** fst, const char* mode_str, const char* fname); int closeEx(file_st* fst); int writeEx(file_st* fst, const unsigned char* buf, unsigned long long size); int readEx(file_st* fst, unsigned char* buf, unsigned char* total_buf, unsigned long long size); int mkdirEx(const char* base_dir, const char* add_dir); int get_size(file_st* fst); int get_total_read_size(file_st* fst); int get_total_write_size(file_st* fst); #endif /* FILE_ACCESS_IMPL_H */
C
#include "./ext2_find.h" int trobarArxiuExt(int fd, const char *nomArxiu, unsigned int offset, char delete){ int saltsFins1erInode = readInodeSizeExt(fd)*(readFirstInodeExt(fd)-1); int i_block[15]; int counter; int trobat = 0; //Anar al primer inode (Inode 11). int inodeDir= readFirstInodeExt(fd)*readInodeSizeExt(fd); lseek(fd, inodeDir, SEEK_SET); int offset_Al_Inode_Table = 2048 + (readBG_INODE_TABLE_Ext(fd) - 2)*readBlockSize(fd) + saltsFins1erInode; read_i_block(fd, offset_Al_Inode_Table, i_block); char nom[255]; int directory_offset = 2048 + (i_block[0] -3)*readBlockSize(fd); if (offset != 0){ read_i_block(fd, offset, i_block); int grup = (i_block[0] -1)/readBlocksGroup(fd); int block = (i_block[0] -1) - (grup*readBlocksGroup(fd)); directory_offset = 1024 + grup*readBlockSize(fd)*readBlocksGroup(fd) + block*readBlockSize(fd); } //directory_offset = offset; counter = directory_offset; while(counter < (directory_offset + readInodeSizeExt(fd))){ memset(nom, '\0', 255); short nextEntry = read_rec_len(fd, counter); llegirNomArxiu(fd, counter, nom); int filesize = llegirFileSize(fd, counter); if (llegirFileType(fd, counter) == 2) { if ((strcmp(nom, ".") != 0)&&(strcmp(nom, "..") != 0)&&(strcmp(nom,"lost+found") != 0)) { int inodeDest = llegirInode(fd, counter); trobat = trobarArxiuExt(fd, nomArxiu, inodeDest, delete); } }else if (llegirFileType(fd,counter) == 1){ if (strcmp(nom, nomArxiu) == 0) { if (delete) { borrarArxiuExt(fd, counter, directory_offset, offset); printf("El fitxer %s ha estat eliminat.\n", nom); }else{ printf("fitxer trobat. Ocupa %d\n", filesize); } return 1; } } counter += nextEntry; } if ((offset == 0)&&(!trobat)) { printf("Error. Fitxer inexistent\n"); } return 0; }
C
#include "alloc.h" /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int opcode = 0; char words[9]; int main(int argc, char *argv[]) { printf("ԤڳĹĿ¼ﴴһΪ encryptedwords.txt ļд8ֵݣ\n"); printf("ѡ\n1.\n2.\n.˳\n"); scanf("%d",&opcode); switch (opcode) { case 1: simpleencry(); break; case 2: simpledecry(); break; default: return 0; } return 0; }
C
/** * Exercice 1.14 * * Write a program to print a histogram of the frequencies of * different character in its input. * **/ #include <stdio.h> void main() { int c, i, max; int nChar[26]; for (i = 0; i < 27; i++) nChar[i] = 0; while ((c = getchar()) != EOF) { if (c >= 'a' && c <= 'z') nChar[c - 'a']++; else if (c >= 'A' && c <= 'Z') nChar[c - 'A']++; } // print vertical histogram max = nChar[0]; for (i = 0; i < 26; i++) if (max < nChar[i]) max = nChar[i]; putchar('\n'); for (max; max > 0; max--) { for (i = 0; i < 26; i++) { putchar(' '); if (nChar[i] >= max) putchar('*'); else putchar(' '); putchar(' '); } putchar('\n'); } for (i = 0; i < 26; i++) printf("-%c-", 'a' + i); putchar('\n'); }
C
#include "binary_trees.h" #include "binary_level_func.c" /** * binary_tree_levelorder - prints the binary tree by level order * @tree: the node to the tree * @func: function pointer */ void binary_tree_levelorder(const binary_tree_t *tree, void (*func)(int)) { binary_level_t *level_head; if (tree == NULL || func == NULL) return; level_head = malloc(sizeof(binary_level_t)); if (level_head == NULL) binary_level_free(level_head); level_head->right = NULL; level_head->left = NULL; level_head->level = 0; level_head->lvl_val_head = NULL; level_head = binary_tree_level_recur(tree, level_head, 0); print_tree_levels(level_head, func); binary_level_free(level_head); } /** * binary_tree_level_recur - recursive search through a binary tree * @tree: pointer to a node in a tree * @level_head: pointer to a node in level linked list * @lvl: current level of the tree node * * Return: the a pointer to the level linked list */ binary_level_t *binary_tree_level_recur( const binary_tree_t *tree, binary_level_t *level_head, int lvl) { if (tree == NULL || level_head == NULL) return (NULL); binary_tree_val_push(level_head, lvl, tree->n); binary_tree_level_recur(tree->right, level_head, lvl + 1); binary_tree_level_recur(tree->left, level_head, lvl + 1); return (level_head); } /** * print_tree_levels - prints all the trees by level * @level_head: pointer level linked list * @func: pointer to a function */ void print_tree_levels(binary_level_t *level_head, void (*func)(int)) { binary_lvl_val_t *lvl_val_head; while (level_head->left != NULL) level_head = level_head->left; while (level_head != NULL) { lvl_val_head = level_head->lvl_val_head; while (lvl_val_head != NULL) { func(lvl_val_head->n); lvl_val_head = lvl_val_head->next; } level_head = level_head->right; } }
C
/************************** *** ImageColor.c *** *************************/ #include "ImageType/ImageType.h" #include "Image2Tool.h" void image2_average( image_type *im, int x0, int y0, int width, int height, float *av ) { short *sp; float sum; int i, j, n; sum = 0; for( i = 0 ; i < height ; i++ ){ sp = (short *)IMAGE_PIXEL( im, i+y0, x0 ); for( j = 0 ; j < width ; j++, sp++ ){ sum += *sp; } } n = height * width; *av = sum / ( n*16); } image_type * image2_negative( image_type *sim, image_type *im ) { short *sp, *tp; int i, j; im = image_recreate( im, sim->height, sim->width, 2, 1 ); sp = sim->data_s; tp = im->data_s; for( i = 0 ; i < im->row ; i++ ){ for( j = 0 ; j < im->column ; j++, sp++, tp++ ){ *tp = 255*16 - *sp; } } return( im ); } image_type * image2_add_scalar( image_type *sim, int a, image_type *im ) { short *sp, *tp; int i, j, tmp; im = image_recreate( im, sim->height, sim->width, 2, 1 ); sp = sim->data_s; tp = im->data_s; for( i = 0 ; i < im->row ; i++ ){ for( j = 0 ; j < im->column ; j++, sp++, tp++ ){ tmp = *sp + a; *tp = PUSH_TO_RANGE( tmp, 0, 4096 ); } } return( im ); } image_type * image2_contrast( image_type *sim, float a, float b, image_type *im ) { short *sp, *tp; int i, j, tmp; im = image_recreate( im, sim->height, sim->width, 2, 1 ); sp = sim->data_s; tp = im->data_s; for( i = 0 ; i < im->row ; i++ ){ for( j = 0 ; j < im->column ; j++, sp++, tp++ ){ tmp = a* ( (*sp) - b ) + b; *tp = PUSH_TO_RANGE( tmp, 0, 4096 ); } } return( im ); } image_type * image2_enhance( image_type *sim, float a, float b, float m, image_type *im ) { short *sp, *tp; int i, j, tmp; im = image_recreate( im, sim->height, sim->width, 2, 1 ); sp = sim->data_s; tp = im->data_s; for( i = 0 ; i < im->row ; i++ ){ for( j = 0 ; j < im->column ; j++, sp++, tp++ ){ tmp = a* ( (*sp) - m ) + b; *tp = PUSH_TO_RANGE( tmp, 0, 4096 ); } } return( im ); } void image2_var0( image_type *im, int x0, int y0, int width, int height, float av, float *var ) { short *sp; float sum, tmp; int i, j, n; sum = 0; av *= 16; for( i = 0 ; i < height ; i++ ){ sp = (short *)IMAGE_PIXEL( im, i+y0, x0 ); for( j = 0 ; j < width ; j++, sp++ ){ tmp = (int)*sp - av; if( tmp < 0 ) tmp = -tmp; sum += tmp; } } n = height * width; *var = sum / (16*n); } image_type * image2_add( image_type *sim, image_type *im ) { short *sp, *tp; int i, j; if( im == NULL ){ im = image_create( sim->row, sim->column, 2 , 1, NULL ); image2_const( im, 0 ); } sp = sim->data_s; tp = im->data_s; for( i = 0 ; i < im->row ; i++ ){ for( j = 0 ; j < im->column ; j++ ){ *tp++ += *sp++; } } return( im ); } image_type * image2_interpolate( image_type *im0, image_type *im1, image_type *wim, image_type *im) { short *sp0, *sp1, *tp; float *wp; int i, j; im = image_recreate( im, im0->row, im1->column, 2 , 1 ); sp0 = im0->data_s; sp1 = im1->data_s; wp = wim->data_f; tp = im->data_s; for( i = 0 ; i < im->row ; i++ ){ for( j = 0 ; j < im->column ; j++, sp0++, sp1++, wp++, tp++ ){ *tp = ((*sp0)*(*wp) + (*sp1)*(255.0-(*wp)))/255.0; } } return( im ); }
C
//Shrenik Bhatt //Lab5Part1 //This program will be used in order to encrypt a number that has a minimum of 6 digits. it uses a function called add4 in order to add4 to each value. //It also uses a shift function in order to shift the digits to the left. It then uses a print function to print out the results. #include <stdio.h> #include <math.h> //This function takes pointer and sets the value that was inputted to the address at which num exists. void input(int *num){ *num = 0; do{ printf("Please enter an integer greater than 99999: "); scanf ("%d", num); if (*num <= 99999) printf ("Incorrect input.\n"); }while (*num <= 99999); printf("The number entered is %d\n", *num); } int count = 0; //global variable that will be used in add4 function as well as the shift function //This function takes the input given by the user, converts each of the digits into an array // and adds 4 to each digit. It then creates a number once again and returns that integer with the digits added. int add4 (int num){ int tempNum = num; //This loop counts the number of digits while (tempNum > 0){ count +=1; tempNum /= 10; } int length [count]; //declaring array with elements equal to number of digits //This loop saves each digit individually in the array (in reverse order) for(int i = 0; i < count; i++){ length[i] = (num%10); num /= 10; } //This loop will reverse the order of the array so that the array is now in the original order of the inputted integer for (int low = 0, high = count-1; low < high; low++, high--){ int temp = length[low]; length[low] = length[high]; length[high] = temp; } int newNum = 0; //This loop converts the array back into an integer for (int i = 0; i < count; i++){ length[i] += 4; if (length[i] >= 10) length[i] = length[i] % 10; newNum = 10 * newNum + length[i]; } return newNum; } //This function takes the integer returned by the add4 function and shifts each of the digits to the left. The first digit becomes the last digit. int shift(int num){ int firstDigit = num/pow(10,count-1); //If the first digit is 0 after add4, the code will ensure that there is no extra 0 added in the code. if (firstDigit == 0){ firstDigit = num/pow(10,count-2); int temp2 = num-(firstDigit*pow(10,count-2)); num = temp2*10+firstDigit; return num; } //This is for all other cases else{ int temp2 = num-(firstDigit*pow(10,count-1)); num = temp2*10+firstDigit; return num; } } //This function prints out the original number as well as the newly encrypted number void printOutput(int encryptNum, int originalNum){ printf("Original number: %d\n", originalNum); printf("Encrypted number: %d\n", encryptNum); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> //DECLARANDO FUNCOES char* diaDaSemana(int); void vendaIngresso(); int verificarEscolha(char escolha); typedef struct comprador{ int assento; int idade; char *estudante; char *professor; double precoIngresso; struct comprador *proximo; }celula; celula *pLista =NULL; int assentos[60]; void initLista(celula **pRecebido); void insertLista(celula **pRecebido); void buscaListaSimples(celula **pRecebido); void removeElementoListaSimples(celula **pRecebido); int leValor(int *valorRecebido); //CONSTANTES SISTEMA int OPC_SYSTEM; int EXIT_PROGRAM = 99; char NOME_PECA[60]; char CLEAR[5]="clear"; //CONSTANTES DIA DA SEMANA int DOMINGO = 0; int SEGUNDA = 1; int TERCA = 2; int QUARTA = 3; int QUINTA = 4; int SEXTA = 5; int SABADO = 6; int DIA_SEMANA =-1; void main() { char opc; DIA_SEMANA = getDiaSemana(); getNomePeca(); do { menu(); printf("DIGITE UMA OPCAO:"); scanf("%d",&OPC_SYSTEM); verificarOpcao(); getchar(); limparTela(); } while(OPC_SYSTEM != EXIT_PROGRAM); } void menu(){ char opc; limparTela(); printf("*********** MENU ***************\n\n"); printf("1 - TABELA DE PRECOS.\n"); printf("2 - VENDER INGRESSO.\n"); printf("3 - LISTAR ASSENTOS.\n"); printf("4 - FLUXO DE COMPRAS.\n\n"); printf("9 - FECHAR.\n\n"); } void getNomePeca(){ printf("DIGITE O NOME DA PECA:"); getchar(); scanf("%[^\n]s", &NOME_PECA); //scanf("%[^\n]",&NOME_PECA); //flush_in(); //getchar(); } void verificarOpcao() { limparTela(); switch(OPC_SYSTEM){ case 1: imprimirTabelaPreco(); break; case 2: vendaIngresso(); break; case 3: listarAssentos(); break; break; case 4: imprimirLista(pLista); break; case 9: OPC_SYSTEM = 99; break; } } void imprimirTabelaPreco(){ printf("+======================================+\n"); printf("| INGRESSOS |\n"); printf("+======================================+\n"); printf("| INTEIRA : R$ 24,00 |\n"); printf("| MEIA : R$ 12,00 |\n"); printf("+======================================+\n\n"); printf("REGRAS INGRESSOS MEIA-ENTRADA:\n\n"); printf("a - ESTUDANTES CRIANCAS DE 2 A 12 ANOS.\n"); printf("b - ADULTOS A PARTIR DOS 60 ANOS.\n"); printf("c - PROFESSORES DA REDE PUBLICA.\n\n"); printf("REGRAS INGRESSOS GRATUITOS:\n\n"); printf("a - ESTUDANTES CARENTES REDE PUBLICA (AS TERCAS-FEIRAS).\n"); getchar(); } char* diaDaSemana(int dia){ char *result; result=malloc(7*sizeof(char)); switch(dia){ case 0: result = "DOMINGO"; break; case 1: result ="SEGUNDA"; break; case 2: result ="TERCA"; break; case 3: result ="QUARTA"; break; case 4: result ="QUINTA"; break; case 5: result ="SEXTA"; break; case 6: result ="SABADO"; break; } return result; } void limparTela() { system(CLEAR); } int getIdade(){ int idade; do{ printf("\nIDADE:"); scanf("%d",&idade); if (idade < 2){ printf("\nENTRADA NAO PERMITIDA PARA MENORES DE 2 ANOS"); } else if(idade > 100) { printf("\nIDADE LIMITE DE 100 ANOS"); } }while(idade < 2 || idade > 100); return idade; } void flush_in() { int ch; while( (ch = fgetc(stdin)) != EOF && ch != '\n' ){} } int isProfessor() { int escolha; do { printf("\nPROFESSOR DE REDE PUBLICA? 1 para (SIM) 0 para (NAO)"); scanf("%d",&escolha); flush_in(); // Limpa o teclado // professor = verificarEscolha(escolha); } while(escolha != 1 && escolha != 0); return escolha; } int diaValido(int dia){ int result = 0; switch(dia){ case 0: case 1: case 2: case 3: case 4: case 5: case 6: result = 1; break; } return result; } //PEGA O DIA DA SEMANA DE ACORDO COM OS VALORES DA CONSTANTES NO TOPO DO ARQUIVO int getDiaSemana(){ int dia; do { printf("\nQUE DIA E HOJE?\n\n"); printf("0-DOMINGO\n"); printf("1-SEGUNDA\n"); printf("2-TERCA\n"); printf("3-QUARTA\n"); printf("4-QUINTA\n"); printf("5-SEXTA\n"); printf("6-SABADO\n"); printf("\nESCOLHA UM DIA:"); scanf("%d",&dia); if(!diaValido(dia)){ printf("\n DIA INCORRETO\n"); } } while(!diaValido(dia)); return dia; } int getAssento() { int assento; int sair =0; int ocupado; char *cadeira =malloc(3*sizeof(char)); do { limparTela(); listarAssentos(); printf("\n\nESCOLHA UM ASSENTO:"); scanf("%d",&assento); if (assento > 0 && assento < 61 ) { if(assentos[assento-1] != 0){ printf("\nCADEIRA OCUPADA\n"); } else { assentos[assento-1] =1; sair =-99; } } }while(sair != -99 ); return assento; } void imprimirTicket(int assento,double valorIngresso) { //ponteiro para struct que armazena data e hora struct tm *data_hora_atual; //variável do tipo time_t para armazenar o tempo em segundos time_t segundos; //obtendo o tempo em segundos time(&segundos); //para converter de segundos para o tempo local //utilizamos a função localtime data_hora_atual = localtime(&segundos); limparTela(); printf("+======================================+\n"); printf("| TICKET |\n"); printf("+======================================+\n"); printf("DATA/HORA:%d/%d/%d %d:%d \n", data_hora_atual->tm_mday, data_hora_atual->tm_mon+1, data_hora_atual->tm_year+1900, data_hora_atual->tm_hour, data_hora_atual->tm_min ); printf("PECA :%s\n",NOME_PECA); printf("ASSENTO:%d\n", assento); printf("PRECO INGRESSO: %.2f\n",valorIngresso); printf("TIPO:%s\n",(valorIngresso == 12.0 ? "MEIA-ENTRADA":valorIngresso ==0.0 ?"GRATUITO":"INTEIRA")); getchar(); } void vendaIngresso(){ char opc='n'; do { limparTela(); printf("+======================================+\n"); printf("| VENDA DE INGRESSOS |\n"); printf("+======================================+\n"); inserirComprador(&pLista); }while(opc =='s'); } int verificarEscolha(char escolha){ int result; printf("VERIFICAR ESCOLHA %d",escolha); switch (escolha){ case 's': case 'S': result = 1; break; case'n': case'N': result = 0; break; } return result; } /* Inicialização da Lista Encadeada */ void initLista(celula **pRecebido){ (*pRecebido)->proximo = NULL; } /* Função para Inserção no Início */ void inserirComprador(celula **pRecebido){ // Declarações celula *temporario; // IDADE DO COMPRADOR. int idade; // RESULTADO PERGUNA PROFESSOR REDE PUBLICA : TRUE OR FALSE int eProfessor=0; int condicaoEspecial = 0; int assento; double valorIngresso; idade =getIdade(); if(idade > 18 && idade < 60){ eProfessor = isProfessor(); } else if(idade >1 && idade < 13 || idade > 59){ condicaoEspecial = 1; } assento = getAssento(); if(idade > 1 && idade < 13){ eProfessor = 0; valorIngresso = DIA_SEMANA == TERCA ? 0.0 : 12.0; } else if(idade > 59 || eProfessor){ valorIngresso = 12.0; } else { valorIngresso = 24.0; } temporario = (celula *)malloc(sizeof(celula)); temporario->idade = idade; temporario->estudante = malloc(3*sizeof(char)) ; temporario->estudante = idade > 1 && idade < 13 ? "SIM" : "NAO"; temporario->professor = malloc(3*sizeof(char)) ; temporario->professor = eProfessor == 0 ? "NAO" : "SIM"; temporario->precoIngresso = valorIngresso; temporario->assento = assento; if(pLista == NULL){ (*pRecebido) = temporario; }else { temporario->proximo = (*pRecebido)->proximo; (*pRecebido)->proximo = temporario; } imprimirTicket(assento,valorIngresso); } void listarAssentos() { int assento; int sair =0; int ocupado; char *cadeira =malloc(3*sizeof(char)); printf("+======================================+\n"); printf("| ASSENTOS |\n"); printf("+======================================+\n\n"); for(int i = 1; i < 61 ; i ++){ ocupado = assentos[i-1] == 0 ? 0 : 1; //cadeira = ocupado == 1 ? "[X]" : "[ ]"; if(ocupado == 1){ cadeira = "[#]"; } else { cadeira ="[ ]"; } if(i % 10 == 0){ printf("%d-%s\n",i,cadeira); }else { printf("%d-%s\t",i,cadeira); } } getchar(); } /* Função para Percorrer Elementos */ /*void buscaListaSimples(celula **pRecebido){ // Declarações celula *temporario; // Instruções if((*pRecebido)->proximo == NULL){ printf("Lista Vazia!\n"); } else{ temporario = (celula *)malloc(sizeof(celula)); temporario = (*pRecebido)->proximo; while(temporario != NULL){ printf("Valor : %d\n", temporario->informacao); temporario = temporario->proximo; } } }*/ /* Remove Elemento da Cabeça */ void removeElementoListaSimples(celula **pRecebido){ // Declarações celula *temporario; // Instruções if((*pRecebido)->proximo == NULL){ printf("\nLista Vazia!"); } else{ temporario = (*pRecebido)->proximo; (*pRecebido)->proximo = temporario->proximo; free(temporario); } } void imprimirLista(celula *p) { limparTela(); printf("%s\n\n",NOME_PECA); double sum =0.0; while(p!=NULL) { printf("ASSENTO:%d\t",p->assento); printf("IDADE:%d\t",p->idade); printf("ESTUDANTE:%s\t",p->estudante); printf("PROFESSOR:%s\t",p->professor); printf("INGRESSO:%.2f",p->precoIngresso); printf("\n"); sum += p->precoIngresso; p=p->proximo; } printf("-----------------------------------------\n\n"); printf("TOTAL: R$ %.2f",sum); getchar(); }
C
#ifndef ASSET_H #define ASSET_H /* * */ #include "common.h" #include <SDL.h> struct asset_t { void *bytes; SDL_Texture *texture; char *name; s32 w, h, c; }; struct asset_container_t { struct asset_t *assets; size_t assets_len, assets_cap; }; // function definition // AssetLoad : loads a single asset from disk s32 AssetLoad(struct asset_container_t *container, char *path); // AssetFetchByName : fetches an asset by name struct asset_t *AssetFetchByName(struct asset_container_t *container, char *name); // AssetsFree : releases all of the resources associated with the asset s32 AssetsFree(struct asset_container_t *container); #endif // ASSET_H
C
/* * @file i2c.c * @brief Source file for controlling the I2C registers * * This header file has functions that initializes the * I2C and connects to the TMP102 temperature sensor, * which then returns the current temperature and the alert * status * * @authors Rahul Ramaprasad, Prayag Milan Desai * @date November 1 2019 * @verison 1.0 */ #include "../CMSIS/MKL25Z4.h" #include <stdio.h> #include "i2c.h" #include "loggerFunctions.h" //Function that terminates program void endProgram(void); //Set up tlow and thigh on boot bool setupOnce = false; //if temperature is -ve bool negative = false; //is POST passed bool postCheck = false; void i2c_master_init() { SIM->SCGC4 |= SIM_SCGC4_I2C1_MASK; //Enabling the clock for I2C module SIM->SCGC5 |= SIM_SCGC5_PORTE_MASK; PORTE->PCR[0] |= PORT_PCR_MUX(6) | 0x03; //SCL PORTE->PCR[1] |= PORT_PCR_MUX(6) | 0x03; //SDA I2C1->F |= I2C_F_MULT(0) | I2C_F_ICR(0x11); //Setting a baud rate of 300kbps I2C1->C1|= I2C_C1_IICEN_MASK;// | I2C_C1_IICIE_MASK; //Enabling I2C module log_message(DEBUG, __func__, "I2C registers initialised"); log_message(TEST, __func__, "I2C registers initialised"); } void start() { I2C1->S |= I2C_S_RXAK_MASK; I2C1->C1 |= I2C_C1_TXAK_MASK; I2C1->C1 |= I2C_C1_TX_MASK; //Enabling transmit mode START; DATA(TMP102_WRITE); //Transmit first byte WAIT; if((I2C1->S & I2C_S_RXAK_MASK) == 0) //Check if slave received a byte { postCheck = true; log_message(DEBUG, __func__, "Temperature Sensor detected"); log_message(TEST, __func__, "Temperature Sensor detected"); I2C1->S |= I2C_S_RXAK_MASK; } else{ log_message(DEBUG, __func__, "No device found"); log_message(TEST, __func__, "No device found"); log_message(NORMAL, __func__, "No device found"); endProgram(); } if(!setupOnce){ RESTART; DATA(TMP102_WRITE); //Transmit first byte WAIT; DATA(TMP102_TLOW); //Send pointer register address of TLow WAIT; DATA(0x00); //Send MSB of TLow WAIT; DATA(0x00); //Send LSB of TLow WAIT; log_message(DEBUG, __func__, "TLOW registers initialised"); log_message(TEST, __func__, "TLOW registers initialised"); //Thigh RESTART; DATA(TMP102_WRITE); //Transmit first byte WAIT; DATA(TMP102_THIGH); //Send pointer register address of Temperature WAIT; DATA(0x00); //Send MSB of THigh WAIT; DATA(0x00); //Send LSB of THigh WAIT; log_message(DEBUG, __func__, "THIGH registers initialised"); log_message(TEST, __func__, "THIGH registers initialised"); setupOnce = true; } } uint16_t read_temp() { uint8_t MSB = 0, LSB = 0; int32_t temp_read = 0; int16_t twos_complement; log_message(DEBUG, __func__, "Reading Temperature"); log_message(TEST, __func__, "Reading Temperature"); RESTART; DATA(TMP102_WRITE); //Transmit first byte WAIT; DATA(TMP102_TEMPERATURE); //Send pointer register address of Temperature WAIT; RESTART; DATA(TMP102_READ); //Read Temperature WAIT; //read mode I2C1->C1 &= ~I2C_C1_TX_MASK; //NACK I2C1->C1 &= ~I2C_C1_TXAK_MASK; //dummy read I2C1->D; WAIT; MSB = I2C1->D; WAIT; STOP; LSB = I2C1->D; if( LSB == 0xFF ) return 0xFFFF; //Return error when it reads reserved value if((MSB & 0x80) == 0) { temp_read = (MSB << 4) | ((LSB >> 4) & 0x0F); //Convert into 12 bit format } else { negative = true; twos_complement = (MSB << 4) | ((LSB >> 4) & 0x0F); //Convert into 12 bit format temp_read = ((~twos_complement) & 0x0FF) +1; //Find twos complement } if( (temp_read/16) < (-45) || (temp_read/16) > 125) //Check if temperature is out of range of sensor { log_message(DEBUG, __func__, "Error in reading temp"); log_message(TEST, __func__, "Error in reading temp"); log_message(NORMAL, __func__, "Error in reading temp"); return 0xFFFF; } else return (temp_read/16); }
C
#include <stdio.h> int main () { long int N, M, aux; while(1){ scanf("%ld %ld", &N, &M); if(N == 0 && M == 0){ break; } aux = (N - M)/2; if(M == 1||M == 4||M == 9||M == 11||M == 16||M == 18||M == 20||M == 22||M == 24||M == 25||M == 26||M == 27||M == 28||M == 29||M == 30||M == 31||M == 32||M == 33||M>=35||N >= 50){ printf("Let me try!\n"); }else if(N >= 9 && (aux%2 != 0)){ printf("Let me try!\n"); }else{ printf("Don't make fun of me!\n"); } } return 0; }
C
/* * project_euler_prob6.c * * Created on: Jul 19, 2012 * Author: ssimmons * Returns difference between sum of squares and square of sum of numbers 1-100 */ #include <stdio.h> #include <math.h> int main(){ int squareofsum = (5050*5050); // a priori knowledge int sumofsquares = 0, i; for (i = 1; i<101; i++) sumofsquares += i*i; printf("The difference is: %d\n", (squareofsum-sumofsquares)); return 0; } // Can do more smartly by realizing undetermined coefficient cubic polynomial will give // Sum of squares from 1 to n
C
// // Created by Administrator on 2019/1/10/010. // #include <time.h> #include "byteutils.h" #ifdef WIN32 #include <Windows.h> #endif // WIN32 int byteutils_get_int(unsigned char* b, int offset) { return ((b[offset + 3] & 0xff) << 24) | ((b[offset + 2] & 0xff) << 16) | ((b[offset + 1] & 0xff) << 8) | (b[offset] & 0xff); } short byteutils_get_short(unsigned char* b, int offset) { return (short) ((b[offset + 1] << 8) | (b[offset] & 0xff)); } float byteutils_get_float(unsigned char* b, int offset) { //unsigned char tmp[4] = {b[offset + 3], b[offset + 2], b[offset + 1], b[offset]}; return *((float *)(b + offset)); } uint64_t byteutils_get_int2(unsigned char* b, int offset) { return ((uint64_t)(b[offset + 3] & 0xff) << 24) | ((uint64_t)(b[offset + 2] & 0xff) << 16) | ((uint64_t)(b[offset + 1] & 0xff) << 8) | ((uint64_t)b[offset] & 0xff); } uint64_t byteutils_get_long(unsigned char* b, int offset) { return (byteutils_get_int2(b, offset + 4)) << 32 | byteutils_get_int2(b, offset); } //s -> us uint64_t ntptopts(uint64_t ntp) { return (((ntp >> 32) & 0xffffffff)* 1000000) + ((ntp & 0xffffffff) * 1000 * 1000 / INT_32_MAX) ; } uint64_t byteutils_read_int(unsigned char* b, int offset) { return ((uint64_t)b[offset] << 24) | ((uint64_t)b[offset + 1] << 16) | ((uint64_t)b[offset + 2] << 8) | ((uint64_t)b[offset + 3] << 0); } //s->us uint64_t byteutils_read_timeStamp(unsigned char* b, int offset) { return (byteutils_read_int(b, offset) * 1000000) + ((byteutils_read_int(b, offset + 4) * 1000000) / INT_32_MAX); } // us time to ntp void byteutils_put_timeStamp(unsigned char* b, int offset, uint64_t time) { // time= ms uint64_t seconds = time / 1000000L; uint64_t microseconds = time - seconds * 1000000L; seconds += OFFSET_1900_TO_1970; // write seconds in big endian format b[offset++] = (uint8_t)(seconds >> 24); b[offset++] = (uint8_t)(seconds >> 16); b[offset++] = (uint8_t)(seconds >> 8); b[offset++] = (uint8_t)(seconds >> 0); uint64_t fraction = microseconds * 0x100000000L / 1000000L; // write fraction in big endian format b[offset++] = (uint8_t)(fraction >> 24); b[offset++] = (uint8_t)(fraction >> 16); b[offset++] = (uint8_t)(fraction >> 8); // low order bits should be random data b[offset++] = (uint8_t)(fraction >> 0); //b[offset++] = (Math.random() * 255.0); } #ifdef WIN32 // https://stackoverflow.com/questions/5404277/porting-clock-gettime-to-windows?r=SearchResults #define CLOCK_PROCESS_CPUTIME_ID 0 LARGE_INTEGER getFILETIMEoffset() { SYSTEMTIME s; FILETIME f; LARGE_INTEGER t; s.wYear = 1970; s.wMonth = 1; s.wDay = 1; s.wHour = 0; s.wMinute = 0; s.wSecond = 0; s.wMilliseconds = 0; SystemTimeToFileTime(&s, &f); t.QuadPart = f.dwHighDateTime; t.QuadPart <<= 32; t.QuadPart |= f.dwLowDateTime; return (t); } int clock_gettime(int X, struct timespec* tv) { LARGE_INTEGER t; FILETIME f; double microseconds; static LARGE_INTEGER offset; static double frequencyToMicroseconds; static int initialized = 0; static BOOL usePerformanceCounter = 0; if (!initialized) { LARGE_INTEGER performanceFrequency; initialized = 1; usePerformanceCounter = QueryPerformanceFrequency(&performanceFrequency); if (usePerformanceCounter) { QueryPerformanceCounter(&offset); frequencyToMicroseconds = (double)performanceFrequency.QuadPart / 1000000.; } else { offset = getFILETIMEoffset(); frequencyToMicroseconds = 10.; } } if (usePerformanceCounter) QueryPerformanceCounter(&t); else { GetSystemTimeAsFileTime(&f); t.QuadPart = f.dwHighDateTime; t.QuadPart <<= 32; t.QuadPart |= f.dwLowDateTime; } t.QuadPart -= offset.QuadPart; microseconds = (double)t.QuadPart / frequencyToMicroseconds; t.QuadPart = (LONGLONG)microseconds; tv->tv_sec = (long)(t.QuadPart / 1000000); tv->tv_nsec = t.QuadPart % 1000000; return (0); } #endif // WIN32 uint64_t now_us() { struct timespec time; clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time); return (uint64_t)time.tv_sec * 10000000L + (uint64_t)(time.tv_nsec / 1000); }
C
#include "param.h" #include "types.h" #include "defs.h" #include "x86.h" #include "memlayout.h" #include "mmu.h" #include "proc.h" #include "spinlock.h" struct { struct spinlock lock; struct shm_page { uint id; char *frame; int refcnt; } shm_pages[64]; } shm_table; void shminit() { int i; initlock(&(shm_table.lock), "SHM lock"); acquire(&(shm_table.lock)); for (i = 0; i< 64; i++) { shm_table.shm_pages[i].id =0; shm_table.shm_pages[i].frame =0; shm_table.shm_pages[i].refcnt =0; } release(&(shm_table.lock)); } int shm_open(int id, char **pointer) { // you write this // Look through the shm_table to see if the id we are opening already exists int i = 0; int index = -1; acquire(&(shm_table.lock)); for (i=0; i<64; i++){ if(shm_table.shm_pages[i].id == id){ index = i; break; } } struct proc* p = myproc(); if(index > -1){ // Case 1 mappages(p->pgdir, (void*)PGROUNDUP(p->sz), PGSIZE, V2P(shm_table.shm_pages[index].frame), PTE_W|PTE_U); shm_table.shm_pages[index].refcnt++; *pointer=(char *)PGROUNDUP(p->sz); // p->sz += PGSIZE; } else{ // Case 2 for(i = 0; i<64; i++){ if(shm_table.shm_pages[i].id == 0){ shm_table.shm_pages[i].id = id; shm_table.shm_pages[i].frame = kalloc(); shm_table.shm_pages[i].refcnt = 1; memset(shm_table.shm_pages[i].frame, 0, PGSIZE); mappages(p->pgdir, (void*)(p->sz), PGSIZE, V2P(shm_table.shm_pages[i].frame), PTE_W|PTE_U); *pointer=(char *)PGROUNDUP(p->sz); p->sz += PGSIZE; break; } } } release(&(shm_table.lock)); return 0; //added to remove compiler warning -- you should decide what to return } int shm_close(int id) { int i=0; initlock(&(shm_table.lock), "SHM lock"); acquire(&(shm_table.lock)); for (i=0; i<64; i++){ if(shm_table.shm_pages[i].id == id){ shm_table.shm_pages[i].refcnt--; if(shm_table.shm_pages[i].refcnt == 0){ shm_table.shm_pages[i].id =0; shm_table.shm_pages[i].frame =0; } break; } } release(&(shm_table.lock)); return 0; //added to remove compiler warning -- you should decide what to return }
C
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #include "sport.h" void mostarDeporte(edeportes sport) { printf(" %d %s\n", sport.id, sport.descripcion); } int mostrarDeportes(edeportes sport[], int tam) { int error = -1; if(sport != NULL && tam > 0) { printf("***** Listado de deportes ******\n"); printf("----------------------------------\n"); printf(" ID Descripcion\n\n"); printf("------------------------------------\n"); for(int i=0; i<tam ; i++) { mostarDeporte(sport[i]); } printf("\n\n"); error = 0; } return error; }
C
#include "header.h" int ft_strcmp(char *s1, char *s2) { int i; i = 0; while (s1[i] != '\0' || s2[i] != '\0') { if (s1[i] == s2[i]) i++; else if (s1[i] > s2[i]) return (s1[i] - s2[i]); else if (s1[i] < s2[i]) return (s1[i] - s2[i]); } return (0); } char *read_input() { char ch; char *str; int i; str = (char*)malloc(3000 * sizeof(char)); i = 0; while (read(STDIN_FILENO, &ch, 1) > 0 && ch != '\0') { write(1, &ch, 1); str[i] = ch; i++; } str[i] = '\0'; return (str); } void ft_countdim(char *str, int *rows, int *cols) { int i; int check; i = 0; *rows = 0; *cols = 0; check = 0; while (str[i] != '\0') { if (str[i] == '\n') { *rows = *rows + 1; check = 1; } if (check == 0 && str[i] != '\n') *cols = *cols + 1; i++; } } char *get_r(int i, int rows, int cols) { if (i == 0) rush00(rows, cols); else if(i == 1) rush01(rows, cols); else if(i == 2) rush02(rows, cols); else if(i == 3) rush03(rows, cols); else if(i == 4) rush04(rows, cols); return (read_input()); } void solve(char *str) { int rows; int cols; int i; char *s; i = 0; ft_countdim(str, &rows, &cols); while (i < 5) { s = get_r(i, rows, cols); if (ft_strcmp(str, s) == 0) { //print answer here } i++; } } int main(int argc, char *argv[]) { char *input; input = read_input(); solve(input); free(input); return (0); }
C
/* * options.c * * Created on: Nov 27, 2013 * Author: DiamondS */ #include <stdio.h> #include <stdlib.h> #include <getopt.h> #include "options.h" #include "types.h" void OPTIONS_Init(options_t *options, int argc, char *argv[]) { int nextOption; const char *shortOptions = "hVdcgirtw"; const struct option longOptions[] = { { "port", required_argument, NULL, 'p' }, { "debug", no_argument, NULL, 'd' }, { "config", no_argument, NULL, 'c' }, { "gps", no_argument, NULL, 'g' }, { "indication", no_argument, NULL, 'i' }, { "remote", no_argument, NULL, 'r' }, { "tcp", no_argument, NULL, 't' }, { "wheel", no_argument, NULL, 'w' }, { "Version", no_argument, NULL, 'V' }, { "help", no_argument, NULL, 'h' }, { NULL, no_argument, NULL, 0 } }; options->debug = FALSE; options->debugConfig = FALSE; options->debugGps = FALSE; options->debugIndication = FALSE; options->debugRemote = FALSE; options->debugTcpServer = FALSE; options->debugWheel = FALSE; do { nextOption = getopt_long(argc, argv, shortOptions, longOptions, NULL); switch (nextOption) { case 'd': options->debug = TRUE; break; case 'c': options->debugConfig = TRUE; options->debug = TRUE; break; case 'g': options->debugGps = TRUE; options->debug = TRUE; break; case 'i': options->debugIndication = TRUE; options->debug = TRUE; break; case 'r': options->debugRemote = TRUE; options->debug = TRUE; break; case 't': options->debugTcpServer = TRUE; options->debug = TRUE; break; case 'w': options->debugWheel = TRUE; options->debug = TRUE; break; case 'V': OPTIONS_PrintVersion(stdout, 0); break; case 'h': OPTIONS_PrintUsage(stdout, 0, argv); break; case '?': OPTIONS_PrintUsage(stderr, 1, argv); break; case -1: break; default: abort(); break; } } while (nextOption != -1); return; } void OPTIONS_PrintUsage(FILE *stream, int exitCode, char *argv[]) { fprintf(stream, "\nUsage:\n %s options\n", argv[0]); fprintf(stream, "\n" "Debug:\n" " -d, --debug Debug mode;\n" " -c, --config Debug Configuration;\n" " -g, --gps Debug GPS;\n" " -i, --indication Debug Indication.\n" " -r, --remote Debug Remote.\n" " -t, --tcp Debug TCP Server.\n" " -w, --wheel Debug Wheels.\n"); fprintf(stream, "\n" "OPtions:\n" " -V, --version Version;\n" " -h, --help Display this usage information.\n" "\n"); exit(exitCode); } void OPTIONS_PrintVersion(FILE *stream, int exitCode) { fprintf(stream, "Version: %s v%d.%d.%d.%d %s\n", OPTIONS_SOFTWARE_NAME, OPTIONS_SOFTWARE_MAJOR, OPTIONS_SOFTWARE_MINOR, OPTIONS_SOFTWARE_MAINTENANCE, OPTIONS_SOFTWARE_BUILD, OPTIONS_SOFTWARE_EDITION); exit(exitCode); }
C
#include <stdio.h> #include <conio.h> int main(){ int uzun,kisa; printf("Uzun kenar yildiz adedini giriniz: "); scanf("%d", &uzun); printf("Kisa kenar yildiz adedini giriniz: "); scanf("%d", &kisa); for(int i=0; i<kisa; i++){ for(int j=0; j<i; j++){ printf(" "); } for(int j=0; j<uzun; j++){ printf("*"); } printf("\n"); } getch(); }
C
#include <stdio.h> #include <stdlib.h> int main (void) { execv("print",NULL); printf("Returned from execv call.\n"); return 0; }
C
#include "elf64.h" size_t elf64_hash(const unsigned char* name) { size_t h = 0, g; while (*name) { h = (h << 4) + *name++; if ((g = h & 0xf0000000) != 0) { h ^= g >> 24; } h &= 0x0fffffff; } return h; }
C
/* C 标准库的 float.h 头文件包含了一组与浮点值相关的依赖于平台的常量。 这些常量是由 ANSI C 提出的,这让程序更具有可移植性。 在讲解这些常量之前,最好先弄清楚浮点数是由下面四个元素组成的 S 符号 ( +/- ) b 指数表示的基数,2 表示二进制,10 表示十进制,16 表示十六进制,等等... e 指数,一个介于最小值 emin 和最大值 emax 之间的整数。 p 精度,基数 b 的有效位数 floating-point = ( S ) p * b^e */ #include <stdio.h> #include <float.h> int main(void) { printf("The maximum value of float = %.10e\n", FLT_MAX); printf("The minimum value of float = %.10e\n", FLT_MIN); printf("The number of digits in the number = %.10e\n", FLT_MANT_DIG); }
C
#include "bzpartial.h" #include "bzextract.h" #include <string.h> #include <stdio.h> #include <expat.h> #include <getopt.h> #include <assert.h> #include <unistd.h> void bze_help(char *name) { fprintf(stderr, "usage: %s [-i offset] [-s skip] [-c count] file.bz2\n", name); fprintf(stderr, "version: 0.2\n"); fprintf(stderr, "options:\n"); fprintf(stderr, "\t -i bits \t\tnumbers of bits to skip while opening a given .bz2 (bit_offset).\n"); fprintf(stderr, "\t -s count \t\tdont include the count of extracted bytes in the output (byte_count).\n"); fprintf(stderr, "\t -c count \t\tstop after writing given count of bytes to the output (byte_count).\n"); fprintf(stderr, "\t -m \t\tmachine parsable, binary output\t\t\n"); } int main(int argc, char **argv) { int c; struct bze_options_t opts; opts.start_bit = 0; opts.seek_bytes = 0; opts.stop_bytes = -1; opts.output_type = OUT_SIMPLE; opts.write_fun = bze_write_stdout_fun;; opts.write_opts = NULL; while ((c = getopt(argc, argv, ":vhmi:s:c:")) != -1) { switch (c) { case 'v': bze_help(argv[0]); return 0; case 'h': bze_help(argv[0]); return 0; case 'i': sscanf(optarg, "%lu", &opts.start_bit); break; case 's': sscanf(optarg, "%lu", &opts.seek_bytes); break; case 'c': sscanf(optarg, "%lu", &opts.stop_bytes); break; case 'm': opts.output_type = OUT_TAGGED; break; default: bze_help(argv[0]); return 1; } } if (optind != (argc - 1)) { bze_help(argv[0]); return 1; }; opts.fn = argv[optind]; // fprintf(stderr, "Starting %s with bit=%lu, seek=%lu, count=%lu\n", opts.fn, // opts.start_bit, opts.seek_bytes, opts.stop_bytes); return bze_extract_data(&opts); }
C
#include<stdio.h> int main() { int x = 9;//ʹʹӡո񷽱 for (int i = 0; i < 9; i++)//9Уѭ9 { for (int j = x; j>0; j--)//ӡոÿοոһ { printf(" "); } x--;//ʹӡĿոÿμһ for (int m = 0; m <= i * 2; m++)//ӡ * ÿ { printf("*"); } printf("\n");// } //ʼӡ ӡ9УҪôһУҪôһ һУ8 int l = 2; for (int i = 8; i >0; i--)//ӡ8 { for (int j = 0; j<l; j++)//ӡո { printf(" "); } l++; for (int m = 0; m<i * 2 - 1; m++)//ӡ* { printf("*"); } printf("\n"); } getchar(); return 0; }
C
/* Implement a function which checks whether a string appears as a substring in another string. It should return 1 if the string occurs and 0 if it does not. Its declaration could be: int strsearch(char * src, char * substr); */ #include <stdio.h> #include <stdlib.h> int strsearch(char *src, char *substr); int main() { printf("%d\n", strsearch("SoftUni", "Soft")); printf("%d\n", strsearch("Hard Rock", "Rock")); printf("%d\n", strsearch("Ananas", "nasa")); printf("%d\n", strsearch("Coolness", "cool")); return (EXIT_SUCCESS); } int strsearch(char *src, char *substr) { if (*substr == '\0') { return 0; } if (*src == '\0') { return 0; } char *start = src; char *p; while (*start != '\0') { p = start; char *q = substr; while (*p != '\0' && *q != '\0' && *p == *q) { p++; q++; } if (*q == '\0') { return 1; } start++; } return 0; }
C
#include<stdio.h> int main() { int n; abc: printf("Enter value: "); scanf("%d",&n); if(n!=20){ goto abc; } printf("\n%d\n",n); return 0; }
C
//Programme to find the Sine Series #include<stdio.h> #include<stdlib.h> int main() { int loop,n; float val1,sum=0,term; printf("The sine series will be \n"); for(loop=0;loop<=360;loop=loop+30) { val1=loop*3.1415/180;//Changing into redian term=val1; sum=val1; n=1; while((term>0.00001)||(term<-0.00001)) { term=(-1)*val1*val1*term/((2*n)*(2*n+1));//Relation Equation n++; sum+=term; } printf("\t\tSine(%d)=%f",loop,sum); printf("\n"); } return 0; }
C
#ifndef __MP_HASHMAP__ #define __MP_HASHMAP__ #include <stddef.h> #include <stdint.h> /* PROBLEM: * The hashmap does not own the items added to it * When using put(...), the key and the value should be copied and pointers to that should be stored in the linked list. When clearing, these pointers should be freed. * This allows types like 'char *' to be safely added and freed */ typedef uint64_t hash_t; // must be a power of 2 #define __MP_HASHMAP_DEFAULT_BUCKETS__ (16) #define __MP_HASHMAP_DEFAULT_BUCKET_LOAD__ (0.90) typedef char * mkey_t; typedef int value_t; typedef struct __MP_HASHMAP_NODE__ { struct __MP_HASHMAP_NODE__ * next; mkey_t key; value_t value; } mp_hashmap_node; typedef struct __MP_HASHMAP__ { /* An array of pointers to the heads of singly linked lists. Each node of these singly linked lists contains a key, value pair. This also allows a bucket value to be NULL, so it is known when the bucket is not in use. */ mp_hashmap_node ** buckets; // Total buckets allocated size_t total_buckets; // Buckets that are being used size_t used_buckets; // If (used_buckets/total_buckets) >= max_bucket_load, // allocate more buckets const float max_bucket_load; // Total number of elements size_t length; // Hash function hash_t (*to_hash)(const mkey_t *); // Key Equals int (*key_equals)(const mkey_t *, const mkey_t *); // Value Equals int (*value_equals)(const value_t *, const value_t *); } mp_hashmap; /* Create a hashmap given a hashing function for key type. */ mp_hashmap mphm_create( hash_t (*to_hash)(const mkey_t *), int (*key_equals)(const mkey_t *, const mkey_t *), int (*value_equals)(const value_t *, const value_t *) ); // Returns if a hasmap is empty (has any elements) int mphm_is_empty(mp_hashmap *); // Returns if a hashmap is valid (buckets aren't null) int mphm_is_valid(mp_hashmap *); // Clears all the buckets present void mphm_clear(mp_hashmap *); // Frees (and invalidates) a map void mphm_free(mp_hashmap *); /* Get a pointer to a value for a given key. NULL if key not present */ value_t * mphm_get(mp_hashmap *, mkey_t); /* Check if a hashmap contains a key. */ int mphm_contains(mp_hashmap *, mkey_t); /* Check if a hashmap contains a value. */ int mphm_contains_value(mp_hashmap *, value_t); /* Puts a value in a given key. This is the only function that allows the addition of key value pairs. Returns 1 if the key had not been present. */ int mphm_put(mp_hashmap *, mkey_t, value_t); /* Removes a key, value pair based on its key. Returns 1 if the key was present and was removed */ int mphm_remove(mp_hashmap *, mkey_t); /* Removes key value pairs based on their values. Returns 0 if no pairs were removed. Returns the number of pairs that were removed otherwise. */ int mphm_remove_value(mp_hashmap *, value_t); /* Given a map and a new bucket count, setup the buckets based on the given map's current key, value pairs. The given map's current data will be freed and replaced with the new length, used & total buckets, and bucket array. */ void mphm_resize(mp_hashmap *, size_t); #endif
C
// Write a program that converts strings to integer and floating point numbers // and calculates the sum of these converted numbers. // The strings represent integer or floating point numbers #include <stdio.h> #include <stdlib.h> #define SIZE 6 // function for converting from string to floating point numbers double StringToFloat(char *string[], char **remainingPtr); // function for converting from string to long integer numbers long StringToInteger(char *string[], char **remainingPtr, int base); int main() { char *float_string[SIZE] = {"1.5","2.5","3.65","7.35","4.20","4.8"}; char *integer_string[SIZE] = {"700","2000","1500","800","6000","2000"}; char *remainingStringPtr; double d = StringToFloat(float_string, &remainingStringPtr); long e = StringToInteger(integer_string, &remainingStringPtr, 0); } double StringToFloat(char *string[], char **remainingPtr) { double sum = 0.0; double average = 0.0; for (size_t i = 0; i < SIZE; ++i) { printf("The value: %.2f \n", strtod(string[i], remainingPtr)); sum += strtod(string[i], remainingPtr); } average = sum/SIZE; printf("The sum: %.2f and The average: %.2f \n", sum, average); return sum; } long StringToInteger(char *string[], char **remainingPtr, int base) { long sum = 0; double average = 0.0; for (size_t i = 0; i < SIZE; ++i) { printf("The value: %lu \n", strtol(string[i], remainingPtr, base)); sum += strtol(string[i], remainingPtr, base); } average = sum/SIZE; printf("The sum: %lu and The average: %.1f \n", sum, average); return sum; }